BusinessProcess.py 13.8 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5
##############################################################################
#
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
6
#                    Yusuke Muraoka <yusuke@nexedi.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
##############################################################################

from AccessControl import ClassSecurityInfo
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
32
from Products.ERP5Type import Permissions, PropertySheet, interfaces
33 34 35
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Document.Path import Path

36 37
import zope.interface

38 39 40 41 42
class BusinessProcess(Path, XMLObject):
  """
    The BusinessProcess class is a container class which is used
    to describe business processes in the area of trade, payroll
    and production.
43 44 45

    TODO:
      - finish interface implementation
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
  """
  meta_type = 'ERP5 Business Process'
  portal_type = 'Business Process'

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

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Folder
                    , PropertySheet.Comment
                    , PropertySheet.Arrow
62
                    , PropertySheet.BusinessProcess
63 64
                    )

65 66 67 68
  # Declarative interfaces
  zope.interface.implements(interfaces.IBusinessProcess,
                            interfaces.IArrowBase)

69 70
  # Access to path and states of the business process
  security.declareProtected(Permissions.AccessContentsInformation, 'getPathValueList')
71
  def getPathValueList(self, trade_phase=None, context=None, **kw):
72 73 74 75 76 77 78 79 80 81 82 83
    """
      Returns all Path of the current BusinessProcess which
      are matching the given trade_phase and the optional context.

      trade_phase -- a single trade phase category or a list of
                      trade phases

      context -- the context to search matching predicates for

      **kw -- same parameters as for searchValues / contentValues
    """
    # Naive implementation to redo XXX using contentValues
84
    if trade_phase is None:
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
85 86
      trade_phase = []
    elif not isinstance(trade_phase, (list, tuple)):
87 88
      trade_phase = (trade_phase,)
    result = []
89 90
    if len(trade_phase) == 0:
      return result
91 92
    business_path_list = sorted(self.objectValues(portal_type="Business Path"),
                                key=lambda x:x.getIntIndex())
93
    trade_phase = set(trade_phase)
94
    for document in business_path_list:
95 96
      if trade_phase.intersection(document.getTradePhaseList()) and \
              document.test(context):
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
97
        result.append(document)
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
    return result

  security.declareProtected(Permissions.AccessContentsInformation, 'getStateValueList')
  def getStateValueList(self, *args, **kw):
    """
      Returns all states of the business process. The method
      **kw parameters follows the API of searchValues / contentValues
    """
    # Naive implementation to redo XXX
    kw['portal_type'] = "Business State"
    return self.contentValues(*args, **kw)

  # Access to path and states of the business process
  def isCompleted(self, explanation):
    """
      True if all states are completed
    """
    for state in self.getStateValueList():
      if not state.isCompleted(explanation):
        return False
    return True
  
  def isBuildable(self, explanation):
    """
      True if all any path is buildable
    """
    return len(self.getBuildablePathValueList(explanation)) != 0

  def getBuildablePathValueList(self, explanation):
    """
      Returns the list of Business Path which are ready to 
      be built
    """
131 132
    return filter(lambda x:x.isBuildable(explanation),
                  self.objectValues(portal_type='Business Path'))
133 134 135 136 137 138 139 140 141 142 143 144 145 146

  def getCompletedStateValueList(self, explanation):
    """
      Returns the list of Business States which are finished
    """
    return filter(lambda x:x.isCompleted(explanation), self.getStateValueList())

  def getPartiallyCompletedStateValueList(self, explanation):
    """
      Returns the list of Business States which are finished
    """
    return filter(lambda x:x.isPartiallyCompleted(explanation), self.getStateValueList())

  def getLatestCompletedStateValue(self, explanation):
147 148 149
    """
      Returns the most advanced completed state
    """
150 151 152 153 154 155 156
    for state in self.getCompletedStateValueList(explanation):
      for path in state.getPredecessorRelatedValueList():
        if not path.isCompleted(explanation):
          return state
    return None

  def getLatestPartiallyCompletedStateValue(self, explanation):
157 158 159
    """
      Returns the most advanced completed state
    """
160 161 162 163 164 165 166
    for state in self.getCompletedStateValueList(explanation):
      for path in state.getPredecessorRelatedValueList():
        if not path.isPartiallyCompleted(explanation):
          return state
    return None

  def getLatestCompletedStateValueList(self, explanation):
167 168 169
    """
      Returns the most advanced completed state
    """
170 171 172 173 174 175 176 177
    result = []
    for state in self.getCompletedStateValueList(explanation):
      for path in state.getPredecessorRelatedValueList():
        if not path.isCompleted(explanation):
          result.append(state)
    return result

  def getLatestPartiallyCompletedStateValueList(self, explanation):
178 179 180
    """
      Returns the most advanced completed state
    """
181 182 183 184 185 186 187
    result = []
    for state in self.getCompletedStateValueList(explanation):
      for path in state.getPredecessorRelatedValueList():
        if not path.isPartiallyCompleted(explanation):
          result.append(state)
    return result

188
  def build(self, explanation_relative_url):
189 190 191
    """
      Build whatever is buildable
    """
192
    explanation = self.restrictedTraverse(explanation_relative_url)
193
    for path in self.getBuildablePathValueList(explanation):
194
      path.build(explanation)
195

196
  def isStartDateReferential(self): # XXX - not in interface
197 198
    return self.getReferentialDate() == 'start_date'

199
  def isStopDateReferential(self): # XXX - not in interface
200
    return self.getReferentialDate() == 'stop_date'
201 202

  def getTradePhaseList(self):
203 204 205
    """
      Returns all trade_phase of this business process
    """
