ExplanationCache.py 8.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2O10 Nexedi SA and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solanes <jp@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.
#
##############################################################################

import types

from Products.CMFCore.utils import getToolByName
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable

class ExplanationCache:
  """ExplanationCache provides a central access to 
  all parameters and values which are needed to process 
  an explanation. It is based on the idea that a value is calculated
  once and once only, as a way to accelerate performance of algorithms
  related to an explanation.

        'explanation_uid': self._getExplanationUidList(explanation) # XXX-JPS why do we need explanation_uid ? and why a list
        'simulation_path': simulation_path,

    explanation_uid = self._getExplanationUidList(explanation) # A hint value to reduce the size of the tree
    simulation_path = '/erp5/p.../%' # A list of path

"""
  def __init__(self, explanation):
    """
    """
    # Define share properties
    self.explanation = explanation
54
    self.portal_catalog = getToolByName(explanation, 'portal_catalog')
55 56 57 58
    self.simulation_movement_cache = {} # Simulation Movement Cache
    self.explanation_uid_cache = []
    self.explanation_path_pattern_cache = []

59
  def _getDeliveryMovementList(self):
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    """Returns self is explanation is a delivery line
    of the list of explanation delivery lines if explanation
    is a delivery
    """
    explanation = self.explanation
    if explanation.isDelivery():
      # Gather all movements of the delivery
      delivery_movement_list = explanation.getMovementList()
    else:
      # Only consider a single movement - XXX-JPS is this OK when we have lines in lines ?
      delivery_movement_list = [explanation]
    return delivery_movement_list

  def getRootExplanationUidList(self):
    """Return the list of explanation_uid values involved
    in the context of the explanation. This will be useful later
    in order to accelerate searches in the catalog.
    """
    # Return cache if defined
    if self.explanation_uid_cache:
      return self.explanation_uid_cache
    result = set()
    # For each delivery movement
83
    for movement in self._getDeliveryMovementList():
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
      # For each simulation movement
      for simulation_movement in movement.getDeliveryRelatedValueList():
        result.add(simulation_movement.getExplanationUid()) # XXX-JPS use new API later
    # Return result
    self.explanation_uid_cache = result
    return result

  def getSimulationPathPatternList(self):
    """Return the list of root path of simulation tree which are 
    involved in the context of the explanation. This will be useful later
    in order to accelerate searches in the catalog.
    """
    # Return cache if defined
    if self.explanation_path_pattern_cache:
      return self.explanation_path_pattern_cache

    # Helper method to update path_dict with
    # each key which forms the pay of the simulation_movement
    path_dict = {}
    def updatePathDict(simulation_movement):
      local_path_dict = path_dict
      container_path = simulation_movement.getParentValue().getPhysicalPath()
      simulation_movement_id = simulation_movement.getId()
      insert_movement = True
      for path_id in container_path:
        if local_path_dict.get(path_id, None) is None:
          local_path_dict[path_id] = dict()
        local_path_dict = local_path_dict[path_id]
        if type(local_path_dict) is not types.DictType:
          # A movement was already inserted
          insert_movement = False
          break
      if insert_movement:
        local_path_dict[simulation_movement_id] = simulation_movement

    # For each delivery movement
120
    for movement in self._getDeliveryMovementList():
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
      # For each simulation movement
      for simulation_movement in movement.getDeliveryRelatedValueList():
        updatePathDict(simulation_movement)
    
    # Build result by browsing path_dict and
    # assembling path '/erp5/portal_simulation/1/34/23/43%'
    result = []
    def browsePathDict(prefix, local_path_dict):
      for key, value in local_path_dict.items():
        if type(value) is not types.DictType:
          # We have a real root
          result.append('%s/%s%' % (prefix, key))
        else:
          browsePathDict('%s/%s' % (prefix, key), value) # Recursing with string append is slow XXX-JPS

136
    browsePathDict('/', path_dict)
137 138 139 140 141 142 143 144 145
    self.explanation_path_pattern_cache = result
    return result

  def getBusinessPathRelatedSimulationMovementValueList(self, business_path):
    """Returns the list of simulation movements caused by a business_path
    in the context the our explanation.
    """
    return self.getSimulationMovementList(causality_uid=business_path.getUid())
    
146
  def getSimulationMovementList(self, **kw):
147 148 149 150 151 152 153 154 155 156 157 158 159
    """Search Simulation Movements related to our explanation.
    Cache result so that the second time we saarch for the same
    list we need not involve the catalog again.
    """
    kw_tuple = tuple(kw.items()) # We hope that no sorting is needed
    if self.simulation_movement_list.get(kw_tuple, None) is None:
      self.simulation_movement_cache[kw_tuple] = \
           self.portal_catalog(portal_type="Simulation Movement",
                               explanation_uid=self.getRootExplanationUidList(),
                               path=self.getSimulationPathPatternList(), # XXX-JPS Explicit Query is better
                               **kw)
    return self.simulation_movement_cache[kw_tuple]

160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
  def geBusinessPathClosure(business_path):
    """Creates a Business Process by filtering out all Business Path
    in self which are not related to a simulation movement
    which is either or parent or a child of explanation simulations movements
    caused by 'business_path'

    cache keys: business_path (simple) then path_set

    XXX-JPS PSEUDO CODE
    """
    new_business_process = BusinessProcess()
    accepted_path = []
    
    explanation_cache = _getExplanationCache(explanation)
    path_list = explanation_cache.getSimulationPathPatternList()
    path_list = map(lambda x:x[0:-1], path_list) # Remove trailing %
    path_set = set()
    for simulation_movement in business_path.\
             _getExplanationRelatedSimulationMovementValueList(explanation):
      simulation_path = simulation_movement.getPath()
      for path in path_list:
        if simulation_path.startswith(path):
          path_set.add(path) # This selection path is part of explanation

    for business_path in self.getBusinessPathValueList():
      if business_path.hasMovementsIn(explanation, path_set):
        accepted_path.append(business_path)

    new_business_process.addValueList(business_path)
    return new_business_process

191
def _getExplanationCache(explanation):
192 193
  if explanation.isinstance(ExplanationCache):
    return explanation
194 195 196 197 198
  # Return cached value if any
  tv = getTransactionalVariable(explanation)
  if tv.get('explanation_cache', None) is None:
    tv['explanation_cache'] =  ExplanationCache(explanation)
  return tv.get('explanation_cache')
199 200 201 202 203 204

def _getBusinessPathClosure(explanation, business_path):
  """Returns a 
  """
  explanation_cache = _getExplanationCache(explanation)
  return explanation_cache.getBusinessPathClosure(business_path)