Commit a515e43f authored by Sebastien Robin's avatar Sebastien Robin

moved many utils methods related to date into ERP5Type.DateUtils


git-svn-id: https://svn.erp5.org/repos/public/erp5/trunk@1799 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent b6debe61
...@@ -34,24 +34,22 @@ from DateTime import DateTime ...@@ -34,24 +34,22 @@ from DateTime import DateTime
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.XMLObject import XMLObject from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type.DateUtils import addToDate, getClosestDate, getIntervalBetweenDates, roundMonthToGreaterEntireYear
from Products.ERP5Type.DateUtils import getMonthAndDaysBetween, getCompletedMonthBetween, getRoundedMonthBetween
from Products.ERP5Type.DateUtils import getMonthFraction, getYearFraction, getDecimalNumberOfYearsBetween
from Products.ERP5Type.DateUtils import same_movement_interval, number_of_months_in_year, centis, millis
from Products.ERP5.Document.Amount import Amount from Products.ERP5.Document.Amount import Amount
from Products.CMFCore.WorkflowCore import WorkflowMethod from Products.CMFCore.WorkflowCore import WorkflowMethod
from Products.CMFCore.utils import getToolByName from Products.CMFCore.utils import getToolByName
from Products.ERP5.Document.Immobilisation import Immobilisation from Products.ERP5.Document.Immobilisation import Immobilisation
from Products.ERP5.Document.AmortisationRule import AmortisationRule #from Products.ERP5.Document.AmortisationRule import AmortisationRule
from Products.ERP5.ERP5Globals import movement_type_list from Products.ERP5.ERP5Globals import movement_type_list
from DateTime import DateTime
from zLOG import LOG from zLOG import LOG
INFINITESIMAL_DELAY = 0.00001
class Item(XMLObject, Amount): class Item(XMLObject, Amount):
""" """
Items in ERP5 are intended to provide a way to track objects Items in ERP5 are intended to provide a way to track objects
XXX All constants should be first moved into central place
""" """
meta_type = 'ERP5 Item' meta_type = 'ERP5 Item'
...@@ -129,12 +127,10 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -129,12 +127,10 @@ Items in ERP5 are intended to provide a way to track objects."""
### Amortisation ### Amortisation
security.declareProtected(Permissions.View, 'getImmobilisationMovementValueList')
security.declareProtected(Permissions.View, 'getImmobilisationMovementList') def getImmobilisationMovementValueList(self, from_date=None, to_date=None, sort_on="stop_date", filter_valid=1, owner_change=1, **kw):
def getImmobilisationMovementList(self, from_date=None, to_date=None, sort_on="stop_date", filter_valid=1, owner_change=1, **kw): """
""" Returns a list of immobilisation movements applied to current item from date to date Returns a list of immobilisation movements applied to current item from date to date
XXX Remove LOGs please
XXX Rename using ValueList
""" """
accessor = 'get' accessor = 'get'
if sort_on is not None: if sort_on is not None:
...@@ -165,31 +161,24 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -165,31 +161,24 @@ Items in ERP5 are intended to provide a way to track objects."""
depth = kw.get('depth', None) depth = kw.get('depth', None)
if depth is None: depth = 0 if depth is None: depth = 0
LOG('Item :', 0, 'getImmobilisationMovementList called. from_date = %s, to_date = %s, owner_change = %s' % (repr(from_date), repr(to_date), repr(owner_change)))
immobilisation_list = [] immobilisation_list = []
for immobilisation in self.contentValues(filter = { 'portal_type':'Immobilisation' } ): for immobilisation in self.contentValues(filter = { 'portal_type':'Immobilisation' } ):
LOG('Item, immobilisation.checkConsistency',0,immobilisation.checkConsistency())
if filter_valid: if filter_valid:
invalid = immobilisation.isNotValid() invalid = immobilisation._checkConsistency() #
LOG('Item :', 0, 'immobilisation %s ; filter_valid = 1, invalid=%s' % (repr(immobilisation), repr(invalid)))
else: else:
invalid = 0 invalid = 0
LOG('Item :', 0, 'immobilisation %s ; filter_valid = 0, invalid=0' % repr(immobilisation))
if not invalid: if not invalid:
LOG('Item :', 0, 'immobilisation %s is not invalid' % repr(immobilisation))
immo_date = immobilisation.getStopDate() immo_date = immobilisation.getStopDate()
if ( to_date is None or immo_date - to_date <= 0 ) and \ if ( to_date is None or immo_date - to_date <= 0 ) and \
( from_date is None or immo_date - from_date >= 0 ): ( from_date is None or immo_date - from_date >= 0 ):
immobilisation_list.append(immobilisation) immobilisation_list.append(immobilisation)
LOG('Item :', 0, 'immobilisation %s appended' % repr(immobilisation)) LOG('Item.immobilisation_list',0,immobilisation_list)
else:
LOG('Item %s :' % repr(self), 0, 'Immobilisation movement %s is not valid : %s' % (repr(immobilisation), repr(invalid)))
# Look for each change of ownership and an immobilisation movement within 1 hour # Look for each change of ownership and an immobilisation movement within 1 hour
# If found, adapt the immobilisation date to be correctly interpreted # If found, adapt the immobilisation date to be correctly interpreted
# If not found, and owner_change set to 1, create a context immobilisation movement # If not found, and owner_change set to 1, create a context immobilisation movement
ownership_list = self.getOwnerList(to_date) ownership_list = self.getSectionList(to_date)
LOG('Item :', 0, 'ownership list at date %s = %s' % (repr(to_date), repr(ownership_list)))
for ownership in ownership_list: for ownership in ownership_list:
owner_date = ownership['date'] owner_date = ownership['date']
found_immo = None found_immo = None
...@@ -199,49 +188,33 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -199,49 +188,33 @@ Items in ERP5 are intended to provide a way to track objects."""
immobilisation = immobilisation_list[i] immobilisation = immobilisation_list[i]
my_date = immobilisation.getStopDate() my_date = immobilisation.getStopDate()
# if nearest_immo is None:
# nearest_immo = immobilisation
# nearest_date = nearest_immo.getStopDate()
if (my_date is not None) and (my_date - owner_date < 0) and (nearest_immo is None or nearest_immo.getStopDate() - my_date < 0): if (my_date is not None) and (my_date - owner_date < 0) and (nearest_immo is None or nearest_immo.getStopDate() - my_date < 0):
nearest_immo = immobilisation nearest_immo = immobilisation
if (my_date is not None) and abs(owner_date - my_date) < 1/24.: if (my_date is not None) and abs(owner_date - my_date) < same_movement_interval:
found_immo = immobilisation found_immo = immobilisation
i += 1 i += 1
LOG('Item :', 0, 'ownership %s... found_immo = %s, owner_change = %s, nearest_immo = %s' % (repr(ownership), repr(found_immo), repr(owner_change), repr(nearest_immo)))
if found_immo is None and owner_change and nearest_immo is not None: if found_immo is None and owner_change and nearest_immo is not None:
immobilisation = nearest_immo immobilisation = nearest_immo
if nearest_immo is not None: if nearest_immo is not None:
added_immo = None added_immo = None
LOG('Item :', 0, 'immobilisation_list before asContext = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
added_immo = immobilisation.asContext() added_immo = immobilisation.asContext()
LOG('Item :', 0, 'immobilisation_list after asContext = %s (depth %s)' % (repr(immobilisation_list), repr(depth))) added_immo.setStopDate(owner_date + millis)
added_immo.setStopDate(owner_date + 0.000001) # XXX constant in code
if added_immo.getImmobilisation(): if added_immo.getImmobilisation():
vat = immobilisation.getVat() vat = immobilisation.getVat()
LOG('Item :', 0, 'immobilisation_list before subcall = %s (depth %s)' % (repr(immobilisation_list), repr(depth))) previous_value = immobilisation.getAmortisationOrDefaultAmortisationPrice()
previous_value = immobilisation.getAmortisationOrDefaultAmortisationValue() current_value = added_immo.getDefaultAmortisationPrice(depth = depth + 1)
LOG('Item :', 0, 'immobilisation_list between subcalls = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
current_value = added_immo.getDefaultAmortisationValue(depth = depth + 1)
LOG('Item :', 0, 'immobilisation_list after subcall = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
added_immo.setInputAccount(added_immo.getOutputAccount()) added_immo.setInputAccount(added_immo.getOutputAccount())
added_immo.setAmortisationValue(current_value) added_immo.setAmortisationBeginningPrice(current_value)
LOG('Item :', 0, 'immobilisation_list before 2nd subcall = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
added_immo.setAmortisationDuration(added_immo.getDefaultAmortisationDuration(depth = depth + 1)) added_immo.setAmortisationDuration(added_immo.getDefaultAmortisationDuration(depth = depth + 1))
LOG('Item :', 0, 'immobilisation_list after 2nd subcall = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
added_immo.setVat( vat * current_value / previous_value ) added_immo.setVat( vat * current_value / previous_value )
LOG('Item :', 0, 'immobilisation_list before append = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
immobilisation_list.append(added_immo) immobilisation_list.append(added_immo)
found_immo = added_immo found_immo = added_immo
LOG('Item :', 0, 'added immobilisation %s : %s (depth %s)' % (repr(added_immo), repr(added_immo.showDict()), repr(depth)))
LOG('Item :', 0, 'immobilisation_list = %s (depth %s)' % (repr(immobilisation_list), repr(depth)))
if found_immo is not None: if found_immo is not None:
# Two cases : # Two cases :
...@@ -252,54 +225,51 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -252,54 +225,51 @@ Items in ERP5 are intended to provide a way to track objects."""
found_date = found_immo.getStopDate() found_date = found_immo.getStopDate()
if found_immo.getImmobilisation(): if found_immo.getImmobilisation():
if found_date - owner_date < 0: if found_date - owner_date < 0:
found_immo.setStopDate(owner_date + 0.00001) # XXX Is this good ? found_immo.setStopDate(owner_date + centis)
else: else:
if found_date - owner_date > 0: if found_date - owner_date > 0:
found_immo.setStopDate(owner_date - 0.00001) found_immo.setStopDate(owner_date - centis)
if sort_on is not None: if sort_on is not None:
immobilisation_list.sort(cmpfunc) immobilisation_list.sort(cmpfunc)
LOG('Item :', 0, 'returned immobilisation movement list = %s' % repr(immobilisation_list))
return immobilisation_list return immobilisation_list
security.declareProtected(Permissions.View, 'getUnfilteredImmobilisationMovementList') security.declareProtected(Permissions.View, 'getUnfilteredImmobilisationMovementValueList')
def getUnfilteredImmobilisationMovementList(self, from_date=None, to_date=None, sort_on="stop_date", owner_change=0, **kw): def getUnfilteredImmobilisationMovementValueList(self, from_date=None, to_date=None, sort_on="stop_date", owner_change=0, **kw):
""" """
Returns a list of immobilisation applied to the current item from date to date Returns a list of immobilisation applied to the current item from date to date
All of the movements are returned, not even those which are valid All of the movements are returned, not even those which are valid
XXX Rename using ValueList
""" """
return self.getImmobilisationMovementList(from_date=from_date, return self.getImmobilisationMovementValueList(from_date=from_date,
to_date=to_date, to_date=to_date,
sort_on=sort_on, sort_on=sort_on,
owner_change=owner_change, owner_change=owner_change,
filter_valid=0, **kw) filter_valid=0, **kw)
security.declareProtected(Permissions.View, 'getPastImmobilisationMovementList') security.declareProtected(Permissions.View, 'getPastImmobilisationMovementValueList')
def getPastImmobilisationMovementList(self, from_date=None, at_date=None, sort_on="stop_date", owner_change=1, **kw): def getPastImmobilisationMovementValueList(self, from_date=None, at_date=None, sort_on="stop_date", owner_change=1, **kw):
""" Returns a list of immobilisation movements applied to current item before the given date, or now """
XXX Rename using ValueList Returns a list of immobilisation movements applied to current item before the given date, or now
""" """
if at_date is None: at_date = DateTime() if at_date is None: at_date = DateTime()
result = self.getImmobilisationMovementList(from_date = from_date, result = self.getImmobilisationMovementValueList(from_date = from_date,
to_date = at_date, to_date = at_date,
sort_on = sort_on, sort_on = sort_on,
owner_change = owner_change, **kw ) owner_change = owner_change, **kw )
return result return result
security.declareProtected(Permissions.View, 'getFutureImmobilisationMovementList') security.declareProtected(Permissions.View, 'getFutureImmobilisationMovementValueList')
def getFutureImmobilisationMovementList(self, to_date=None, at_date=None, sort_on="stop_date", owner_change=1, **kw): def getFutureImmobilisationMovementValueList(self, to_date=None, at_date=None, sort_on="stop_date", owner_change=1, **kw):
""" Returns a list of immobilisation movements applied to current item after the given date, or now """
XXX Rename using ValueList Returns a list of immobilisation movements applied to current item after the given date, or now
""" """
if at_date is None: at_date = DateTime() if at_date is None: at_date = DateTime()
result = self.getImmobilisationMovementList(from_date = at_date, result = self.getImmobilisationMovementValueList(from_date = at_date,
to_date = to_date, to_date = to_date,
sort_on = sort_on, sort_on = sort_on,
owner_change = owner_change, **kw) owner_change = owner_change, **kw)
...@@ -307,17 +277,16 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -307,17 +277,16 @@ Items in ERP5 are intended to provide a way to track objects."""
security.declareProtected(Permissions.View, 'getLastImmobilisationMovement') security.declareProtected(Permissions.View, 'getLastImmobilisationMovementValue')
def getLastImmobilisationMovement(self, at_date=None, owner_change=1, **kw): def getLastImmobilisationMovementValue(self, at_date=None, owner_change=1, **kw):
""" Returns the last immobilisation movement before the given date, or now """
XXX Rename using Value Returns the last immobilisation movement before the given date, or now
""" """
result_sql = self.getPastImmobilisationMovementList(at_date = at_date, owner_change=owner_change, **kw) result_sql = self.getPastImmobilisationMovementValueList(at_date = at_date, owner_change=owner_change, **kw)
result = None result = None
if len(result_sql) > 0: if len(result_sql) > 0:
result = result_sql[-1] result = result_sql[-1]
return result return result
...@@ -328,7 +297,7 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -328,7 +297,7 @@ Items in ERP5 are intended to provide a way to track objects."""
Returns total duration of amortisation for the item. Returns total duration of amortisation for the item.
It is the theorical lifetime of this type of item. It is the theorical lifetime of this type of item.
""" """
last_immobilisation_movement = self.getLastImmobilisationMovement(at_date = at_date, owner_change=owner_change, **kw) last_immobilisation_movement = self.getLastImmobilisationMovementValue(at_date = at_date, owner_change=owner_change, **kw)
if last_immobilisation_movement is not None: if last_immobilisation_movement is not None:
return last_immobilisation_movement.getAmortisationOrDefaultAmortisationDuration() return last_immobilisation_movement.getAmortisationOrDefaultAmortisationDuration()
else: else:
...@@ -348,7 +317,6 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -348,7 +317,6 @@ Items in ERP5 are intended to provide a way to track objects."""
return not self.isCurrentlyImmobilised(**kw) return not self.isCurrentlyImmobilised(**kw)
security.declareProtected(Permissions.View, 'isImmobilised') security.declareProtected(Permissions.View, 'isImmobilised')
def isImmobilised(self, at_date=None, **kw): def isImmobilised(self, at_date=None, **kw):
""" Returns true if the item is immobilised at the given date. """ Returns true if the item is immobilised at the given date.
...@@ -356,13 +324,13 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -356,13 +324,13 @@ Items in ERP5 are intended to provide a way to track objects."""
if at_date is not None: if at_date is not None:
is_immobilised = 0 is_immobilised = 0
last_immobilisation_movement = self.getLastImmobilisationMovement(at_date = at_date, **kw) last_immobilisation_movement = self.getLastImmobilisationMovementValue(at_date = at_date, **kw)
if last_immobilisation_movement is not None: if last_immobilisation_movement is not None:
is_immobilised = last_immobilisation_movement.getImmobilisation() is_immobilised = last_immobilisation_movement.getImmobilisation()
else: else:
past_immobilisation_movement_list = self.getPastImmobilisationMovementList(at_date = DateTime(), **kw) past_immobilisation_movement_list = self.getPastImmobilisationMovementValueList(at_date = DateTime(), **kw)
for past_immobilisation in past_immobilisation_movement_list: for past_immobilisation in past_immobilisation_movement_list:
if past_immobilisation.getImmobilisation(): if past_immobilisation.getImmobilisation():
return 1 return 1
...@@ -376,7 +344,6 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -376,7 +344,6 @@ Items in ERP5 are intended to provide a way to track objects."""
return self.getRemainingAmortisationDuration(at_date = DateTime(), **kw) return self.getRemainingAmortisationDuration(at_date = DateTime(), **kw)
security.declareProtected(Permissions.View, 'getRemainingAmortisationDuration') security.declareProtected(Permissions.View, 'getRemainingAmortisationDuration')
def getRemainingAmortisationDuration(self, at_date=None, from_immobilisation=0, **kw): def getRemainingAmortisationDuration(self, at_date=None, from_immobilisation=0, **kw):
""" """
...@@ -390,13 +357,12 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -390,13 +357,12 @@ Items in ERP5 are intended to provide a way to track objects."""
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
# Find the latest movement whose immobilisation is true # Find the latest movement whose immobilisation is true
if from_immobilisation: if from_immobilisation:
my_at_date = at_date - INFINITESIMAL_DELAY my_at_date = at_date - centis
else: else:
my_at_date = at_date my_at_date = at_date
immobilisation_movements = self.getPastImmobilisationMovementList(at_date = my_at_date, **kw) immobilisation_movements = self.getPastImmobilisationMovementValueList(at_date = my_at_date, **kw)
i = len(immobilisation_movements) - 1 i = len(immobilisation_movements) - 1
while i >= 0 and not immobilisation_movements[i].getImmobilisation(): while i >= 0 and not immobilisation_movements[i].getImmobilisation():
i -= 1 i -= 1
...@@ -421,10 +387,8 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -421,10 +387,8 @@ Items in ERP5 are intended to provide a way to track objects."""
immo_period_start_date = start_movement.getStopDate() immo_period_start_date = start_movement.getStopDate()
immo_period_remaining = start_movement.getAmortisationOrDefaultAmortisationDuration() immo_period_remaining = start_movement.getAmortisationOrDefaultAmortisationDuration()
immo_period_duration = immo_period_stop_date - immo_period_start_date immo_period_duration = getRoundedMonthBetween(immo_period_start_date, immo_period_stop_date)
remaining_time = (immo_period_remaining * 30.4375) - immo_period_duration # XXXX returned_value = immo_period_remaining - immo_period_duration
returned_value = round(remaining_time / 30.4375) # XXXX
if returned_value < 0: if returned_value < 0:
returned_value = 0 returned_value = 0
...@@ -443,75 +407,24 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -443,75 +407,24 @@ Items in ERP5 are intended to provide a way to track objects."""
If with_currency is set, returns a string containing the value and the corresponding currency. If with_currency is set, returns a string containing the value and the corresponding currency.
""" """
def changeDateYear(date, new_year): def calculateProrataTemporis(immo_period_start_date, immo_period_stop_date, raw_annuity_value=0, amortisation_type='degressive', financial_date=None):
"""
Return the given date modified so that its year is new_year
"""
if new_year is not None:
return DateTime( str(int(new_year)) + "/" + str(date.month()) + "/" + str(date.day()) )
else:
return date
def calculateProrataTemporis(annuity_duration=0, raw_annuity_value=0, amortisation_type='degressive', immo_period_stop_date=None, immo_period_start_date=None, financial_date=None):
""" """
Returns the value of the annuity respecting to the amortisation Returns the value of the annuity respecting to the amortisation
duration during this annuity. duration during this annuity.
For linear amortisation, immo_period_start_date and immo_period_stop_date
are absolutely needed
XXX Please define a generic function which calculates number of months
between 2 dates according to fiscal rules
XXX Please put duration calculation code oustide calculation - such
methods might be useful in other places and might be different
from one fiscal system to another
""" """
if (immo_period_stop_date is not None) and (immo_period_start_date is not None):
annuity_duration = immo_period_stop_date - immo_period_start_date
if amortisation_type == 'degressive': if amortisation_type == 'degressive':
month_value = raw_annuity_value / 12. # XXX Same code seems repeated many times month_value = raw_annuity_value / number_of_months_in_year
month_number = round(annuity_duration / 30.4375,1) duration = getMonthAndDaysBetween(immo_period_start_date, immo_period_stop_date)
if abs(month_number - round(month_number)) <= 0.15: month_number = duration['month']
month_number = round(month_number) day_number = duration['day']
else:
month_number = int(month_number)
# days_remaining should always be 0 annuity_value = month_value * (month_number + getMonthFraction(immo_period_stop_date, day_number))
days_remaining = int(annuity_duration - month_number * 30.4375)
if days_remaining < 3:
days_remaining = 0
annuity_value = month_value * month_number + (raw_annuity_value * days_remaining / 365.25)
return annuity_value return annuity_value
else: else:
# Linear amortisation : it is calculated on days, # Linear amortisation : it is calculated on days,
# unlike degressive amortisation which is calculated on months # unlike degressive amortisation which is calculated on months
# immo_period_stop_date, financial_date AND immo_period_start_date MUST NOT be None return getDecimalNumberOfYearsBetween(immo_period_start_date, immo_period_stop_date, financial_date) * raw_annuity_value
years = 0
current_date = changeDateYear(financial_date, immo_period_start_date.year())
if current_date - immo_period_start_date < 0:
current_date = changeDateYear(current_date, current_date.year() + 1)
if immo_period_stop_date - current_date < 0:
current_date = immo_period_stop_date
annuity_duration = round(current_date - immo_period_start_date)
current_date = changeDateYear(current_date, current_date.year() + 1)
while immo_period_stop_date - current_date >= 0:
years += 1
current_date = changeDateYear(current_date, current_date.year() + 1)
current_date = changeDateYear(current_date, current_date.year() - 1)
annuity_duration += round(immo_period_stop_date - current_date)
prorata_temporis = annuity_duration / 365.
LOG('Item :', 0, 'prorata_temporis = %s, annuity_duration = %s, start_date=%s, stop_date=%s' % (repr(prorata_temporis), repr(annuity_duration), repr(immo_period_start_date), repr(immo_period_stop_date)))
if abs(prorata_temporis - 1.) < .003: prorata_temporis = 1.
annuity_value = (years + prorata_temporis) * raw_annuity_value
return annuity_value
if at_date is None: if at_date is None:
at_date = DateTime() at_date = DateTime()
...@@ -519,11 +432,10 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -519,11 +432,10 @@ Items in ERP5 are intended to provide a way to track objects."""
if from_immobilisation: if from_immobilisation:
# We need to exclude the immobilisation movement which calls currently the method, # We need to exclude the immobilisation movement which calls currently the method,
# unless the method will never end # unless the method will never end
my_at_date = at_date - 0.00001 my_at_date = at_date - centis
else: else:
my_at_date = at_date my_at_date = at_date
immobilisation_movements = self.getPastImmobilisationMovementValueList(at_date = my_at_date, **kw)
immobilisation_movements = self.getPastImmobilisationMovementList(at_date = my_at_date, **kw)
length = len(immobilisation_movements) length = len(immobilisation_movements)
i = length - 1 i = length - 1
...@@ -534,16 +446,16 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -534,16 +446,16 @@ Items in ERP5 are intended to provide a way to track objects."""
# Neither of past immobilisation movements did immobilise the item... # Neither of past immobilisation movements did immobilise the item...
LOG ('ERP5 Warning :',0,'Neither of past immobilisation movements did immobilise the item %s' % self.getTitle()) LOG ('ERP5 Warning :',0,'Neither of past immobilisation movements did immobilise the item %s' % self.getTitle())
if length > 0: if length > 0:
returned_value = immobilisation_movements[-1].getAmortisationOrDefaultAmortisationValue() returned_value = immobilisation_movements[-1].getAmortisationOrDefaultAmortisationPrice()
if with_currency: if with_currency:
return '%s %s' % (repr(returned_value), immobilisation_movements[-1].getCurrency()) return '%s %s' % (repr(returned_value), immobilisation_movements[-1].getPriceCurrency())
return returned_value return returned_value
return None # XXX How to find the buy value ? return None # XXX How to find the buy value ?
# Find the latest immobilisation period and gather information # Find the latest immobilisation period and gather information
start_movement = immobilisation_movements[i] start_movement = immobilisation_movements[i]
currency = start_movement.getCurrency() currency = start_movement.getPriceCurrency()
if currency is not None: if currency is not None:
currency = currency.split('/')[-1] currency = currency.split('/')[-1]
immo_period_start_date = start_movement.getStopDate() immo_period_start_date = start_movement.getStopDate()
...@@ -554,23 +466,18 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -554,23 +466,18 @@ Items in ERP5 are intended to provide a way to track objects."""
stop_movement = immobilisation_movements[i+1] stop_movement = immobilisation_movements[i+1]
immo_period_stop_date = stop_movement.getStopDate() immo_period_stop_date = stop_movement.getStopDate()
start_value = start_movement.getAmortisationOrDefaultAmortisationValue() start_value = start_movement.getAmortisationOrDefaultAmortisationPrice()
immo_period_remaining_months = start_movement.getAmortisationOrDefaultAmortisationDuration() immo_period_remaining_months = start_movement.getAmortisationOrDefaultAmortisationDuration()
immo_period_remaining = immo_period_remaining_months * 30.4375
raw_immo_period_duration = immo_period_stop_date - immo_period_start_date
immo_period_duration = round( (raw_immo_period_duration) / 365.25, 2 ) * 365.25
organisation = start_movement.getOrganisation()
LOG('Item :', 0, 'organisation for item %s on date %s is %s' % (repr(self), repr(immo_period_start_date), repr(organisation)))
financial_date = organisation.getFinancialYearEndDate()
section = start_movement.getSectionValue()
financial_date = section.getFinancialYearStopDate()
# Calculate the amortisation value # Calculate the amortisation value
amortisation_type = start_movement.getAmortisationType() amortisation_type = start_movement.getAmortisationType()
if amortisation_type == "linear": if amortisation_type == "linear":
# Linear amortisation prorata temporis calculation is made on a number of days # Linear amortisation prorata temporis calculation is made on a number of days
# unlike degressive amortisation, made on a number of months # unlike degressive amortisation, made on a number of months
raw_annuity_value = start_value / (immo_period_remaining_months / 12.) raw_annuity_value = start_value / (immo_period_remaining_months / number_of_months_in_year)
annuity_value = calculateProrataTemporis(raw_annuity_value=raw_annuity_value, annuity_value = calculateProrataTemporis(raw_annuity_value=raw_annuity_value,
amortisation_type='linear', amortisation_type='linear',
immo_period_stop_date=immo_period_stop_date, immo_period_stop_date=immo_period_stop_date,
...@@ -585,6 +492,10 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -585,6 +492,10 @@ Items in ERP5 are intended to provide a way to track objects."""
elif amortisation_type == "degressive": elif amortisation_type == "degressive":
if financial_date is None:
LOG('ERP5 Warning :', 100, 'Organisation object "%s" has no financial date.' % (repr(section.getTitle()),))
return None
# Degressive amortisation is made on entire annuities, unless the first. # Degressive amortisation is made on entire annuities, unless the first.
# So, saying we immobilise on 114 months as degressive amortisation is meaningless : # So, saying we immobilise on 114 months as degressive amortisation is meaningless :
# in fact, we immobilise on 120 months. # in fact, we immobilise on 120 months.
...@@ -593,128 +504,65 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -593,128 +504,65 @@ Items in ERP5 are intended to provide a way to track objects."""
# amortisation, the immobilisation can not be stopped and restarted. # amortisation, the immobilisation can not be stopped and restarted.
# However, if we immobilised the item during an incomplete year before, we also round the # However, if we immobilised the item during an incomplete year before, we also round the
# remaining period of immobilisation # remaining period of immobilisation
if int(immo_period_remaining_months / 12) != immo_period_remaining_months / 12.: immo_period_remaining_months = roundMonthToGreaterEntireYear(immo_period_remaining_months)
immo_period_remaining = ( int(immo_period_remaining/365.25) + 1 ) * 365.25
immo_period_remaining_months = (int(immo_period_remaining_months / 12) + 1) * 12
# Degressive amortisation is taken in account on months, and not on days. # Degressive amortisation is taken in account on months, and not on days.
# So we need to adjust the immobilisation period start and stop date so that # So we need to adjust the immobilisation period start and stop date so that
# they are at the beginning of a month (a month of financial year - i.e. if # they are at the beginning of a month (a month of financial year - i.e. if
# the financial year date end is March 15th, immobilisation start date is fixed # the financial year date end is March 15th, immobilisation start date is fixed
# to previous 15th, and immobilisation stop date is fixed to next 15th # to previous 15th, and immobilisation stop date is fixed to next 15th
immo_period_start_date = getClosestDate(target_date=immo_period_start_date, date=financial_date, precision='month')
financial_day = financial_date.day() immo_period_stop_date = getClosestDate(target_date=immo_period_stop_date, date=financial_date, precision='month', before=0)
start_day = immo_period_start_date.day()
stop_day = immo_period_stop_date.day()
fiscal_coef = start_movement.getFiscalCoefficient()
if start_day != financial_day:
if start_day > financial_day:
immo_period_start_date = immo_period_start_date - (start_day - 1)
start_month = immo_period_start_date.month()
start_year = immo_period_start_date.year()
immo_period_start_date = DateTime(str(start_year) + '/' + str(start_month) + '/' + str(financial_day))
if stop_day != financial_day:
if stop_day > financial_day:
immo_period_stop_date = immo_period_stop_date + (32 - stop_day)
stop_month = immo_period_stop_date.month()
stop_year = immo_period_stop_date.year()
immo_period_stop_date = DateTime(str(stop_year) + '/' + str(stop_month) + '/' + str(financial_day))
raw_immo_period_duration = immo_period_stop_date - immo_period_start_date
immo_period_duration = round( (raw_immo_period_duration) / 365.25, 2 ) * 365.25
# Get the first financial end date before the beginning of the immobilisation period # Get the first financial end date before the beginning of the immobilisation period
if financial_date is None: # and the last financial date after the end of the immobilisation period.
LOG('ERP5 Warning :', 100, 'Organisation object "%s" has no financial date.' % (repr(organisation.getTitle()),)) first_financial_date = getClosestDate(target_date=immo_period_start_date, date=financial_date, precision='year')
return None last_financial_date = getClosestDate(target_date=immo_period_stop_date, date=financial_date, precision='year', before=0)
financial_date = changeDateYear(financial_date, immo_period_start_date.year())
if DateTime(financial_date.Date()) - DateTime(immo_period_start_date.Date()) > 0:
financial_date = changeDateYear(financial_date, financial_date.year()-1)
first_financial_date = financial_date
financial_date = changeDateYear(financial_date, financial_date.year()+1)
is_last_amortisation_period = 0 is_last_amortisation_period = 0
# Get the last financial date before the end of the immobilisation period.
# Since we are in degressive amortisation, the total time of annuities is less than
# the total time of immobilisation, so we use the financial date BEFORE the end
# of the amortisation
last_financial_date = changeDateYear(financial_date, immo_period_stop_date.year())
if DateTime(last_financial_date.Date()) - DateTime(immo_period_stop_date.Date()) > 0:
last_financial_date = changeDateYear(last_financial_date, last_financial_date.year()-1)
# Adjust the immobilisation period stop date and last financial date # Adjust the immobilisation period stop date and last financial date
# if the current period exceeds the regular immobilisation period # if the current period exceeds the regular immobilisation period
if last_financial_date.year() - first_financial_date.year() >= immo_period_remaining_months / 12.: month_difference = getIntervalBetweenDates(first_financial_date, last_financial_date, {'month':1} )['month']
financial_date_difference = int(immo_period_remaining_months/12) if month_difference >= immo_period_remaining_months:
last_financial_date = changeDateYear(financial_date, first_financial_date.year() + financial_date_difference) last_financial_date = addToDate(last_financial_date, {'month':immo_period_remaining_months} )
is_last_amortisation_period = 1 is_last_amortisation_period = 1
immo_period_stop_date = last_financial_date immo_period_stop_date = last_financial_date
entire_annuities_duration = (last_financial_date.year() - first_financial_date.year()) * 365.25 #entire_annuities_duration = (last_financial_date.year() - first_financial_date.year()) * 365.25
# Find the degressive coefficient # Find the degressive coefficient
if immo_period_remaining: fiscal_coef = start_movement.getFiscalCoefficient()
normal_amortisation_coefficient = 365.25 / immo_period_remaining normal_amortisation_coefficient = 1./ getYearFraction(first_financial_date, months=immo_period_remaining_months)
else:
normal_amortisation_coefficient = 1
degressive_coef = normal_amortisation_coefficient * fiscal_coef degressive_coef = normal_amortisation_coefficient * fiscal_coef
# Find the duration on which we calculate amortisation
immo_period_duration = last_financial_date - immo_period_start_date
duration_difference = entire_annuities_duration - immo_period_duration
if duration_difference > 0:
if immo_period_stop_date != last_financial_date and entire_annuities_duration > 0 and not is_last_amortisation_period:
remaining_duration = changeDateYear(last_financial_date, last_financial_date.year()+1) - immo_period_start_date
else:
remaining_duration = immo_period_duration
else:
remaining_duration = entire_annuities_duration
# First annuity is particular since we use prorata temporis ratio
annuities = 0 # Cumulated annuities value annuities = 0 # Cumulated annuities value
if DateTime(financial_date.Date()) - DateTime(immo_period_stop_date.Date()) < 0: if getIntervalBetweenDates(first_financial_date, last_financial_date, {'day':1})['day'] > 0:
annuity_end_date = financial_date # First annuity is particular since we use prorata temporis ratio
else: second_financial_date = addToDate(first_financial_date, {'year':1})
if getIntervalBetweenDates(immo_period_stop_date, second_financial_date, {'days':1}) < 0:
annuity_end_date = immo_period_stop_date annuity_end_date = immo_period_stop_date
else:
annuity_end_date = second_financial_date
if normal_amortisation_coefficient <= round(degressive_coef, 2): if normal_amortisation_coefficient <= round(degressive_coef, 2):
applied_coef = degressive_coef applied_coef = degressive_coef
else: else:
applied_coef = normal_amortisation_coefficient applied_coef = normal_amortisation_coefficient
raw_annuity_value = start_value * applied_coef raw_annuity_value = start_value * applied_coef
annuity_value = calculateProrataTemporis(immo_period_start_date, annuity_end_date, raw_annuity_value=raw_annuity_value)
first_annuity_duration = annuity_end_date - immo_period_start_date
annuity_value = calculateProrataTemporis(annuity_duration=first_annuity_duration, raw_annuity_value=raw_annuity_value)
annuities += annuity_value annuities += annuity_value
remaining_duration -= first_annuity_duration
remaining_duration = round(remaining_duration / 365.25, 2) * 365.25 # XXX PLEASE MOVE TO GLOBALS OR BETTER
remaining_immobilisation = immo_period_remaining - 365.25
linear_coef = 0 linear_coef = 0
current_financial_date = second_financial_date
# Other annuities # Other annuities
if remaining_duration > remaining_immobilisation: while current_financial_date < last_financial_date:
remaining_duration = remaining_immobilisation remaining_months = immo_period_remaining_months - getIntervalBetweenDates(first_financial_date,
if remaining_duration >= 365.25: current_financial_date, {'month':1})['month']
while remaining_duration > 0:
if not linear_coef: if not linear_coef:
# Linear coef has not been set yet, so we have to check # Linear coef has not been set yet, so we have to check
# if it is time to use it or not # if it is time to use it or not
current_value = start_value - annuities current_value = start_value - annuities
linear_coef = 365.25 / remaining_immobilisation linear_coef = 1./ getYearFraction(last_financial_date, months=remaining_months)
if linear_coef <= round(degressive_coef, 2): if linear_coef <= round(degressive_coef, 2):
applied_coef = degressive_coef applied_coef = degressive_coef
linear_coef = 0 linear_coef = 0
...@@ -723,23 +571,17 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -723,23 +571,17 @@ Items in ERP5 are intended to provide a way to track objects."""
else: else:
applied_coef = linear_coef applied_coef = linear_coef
raw_annuity_value = current_value * applied_coef raw_annuity_value = current_value * applied_coef
if remaining_duration <= 365.25: if (not is_last_amortisation_period) and \
getIntervalBetweenDates(current_financial_date, last_financial_date, {'year':1} )['year'] == 1:
# It is the last annuity of the period. If we enter in this statement, it means # It is the last annuity of the period. If we enter in this statement, it means
# the amortisation stops, but the item is not fully amortised # the amortisation stops, but the item is not fully amortised
my_financial_date = changeDateYear(last_financial_date, last_financial_date.year()-1) annuity_value = calculateProrataTemporis(current_financial_date,immo_period_stop_date,raw_annuity_value=raw_annuity_value)
annuity_duration = immo_period_stop_date - my_financial_date
if annuity_duration > 366:
annuity_duration = immo_period_stop_date - last_financial_date
annuity_value = calculateProrataTemporis(annuity_duration=annuity_duration, raw_annuity_value=raw_annuity_value)
else: else:
annuity_value = raw_annuity_value annuity_value = raw_annuity_value
annuities += annuity_value annuities += annuity_value
remaining_duration -= 365.25 current_financial_date = addToDate(current_financial_date, {'year':1} )
remaining_immobilisation -= 365.25
# Return the calculated value # Return the calculated value
returned_value = start_value - annuities returned_value = start_value - annuities
...@@ -754,28 +596,21 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -754,28 +596,21 @@ Items in ERP5 are intended to provide a way to track objects."""
LOG('ERP5 Warning :', 0, 'Unknown amortisation type. (%s)' % (repr(amortisation_type),)) LOG('ERP5 Warning :', 0, 'Unknown amortisation type. (%s)' % (repr(amortisation_type),))
return None return None
security.declareProtected(Permissions.View, 'getCurrentAmortisationPrice') security.declareProtected(Permissions.View, 'getCurrentAmortisationPrice')
def getCurrentAmortisationPrice(self, with_currency=0, **kw): def getCurrentAmortisationPrice(self, with_currency=0, **kw):
""" Returns the deprecated value of item at current time """ """ Returns the deprecated value of item at current time """
return self.getAmortisationPrice (at_date = DateTime(), with_currency=with_currency, **kw) return self.getAmortisationPrice (at_date = DateTime(), with_currency=with_currency, **kw)
security.declareProtected(Permissions.ModifyPortalContent, 'immobilise') security.declareProtected(Permissions.ModifyPortalContent, 'immobilise')
def immobilise(self, **kw): def immobilise(self, **kw):
""" Create the immobilisation movement to immobilise the item """ """ Create the immobilisation movement to immobilise the item """
return self._createImmobilisationMovement(immobilisation_state = 1, **kw) return self._createImmobilisationMovement(immobilisation_state = 1, **kw)
security.declareProtected(Permissions.ModifyPortalContent, 'unimmobilise') security.declareProtected(Permissions.ModifyPortalContent, 'unimmobilise')
def unimmobilise(self, **kw): def unimmobilise(self, **kw):
""" Create the immobilisation movement to unimmobilise the item """ """ Create the immobilisation movement to unimmobilise the item """
return self._createImmobilisationMovement(immobilisation_state = 0, **kw) return self._createImmobilisationMovement(immobilisation_state = 0, **kw)
security.declareProtected(Permissions.ModifyPortalContent, '_createImmobilisationMovement') security.declareProtected(Permissions.ModifyPortalContent, '_createImmobilisationMovement')
def _createImmobilisationMovement(self, immobilisation_state, **kw): def _createImmobilisationMovement(self, immobilisation_state, **kw):
""" Build a new Immobilisation Movement into the current Item """ """ Build a new Immobilisation Movement into the current Item """
...@@ -789,10 +624,8 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -789,10 +624,8 @@ Items in ERP5 are intended to provide a way to track objects."""
return 1 return 1
security.declareProtected(Permissions.ModifyPortalContent, '_createAmortisationRule')
def _createAmortisationRule(self):
security.declareProtected(Permissions.ModifyPortalContent, '_createAmortisationSimulation')
def _createAmortisationSimulation(self):
my_applied_rule_list = self.getCausalityRelatedValueList(portal_type='Applied Rule') my_applied_rule_list = self.getCausalityRelatedValueList(portal_type='Applied Rule')
if len(my_applied_rule_list) == 0: if len(my_applied_rule_list) == 0:
# Create a new applied order rule (portal_rules.order_rule) # Create a new applied order rule (portal_rules.order_rule)
...@@ -808,41 +641,32 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -808,41 +641,32 @@ Items in ERP5 are intended to provide a way to track objects."""
else: else:
# Delete first rules and re expand if possible # Delete first rules and re expand if possible
for my_applied_rule in my_applied_rule_list[:-1]: for my_applied_rule in my_applied_rule_list[:-1]:
#my_applied_rule.flushActivity(invoke=0) XXX FORBIDDEN, now we use hasActivity to verify,
# but we don't flush
my_applied_rule.aq_parent._delObject(my_applied_rule.getId()) my_applied_rule.aq_parent._delObject(my_applied_rule.getId())
my_applied_rule = my_applied_rule_list[-1] my_applied_rule = my_applied_rule_list[-1]
# We are now certain we have a single applied rule # We are now certain we have a single applied rule
# It is time to expand it # It is time to expand it
LOG('Item :',0, 'expanding applied rule %s... causality=%s' % (repr(my_applied_rule), repr(my_applied_rule.getCausalityValue())))
LOG('Item :',0, 'item %s : causality related value list = %s' % (repr(self), repr(self.getCausalityRelatedValueList())))
my_applied_rule.expand() my_applied_rule.expand()
def expandAmortisation(self): def expandAmortisation(self):
""" """
Calculate the amortisation annuities for the item Calculate the amortisation annuities for the item
""" """
self.activate().immediateExpandAmortisation() self.activate().immediateExpandAmortisation()
def immediateExpandAmortisation(self): def immediateExpandAmortisation(self):
""" """
Calculate the amortisation annuities for the item Calculate the amortisation annuities for the item
""" """
self._createAmortisationSimulation() self._createAmortisationRule()
security.declareProtected(Permissions.View, 'getOwnershipChangeList') security.declareProtected(Permissions.View, 'getSectionChangeValueList')
def getOwnershipChangeList(self, at_date=None): def getSectionChangeValueList(self, at_date=None):
""" """
Return the list of deliveries which change the item ownership Return the list of deliveries which change the item ownership
If at_date is None, return the result for all the time If at_date is None, return the result for all the time
XXX To add : a verification on delivery state XXX To add : a verification on delivery state ; does an item belong to
XXX JPS : please explain in detail above XXX the destination section of a delivery if this delivery is on draft state ?
XXX PLease rename to getSectionChangeList or getSectionChangeValueList
""" """
def cmpfunc(a,b): def cmpfunc(a,b):
""" """
...@@ -862,7 +686,6 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -862,7 +686,6 @@ Items in ERP5 are intended to provide a way to track objects."""
raw_list = self.getAggregateRelatedValueList() raw_list = self.getAggregateRelatedValueList()
LOG('Item.getOwnershipChangeList :', 0, "raw_list = %s" % repr(raw_list))
delivery_list = [] delivery_list = []
for movement in raw_list: for movement in raw_list:
if movement.getPortalType() in movement_type_list: if movement.getPortalType() in movement_type_list:
...@@ -872,7 +695,6 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -872,7 +695,6 @@ Items in ERP5 are intended to provide a way to track objects."""
date = movement.getParent().getStopDate() date = movement.getParent().getStopDate()
except: except:
pass pass
LOG('Item.getOwnershipChangeList :', 0, 'movement %s, date is %s (at_date=%s)' % (repr(movement), repr(date), repr(at_date)))
if date is not None and (at_date is None or date - at_date <= 0): if date is not None and (at_date is None or date - at_date <= 0):
current_owner = movement.getDestinationSectionValue() current_owner = movement.getDestinationSectionValue()
previous_owner = movement.getSourceSectionValue() previous_owner = movement.getSourceSectionValue()
...@@ -887,7 +709,6 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -887,7 +709,6 @@ Items in ERP5 are intended to provide a way to track objects."""
except: except:
pass pass
LOG('Item :', 0, 'ownership... current_owner = %s, previous_owner = %s' % (repr(current_owner), repr(previous_owner)))
if current_owner is not None and previous_owner != current_owner: if current_owner is not None and previous_owner != current_owner:
delivery_list.append(movement) delivery_list.append(movement)
...@@ -895,50 +716,37 @@ Items in ERP5 are intended to provide a way to track objects.""" ...@@ -895,50 +716,37 @@ Items in ERP5 are intended to provide a way to track objects."""
return delivery_list return delivery_list
security.declareProtected(Permissions.View, 'getSectionList')
def getSectionList(self, at_date=None):
security.declareProtected(Permissions.View, 'getOwnerList')
def getOwnerList(self, at_date=None):
""" """
Return the list of successive owners of the item with Return the list of successive owners of the item with
the corresponding dates the corresponding dates
If at_date is None, return the result all the time If at_date is None, return the result all the time
XXX getSectionValueList
""" """
delivery_list = self.getOwnershipChangeList(at_date = at_date) delivery_list = self.getSectionChangeValueList(at_date = at_date)
owner_list = [] owner_list = []
for delivery in delivery_list: for delivery in delivery_list:
owner_list.append( { 'owner' : delivery.getDestinationSectionValue(), 'date' : delivery.getStopDate() } ) owner_list.append( { 'owner' : delivery.getDestinationSectionValue(), 'date' : delivery.getStopDate() } )
LOG('Item :', 0, 'owner list at date %s = %s' % (repr(at_date), repr(owner_list)))
return owner_list return owner_list
security.declareProtected(Permissions.View, 'getSectionValue')
security.declareProtected(Permissions.View, 'getOwner') def getSectionValue(self, at_date=None):
def getOwner(self, at_date=None):
""" """
Return the owner of the item at the given date Return the owner of the item at the given date
If at_date is None, return the last owner without time limit If at_date is None, return the last owner without time limit
XXX getSectionValue
""" """
owner_list = self.getOwnerList(at_date = at_date) owner_list = self.getSectionList(at_date = at_date)
if len(owner_list) > 0: if len(owner_list) > 0:
LOG('Item :', 0, 'owner at date %s is %s' % (repr(at_date), repr(owner_list[-1]['owner'])))
return owner_list[-1]['owner'] return owner_list[-1]['owner']
else: else:
return None return None
security.declareProtected(Permissions.View, 'getCurrentSectionValue')
def getCurrentSectionValue(self):
security.declareProtected(Permissions.View, 'getCurrentOwner')
def getCurrentOwner(self):
""" """
Return the current owner of the item Return the current owner of the item
XXX getCurrentSectionValue
""" """
return self.getOwner( at_date = DateTime() ) return self.getSectionValue( at_date = DateTime() )
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment