InteractionWorkflow.py 14.3 KB
Newer Older
1 2
##############################################################################
#
wenjie.zheng's avatar
wenjie.zheng committed
3 4
# Copyright (c) 2015 Nexedi SARL and Contributors. All Rights Reserved.
#                    Wenjie Zheng <wenjie.zheng@tiolive.com>
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
#
# 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.
#
##############################################################################

import App
wenjie.zheng's avatar
wenjie.zheng committed
30 31
import transaction

32 33 34
from AccessControl import getSecurityManager, ClassSecurityInfo
from AccessControl.SecurityManagement import setSecurityManager
from Acquisition import aq_base
wenjie.zheng's avatar
wenjie.zheng committed
35
from Products.CMFActivity.ActiveObject import ActiveObject
36 37 38
from Products.CMFCore.utils import getToolByName
from Products.DCWorkflow.DCWorkflow import DCWorkflowDefinition
from Products.DCWorkflow.Expression import StateChangeInfo
wenjie.zheng's avatar
wenjie.zheng committed
39 40
from Products.ERP5Type import Permissions, PropertySheet, Globals
from Products.ERP5Type.id_as_reference import IdAsReferenceMixin
41
from Products.ERP5Type.Globals import PersistentMapping
wenjie.zheng's avatar
wenjie.zheng committed
42 43 44 45 46 47
from Products.ERP5Type.patches.Expression import Expression_createExprContext
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type.Workflow import addWorkflowFactory
from Products.ERP5Workflow.Document.Transition import TRIGGER_WORKFLOW_METHOD
from Products.ERP5Workflow.Document.Workflow import Workflow
from types import StringTypes
48 49 50

_MARKER = []

51
class InteractionWorkflow(IdAsReferenceMixin("interactionworkflow_", "prefix"), XMLObject):
52 53 54 55 56
  """
  An ERP5 Interaction Workflow.
  """
  meta_type = 'ERP5 Workflow'
  portal_type = 'Interaction Workflow'
57
  _isAWorkflow = True # DCWorkflow Tool compatibility
58 59 60
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1
61
  default_reference = ''
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
  managed_permission_list = ()
  managed_role = ()

  intaractions = None
  manager_bypass = 0

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

  # Declarative properties
  property_sheets = (
    PropertySheet.Base,
    PropertySheet.XMLObject,
    PropertySheet.CategoryCore,
    PropertySheet.DublinCore,
78
    PropertySheet.Reference,
79 80 81 82
    PropertySheet.InteractionWorkflow,
  )


83
  def notifyCreated(self, document):
84 85 86 87 88 89 90 91 92 93
    pass

  security.declareProtected(Permissions.View, 'getChainedPortalTypeList')
  def getChainedPortalTypeList(self):
    """Returns the list of portal types that are chained to this
    interaction workflow."""
    chained_ptype_list = []
    wf_tool = getToolByName(self, 'portal_workflow')
    types_tool = getToolByName(self, 'portal_types')
    for ptype in types_tool.objectValues():
wenjie.zheng's avatar
wenjie.zheng committed
94
      if self.getId() in ptype.getTypeERP5WorkflowList():
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
        chained_ptype_list.append(ptype.getId())
    return chained_ptype_list

  security.declarePrivate('listObjectActions')
  def listObjectActions(self, info):
    return []

  security.declarePrivate('_changeStateOf')
  def _changeStateOf(self, ob, tdef=None, kwargs=None) :
    """
    InteractionWorkflow is stateless. Thus, this function should do nothing.
    """
    return

  security.declarePrivate('isInfoSupported')
  def isInfoSupported(self, ob, name):
    '''
    Returns a true value if the given info name is supported.
    '''
wenjie.zheng's avatar
wenjie.zheng committed
114
    vdef = self._getOb(name, None)
115 116 117 118 119 120 121 122 123 124 125 126
    if vdef is not None:
      if vdef.getTypeInfo().getId() == 'Variable':
        return 1
      return 0
    return 0

  security.declarePrivate('getInfoFor')
  def getInfoFor(self, ob, name, default):
    '''
    Allows the user to request information provided by the
    workflow.  This method must perform its own security checks.
    '''
127
    vdef = self._getOb(name, _MARKER)
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
    if vdef is _MARKER:
      return default
    if vdef.info_guard is not None and not vdef.info_guard.check(
      getSecurityManager(), self, ob):
      return default
    status = self.getCurrentStatusDict(ob)
    if status is not None and name in status:
      value = status[name]
    # Not set yet.  Use a default.
    elif vdef.default_expr is not None:
      ec = Expression_createExprContext(StateChangeInfo(ob, self, status))
      value = vdef.default_expr(ec)
    else:
      value = vdef.default_value

    return value

