PresencePeriod.py 8.01 KB
Newer Older
1
# -*- coding: utf-8 -*-
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
##############################################################################
#
# Copyright (c) 2006,2007 Nexedi SARL and Contributors. All Rights Reserved.
#                    Rafael Monnerat <rafael@nexedi.com>
#                    Courteaud Romain <romain@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

34
from Products.ERP5Type import Permissions, PropertySheet
35
from Products.ERP5.mixin.periodicity import PeriodicityMixin
36
from Products.ERP5.Document.Movement import Movement
37
from Products.ERP5Type.DateUtils import addToDate
38

39
class PresencePeriod(Movement, PeriodicityMixin):
40
  """
41
  Presence Period is used to add available time of the user in a
42 43 44
  period of Time
  """

45 46
  meta_type = 'ERP5 Presence Period'
  portal_type = 'Presence Period'
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

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

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Amount
                    , PropertySheet.Task
                    , PropertySheet.Movement
                    , PropertySheet.Arrow
                    , PropertySheet.Periodicity
                    , PropertySheet.Path
Romain Courteaud's avatar
Romain Courteaud committed
63
                    , PropertySheet.SortIndex
64 65 66 67 68 69 70 71 72 73 74 75 76 77
                    )

  security.declareProtected(Permissions.AccessContentsInformation,
                            'isAccountable')
  def isAccountable(self):
    """
    For now, consider that it's always accountable
    """
    return 1

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getInventoriatedQuantity')
  def getInventoriatedQuantity(self, default=None, *args, **kw):
    """
78 79
    Surcharged accessor to calculate the Quantity in second
    from stop date and start date values.
80 81 82
    """
    quantity = self.getQuantity(*args, **kw)
    if quantity in [None, 0]:
83 84
      calendar_start_date = self.getStartDate()
      calendar_stop_date = self.getStopDate()
85 86 87 88 89 90 91 92 93 94 95 96
      if (calendar_start_date is not None) and (calendar_stop_date is not None):
        # Convert Days to second
        quantity = int(calendar_stop_date) - int(calendar_start_date)
      else:
        quantity = default
    return quantity

  security.declareProtected( Permissions.AccessContentsInformation,
                             'asMovementList')
  def asMovementList(self):
    """
    Generate multiple movement from a single one.
97
    It is used for cataloging a movement multiple time in
98 99 100
    the movement/stock tables.

    Ex: a movement have multiple destinations.
101
    asMovementList returns a list a movement context with different
102 103 104
    single destination.
    """
    result = []
105 106 107 108 109 110 111 112 113
    if self.getDestinationUid() is None:
      return result
    group_calendar = self.getParentValue()
    presence_period_list = group_calendar.objectValues(portal_type="Group Presence Period")
    for presence_period in presence_period_list:
      for from_date, to_date in presence_period._getDatePeriodList():
        if from_date.greaterThanEqualTo(self.getStartDate()) and to_date.lessThanEqualTo(self.getStopDate() or group_calendar.getStopDate()):
          result.append(self.asContext(self, start_date=to_date, stop_date=from_date))

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
    return result

  def _getDatePeriodList(self):
    """
    Get all periods between periodicity start date
    and periodicity stop date
    """
    result = []
    exception_value_list = self.contentValues(portal_type="Calendar Exception")
    exception_date_list = [x.getExceptionDate() \
                                       for x in exception_value_list]
    exception_date_list = [x for x in exception_date_list if x is not None]
    exception_date_list.sort()
    if len(exception_date_list) != 0:
      current_exception_date = exception_date_list.pop(0).Date()
    else:
      current_exception_date = None

    start_date = self.getStartDate()
    if start_date is not None:
      stop_date = self.getStopDate(start_date)
      periodicity_stop_date = self.getPeriodicityStopDate(
                                          start_date)
137
      second_duration = int(stop_date) - int(start_date)
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
      if second_duration > 0:
        # First date has to respect the periodicity config
        next_start_date = self.getNextPeriodicalDate(start_date-1)
        while (next_start_date is not None) and \
          (next_start_date <= periodicity_stop_date):

          # Check that next_start_date is not an exception
          if (current_exception_date is not None) and \
             (current_exception_date == next_start_date.Date()):
              # We match an exception date
              # So, don't return this value
              # Update the next exception date
              if len(exception_date_list) != 0:
                current_exception_date = exception_date_list.pop(0).Date()
              else:
                current_exception_date = None
          elif (current_exception_date is not None) and \
             (current_exception_date < next_start_date.Date()):
            # SQL method don't like iterator
  #             yield (next_start_date, next_start_date+duration)
158
            result.append([next_start_date,
159
               addToDate(next_start_date, second=second_duration)])
160 161 162 163 164 165
            # Update the next exception date
            if len(exception_date_list) != 0:
              current_exception_date = exception_date_list.pop(0).Date()
            else:
              current_exception_date = None
          else:
166 167
            # SQL method don't like iterator
  #             yield (next_start_date, next_start_date+duration)
168
            result.append([next_start_date,
169 170
               addToDate(next_start_date, second=second_duration)])
          next_start_date = self.getNextPeriodicalDate(next_start_date)
171 172 173

    return result

174
  def getNextPeriodicalDate(self, current_date, next_start_date=None):
175 176
    """
    Get the next date where this periodic event should start.
177 178 179 180 181

    XXX It completely reimplements the PeriodictyMixin method because
    the minimal duration between dates is day, and not minute
    Better way would be to improve the API of getNextPeriodicalDate,
    and optimize addToDate method.
182
    """
183
    # XXX Copy/Paste from PeriodicityMixin
184 185 186 187 188 189
    if next_start_date is None:
      next_start_date = current_date
    if next_start_date > current_date:
      return
    else:
      # Make sure the old date is not too far away
190 191
      day_count = int(current_date-next_start_date)
      next_start_date = next_start_date + day_count
192

193
    next_start_date = addToDate(next_start_date, day=1)
194
    while 1:
195 196 197
      if (self._validateDay(next_start_date)) and \
         (self._validateWeek(next_start_date)) and \
         (self._validateMonth(next_start_date)):
198 199
        break
      else:
200
        next_start_date = addToDate(next_start_date, day=1)
201
    return next_start_date