206 207 208
    path_list = self.objectValues(portal_type=self.getPortalBusinessPathTypeList())
    return filter(None, [path.getTradePhase()
                         for path in path_list])
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

  def getRootExplanationPathValue(self):
    """
      Returns a root path of this business process
    """
    path_list = self.objectValues(portal_type=self.getPortalBusinessPathTypeList())
    path_list = filter(lambda x: x.isDeliverable(), path_list)
    
    if len(path_list) > 1:
      raise Exception, "this business process has multi root paths"

    if len(path_list) == 1:
      return path_list[0]

  def getHeadPathValueList(self, trade_phase_list=None):
    """
      Returns a list of head path(s) of this business process

227
      trade_phase_list -- used to filtering, means that discovering
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 253 254 255 256 257 258
                          a list of head path with the trade_phase_list
    """
    head_path_list = list()
    for state in self.getStateValueList():
      if len(state.getSuccessorRelatedValueList()) == 0:
        head_path_list += state.getPredecessorRelatedValueList()

    if trade_phase_list is not None:
      _set = set(trade_phase_list)
      _list = list()
      # start to discover a head path with the trade_phase_list from head path(s) of whole
      for path in head_path_list:
        _list += self._getHeadPathValueList(path, _set)
      head_path_list = map(lambda t: t[0], filter(lambda t: t != (None, None), _list))

    return head_path_list

  def _getHeadPathValueList(self, path, trade_phase_set):
    # if the path has target trade_phase, it is a head path.
    _set = set(path.getTradePhaseList())
    if _set & trade_phase_set:
      return [(path, _set & trade_phase_set)]

    node = path.getSuccessorValue()
    if node is None:
      return [(None, None)]

    _list = list()
    for next_path in node.getPredecessorRelatedValueList():
      _list += self._getHeadPathValueList(next_path, trade_phase_set)
    return _list
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

  def getRemainingTradePhaseList(self, explanation, trade_state, trade_phase_list=None):
    """
      Returns the list of remaining trade phase for this
      state based on the explanation.

      trade_phase_list -- if provide, the result is filtered by it after collected
    """
    remaining_trade_phase_list = []
    for path in [x for x in self.objectValues(portal_type="Business Path") \
        if x.getPredecessorValue() == trade_state]:
      # XXX When no simulations related to path, what should path.isCompleted return?
      #     if True we don't have way to add remaining trade phases to new movement
      if not (path.getRelatedSimulationMovementValueList(explanation) and
              path.isCompleted(explanation)):
        remaining_trade_phase_list += path.getTradePhaseValueList()

      # collect to successor direction recursively
      state = path.getSuccessorValue()
      if state is not None:
        remaining_trade_phase_list.extend(
          self.getRemainingTradePhaseList(explanation, state, None))

    # filter just at once if given
    if trade_phase_list is not None:
      remaining_trade_phase_list = filter(
        lambda x : x.getLogicalPath() in trade_phase_list,
        remaining_trade_phase_list)

    return remaining_trade_phase_list

  def isStatePartiallyCompleted(self, explanation, trade_state):
    """
      If all path which reach this state are partially completed
      then this state is completed
    """
    for path in [x for x in self.objectValues(portal_type="Business Path") \
        if x.getSuccessorValue() == trade_state]:
      if not path.isPartiallyCompleted(explanation):
        return False
    return True

  def getExpectedStateCompletionDate(self, explanation, trade_state, *args, **kwargs):
    """
      Returns the expected completion date for this
      state based on the explanation.

      explanation -- the document
    """
    # Should be re-calculated?
    # XXX : what is the purpose of the two following lines ? comment it until there is
    # good answer
    if 'predecessor_date' in kwargs:
      del kwargs['predecessor_date']
    successor_list = [x for x in self.objectValues(portal_type="Business Path") \
        if x.getSuccessorValue() == trade_state]
    date_list = self._getExpectedDateList(explanation,
                                          successor_list,
                                          self._getExpectedCompletionDate,
                                          *args,
                                          **kwargs)
    if len(date_list) > 0:
      return min(date_list)

  def getExpectedStateBeginningDate(self, explanation, trade_state, *args, **kwargs):
    """
      Returns the expected beginning date for this
      state based on the explanation.

      explanation -- the document
    """
    # Should be re-calculated?
    # XXX : what is the purpose of the two following lines ? comment it until there is
    # good answer
    if 'predecessor_date' in kwargs:
      del kwargs['predecessor_date']
    predecessor_list = [x for x in self.objectValues(portal_type="Business Path") \
        if x.getPredecessorValue() == trade_state]
    date_list = self._getExpectedDateList(explanation,
                                          predecessor_list,
                                          self._getExpectedBeginningDate,
                                          *args,
                                          **kwargs)
    if len(date_list) > 0:
      return min(date_list)

  def _getExpectedBeginningDate(self, path, *args, **kwargs):
    expected_date = path.getExpectedStartDate(*args, **kwargs)
    if expected_date is not None:
      return expected_date - path.getWaitTime()

  def _getExpectedDateList(self, explanation, path_list, path_method,
                           visited=None, *args, **kwargs):
    """
      getExpected(Beginning/Completion)Date are same structure
      expected date of each path should be returned.

      explanation -- the document
      path_list -- list of target business path
      path_method -- used to get expected date on each path
      visited -- only used to prevent infinite recursion internally
    """
    if visited is None:
      visited = []

    expected_date_list = []
    for path in path_list:
      # filter paths without path of root explanation
      if path not in visited or path.isDeliverable():
        expected_date = path_method(path, explanation, visited=visited, *args, **kwargs)
        if expected_date is not None:
          expected_date_list.append(expected_date)

    return expected_date_list

  def _getExpectedCompletionDate(self, path, *args, **kwargs):
    return path.getExpectedStopDate(*args, **kwargs)