145
  security.declarePrivate('isWorkflowMethodSupported')
146
  def isWorkflowMethodSupported(self, ob, tid):
147 148 149 150
    '''
    Returns a true value if the given workflow method
    is supported in the current state.
    '''
151
    tdef = self._getOb('interaction_' + tid)
152 153 154 155 156
    if tdef is not None and self._checkTransitionGuard(tdef, ob):
      return 1
    return 0

  def _checkTransitionGuard(self, tdef, document, **kw):
157 158 159 160 161 162
    if tdef.temporary_document_disallowed:
      isTempDocument = getattr(document, 'isTempDocument', None)
      if isTempDocument is not None:
        if isTempDocument():
          return 0

163 164 165 166 167 168 169
    guard = tdef.getGuard()
    if guard is None:
      return 1
    if guard.check(getSecurityManager(), self, document, **kw):
      return 1
    return 0

170
  security.declarePrivate('getValidRoleList')
171 172 173
  def getValidRoleList(self):
    return sorted(self.getPortalObject().getDefaultModule('acl_users').valid_roles())

174
  security.declarePrivate('_updateWorkflowHistory')
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  def _updateWorkflowHistory(self, document, status_dict):
    """
    Change the state of the object.
    """
    # Create history attributes if needed
    if getattr(aq_base(document), 'workflow_history', None) is None:
      document.workflow_history = PersistentMapping()
      # XXX this _p_changed is apparently not necessary
      document._p_changed = 1

    # Add an entry for the workflow in the history
    workflow_key = self._generateHistoryKey()
    if not document.workflow_history.has_key(workflow_key):
      document.workflow_history[workflow_key] = ()

    # Update history
    document.workflow_history[workflow_key] += (status_dict,)

193
  security.declarePrivate('getStateChangeInformation')
194 195 196 197 198 199 200 201 202 203 204 205 206
  def getStateChangeInformation(self, document, state, transition=None):
    """
    Return an object used for variable tales expression.
    """
    if transition is None:
      transition_url = None
    else:
      transition_url = transition.getRelativeUrl()
    return self.asContext(document=document,
                          transition=transition,
                          transition_url=transition_url,
                          state=state)

207
  security.declarePrivate('getCurrentStatusDict')
208 209 210 211 212 213 214 215 216 217
  def getCurrentStatusDict(self, document):
    """
    Get the current status dict.
    """
    workflow_key = self._generateHistoryKey()

    # Copy is requested
    result = document.workflow_history[workflow_key][-1].copy()
    return result

218
  security.declarePrivate('_generateHistoryKey')
219 220 221 222
  def _generateHistoryKey(self):
    """
    Generate a key used in the workflow history.
    """
wenjie.zheng's avatar
wenjie.zheng committed
223
    history_key = self.unrestrictedTraverse(self.getRelativeUrl()).getId()
224 225
    return history_key

226
  security.declarePrivate('getWorklistVariableMatchDict')
227 228 229 230
  def getWorklistVariableMatchDict(self, info, check_guard=True):
    return None

  def _getWorkflowStateOf(self, ob, id_only=0):
231 232
    return None

233 234 235 236 237 238 239
  security.declarePrivate('getScriptValueList')
  def getScriptValueList(self):
    scripts = {}
    for script in self.objectValues(portal_type='Workflow Script'):
      scripts[script.getId()] = script
    return scripts

240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
  security.declarePrivate('getTransitionValueList')
  def getTransitionValueList(self):
    interaction_dict = {}
    for tdef in self.objectValues(portal_type="Interaction"):
      interaction_dict[tdef.getReference()] = tdef
    return interaction_dict

  security.declarePrivate('getTransitionIdList')
  def getTransitionIdList(self):
    id_list = []
    for ob in self.objectValues(portal_type="Interaction"):
      id_list.append(ob.getReference())
    return id_list

  security.declarePrivate('notifyWorkflowMethod')
  def notifyWorkflowMethod(self, ob, transition_list, args=None, kw=None):
    """ InteractionWorkflow is stateless. Thus, this function should do nothing.
    """
    pass

  security.declarePrivate('notifyBefore')
  def notifyBefore(self, ob, transition_list, args=None, kw=None):
    if type(transition_list) in StringTypes:
      return

    if kw is None:
      kw = {'workflow_method_args' : args}
    else:
      kw = kw.copy()
      kw['workflow_method_args'] = args
    filtered_transition_list = []

    for t_id in transition_list:
273
      tdef = self._getOb(t_id)
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
      assert tdef.trigger_type == TRIGGER_WORKFLOW_METHOD
      filtered_transition_list.append(tdef.getId())
      former_status = self._getOb(status_dict[self.getStateVariable()], None)

      sci = StateChangeInfo(
      ob, self, former_status, tdef, None, None, kwargs=kw)

      before_script_list = []
      before_script_list.append(self.getBeforeScriptName())
      if before_script_list != [] and tdef.getBeforeScriptName() is not None:
        for script_name in before_script_list:
          script = self._getOb(script_name)
          script.execute(sci)
    return filtered_transition_list

  security.declarePrivate('notifySuccess')
  def notifySuccess(self, ob, transition_list, result, args=None, kw=None):
    """
    Notifies this workflow that an action has taken place.
    """
    if type(transition_list) in StringTypes:
      return

    if kw is None:
      kw = {'workflow_method_args' : args}
    else:
      kw = kw.copy()
      kw['workflow_method_args'] = args

    for t_id in transition_list:
wenjie.zheng's avatar
wenjie.zheng committed
304
      tdef = self._getOb(t_id)
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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
      assert tdef.trigger_type == TRIGGER_WORKFLOW_METHOD
      former_status = self._getOb(status_dict[self.getStateVariable()], None)
      econtext = None
      sci = None

      # Update variables.
      tdef_exprs = tdef.var_exprs
      if tdef_exprs is None: tdef_exprs = {}
      status = {}

      for vdef in self.objectValues(portal_type='Variable'):
        id = vdef.getId()
        if not vdef.for_status:
          continue
        expr = None
        if id in tdef_exprs:
          expr = tdef_exprs[id]
        elif not vdef.update_always and id in former_status:
          # Preserve former value
          value = former_status[id]
        else:
          if vdef.default_expr is not None:
            expr = vdef.default_expr
          else:
            value = vdef.default_value
        if expr is not None:
          # Evaluate an expression.
          if econtext is None:
            # Lazily create the expression context.
            if sci is None:
              sci = StateChangeInfo(
                  ob, self, former_status, tdef,
                  None, None, None)
            econtext = Expression_createExprContext(sci)
          value = expr(econtext)
        status[id] = value

      sci = StateChangeInfo(
            ob, self, former_status, tdef, None, None, kwargs=kw)

      # Execute the "after" script.
      after_script_list = []
      after_script_list.append(self.getAfterScriptName())
      if after_script_list != [] and self.getAfterScriptName() is not None:
        for script_name in after_script_list:
          script = workflow._getOb(script_name)
          # Pass lots of info to the script in a single parameter.
          script.execute(sci)  # May throw an exception

      # Queue the "Before Commit" scripts
      sm = getSecurityManager()
      before_commit_script_list = []
      before_commit_script_list.append(self.getBeforeCommitScriptName())
      if before_commit_script_list != [] and tdef.getBeforeCommitScriptName() is not None:
        for script_name in before_commit_script_list:
          transaction.get().addBeforeCommitHook(tdef._before_commit,
                                                (sci, script_name, sm))

      # Execute "activity" scripts
      activity_script_list = []
      activity_script_list.append(tdef.getActivateScriptName())
      if activity_script_list != [] and tdef.getActivateScriptName() is not None:
        for script_name in activity_script_list:
          workflow.activate(activity='SQLQueue')\
              .activeScript(script_name, ob.getRelativeUrl(),
                            status, tdef.getId())

  def _before_commit(self, sci, script_name, security_manager):
    # check the object still exists before calling the script
    ob = sci.object
    while ob.isTempObject():
      ob = ob.getParentValue()
    if aq_base(self.unrestrictedTraverse(ob.getPhysicalPath(), None)) is \
       aq_base(ob):
      current_security_manager = getSecurityManager()
      try:
        # Who knows what happened to the authentication context
        # between here and when the interaction was executed... So we
        # need to switch to the security manager as it was back then
        setSecurityManager(security_manager)
        self._getOb(script_name)(sci)
      finally:
        setSecurityManager(current_security_manager)

  def activeScript(self, script_name, ob_url, former_status, tdef_id):
    script = self._getOb(script_name)
    ob = self.unrestrictedTraverse(ob_url)
    tdef = self._getOb(tdef_id)
    sci = StateChangeInfo(
          ob, self, former_status, tdef, None, None, kwargs=kw)
    script.execute(sci)
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

  security.declarePrivate('isActionSupported')
  def isActionSupported(self, document, action, **kw):
    '''
    Returns a true value if the given action name
    is possible in the current state.
    '''
    sdef = self._getWorkflowStateOf(document, id_only=0)
    if sdef is None:
      return 0

    if action in sdef.getDestinationIdList():
      tdef = self._getOb(action, None)
      if (tdef is not None and
        tdef.trigger_type == TRIGGER_USER_ACTION and
        self._checkTransitionGuard(tdef, document, **kw)):
        return 1
    return 0