Rule.py 13.1 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
#
# 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
from Products.CMFCore.utils import getToolByName
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Document.Predicate import Predicate
from Acquisition import aq_base, aq_parent, aq_inner, aq_acquire
35
from zLOG import LOG, WARNING
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37

class Rule(XMLObject, Predicate):
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
  """
    Rule objects implement the simulation algorithm
    (expand, solve)

    Example of rules

    - Stock rule (checks stocks)

    - Order rule (copies movements from an order)

    - Capacity rule (makes sure stocks / sources are possible)

    - Transformation rule (expands transformations)

    - Template rule (creates submovements with a template system)
      used in Invoice rule, Paysheet rule, etc.

    Rules are called one by one at the global level (the rules folder)
    and at the local level (applied rules in the simulation folder)

    The simulation_tool includes rules which are parametrized by the sysadmin
    The simulation_tool does the logics of checking, calling, etc.

    simulation_tool is a subclass of Folder & Tool
  """

  # CMF Type Definition
  meta_type = 'ERP5 Rule'
  portal_type = 'Rule'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.AccessContentsInformation)
  
  __implements__ = ( Interface.Predicate,
                     Interface.Rule )

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
83
                    , PropertySheet.Task
84 85 86 87 88 89 90 91 92 93 94 95
                    )
  
  # Portal Type of created children
  movement_type = 'Simulation Movement'

  security.declareProtected(Permissions.AccessContentsInformation,
                            'isAccountable')
  def isAccountable(self, movement):
    """Tells wether generated movement needs to be accounted or not.
    
    Only account movements which are not associated to a delivery;
    Whenever delivery is there, delivery has priority
Jean-Paul Smets's avatar
Jean-Paul Smets committed
96
    """
97
    return movement.getDeliveryValue() is None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
  security.declareProtected(Permissions.ModifyPortalContent,
                            'constructNewAppliedRule')
  def constructNewAppliedRule(self, context, id=None, 
                              activate_kw=None, **kw):
    """
      Creates a new applied rule which points to self
    """
    # XXX Parameter **kw is useless, so, we should remove it
    portal_types = getToolByName(self, 'portal_types')
    if id is None:
      id = context.generateNewId()
    if getattr(aq_base(context), id, None) is None:
      context.newContent(id=id,
                         portal_type='Applied Rule',
                         specialise_value=self,
                         activate_kw=activate_kw)
    return context.get(id)

  # Simulation workflow
  security.declareProtected(Permissions.ModifyPortalContent, 'expand')
  def expand(self, applied_rule, **kw):
    """
      Expands the current movement downward.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122

123 124 125 126 127 128 129 130 131 132 133
      An applied rule can be expanded only if its parent movement
      is expanded.
    """
    for o in applied_rule.objectValues():
      o.expand(**kw)

  security.declareProtected(Permissions.ModifyPortalContent, 'solve')
  def solve(self, applied_rule, solution_list):
    """
      Solve inconsistency according to a certain number of solutions
      templates. This updates the
Jean-Paul Smets's avatar
Jean-Paul Smets committed
134

135
      -> new status -> solved
Jean-Paul Smets's avatar
Jean-Paul Smets committed
136

137 138 139 140 141
      This applies a solution to an applied rule. Once
      the solution is applied, the parent movement is checked.
      If it does not diverge, the rule is reexpanded. If not,
      diverge is called on the parent movement.
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
142

143 144 145 146 147
  def test(self, movement):
    """
    Tests if the rule (still) applies
    First try to call a python script, then call the _test method defined in
    the class
Jean-Paul Smets's avatar
Jean-Paul Smets committed
148

149 150 151 152 153 154
    This method should not be overriden by Rules.
    """
    method = self._getTypeBasedMethod('test')
    if method is not None:
      return method(movement)
    return self._test(movement)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
155

156 157 158 159
  def _test(self, movement):
    """
    Default behaviour of Rule.test, used when no test method for the rule
    was defined
Jean-Paul Smets's avatar
Jean-Paul Smets committed
160

161 162 163 164
    This method should be overriden by Rules if another default behaviour is
    wanted.
    """
    return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
165

166 167
  security.declareProtected(Permissions.ModifyPortalContent, 'diverge')
  def diverge(self, applied_rule):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
168
    """
169
      -> new status -> diverged
Jean-Paul Smets's avatar
Jean-Paul Smets committed
170

171 172 173 174
      This basically sets the rule to "diverged"
      and blocks expansion process
    """
    pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
175

176 177 178
  # Solvers
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isDivergent')
179
  def isDivergent(self, sim_mvt, ignore_list=[]):
180 181 182 183
    """
    Returns true if the Simulation Movement is divergent comparing to
    the delivery value
    """
184
    delivery = sim_mvt.getDeliveryValue()
185 186
    if delivery is None:
      return 0
187 188 189 190
      
    if self.getDivergenceList(sim_mvt) == []:
      return 0
    else:
191
      return 1
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    
  security.declareProtected(Permissions.View, 'getDivergenceList')
  def getDivergenceList(self, sim_mvt):
    """
    Return a list of messages that contains the divergences.
    """
    result_list = []
    for divergence_tester in self.contentValues(
               portal_type=self.getPortalDivergenceTesterTypeList()):
      result = divergence_tester.explain(sim_mvt)
      result_list.extend(result)
    return result_list

  # XXX getSolverList is not part of the API and should be removed.
  # Use getDivergenceList instead.
207
#    security.declareProtected(Permissions.View, 'getSolverList')
208

209 210 211 212 213 214 215 216 217 218 219
#    def getSolverList(self, applied_rule):
#      """
#        Returns a list Divergence solvers
#      """

  # Deliverability / orderability
  def isOrderable(self, movement):
    return 0

  def isDeliverable(self, movement):
    return 0
220

221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  def isStable(self, applied_rule, **kw):
    """
    - generate a list of previsions
    - compare the prevision with existing children
    - return 1 if they match, 0 else
    """
    list = self._getCompensatedMovementList(applied_rule, **kw)
    for e in list:
      if len(e) > 0:
        return 0
    return 1

#### Helpers
  def _isTreeDelivered(self, movement_list, ignore_first=0):
    """
    returns 1 if the movement or any of its child is linked to a delivery
    """
    child_movement_list = []
    for movement in movement_list:
      if not ignore_first and len(movement.getDeliveryList()) > 0:
        return 1
      else:
        for applied_rule in movement.objectValues():
          child_movement_list = applied_rule.objectValues()
    if len(child_movement_list) == 0:
246
      return 0
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 273 274 275 276 277 278 279 280 281 282 283 284 285
    return self._isTreeDelivered(child_movement_list)

  def _getCurrentMovementList(self, applied_rule, **kw):
    """
    Returns the list of current children of the applied rule, sorted in 3
    groups : immutables/mutables/deletable

    If a movement is not frozen, and has no delivered child, it can be
    deleted.
    Else, if a movement is not frozen, and has some delivered child, it can
    be modified.
    Else, it cannot be modified.

    - is delivered
    - has delivered childs (including self)
    - is in reserved or current state
    - is frozen

    a movement is deletable if it has no delivered child, is not in current
    state, and not in delivery movements.
    a movement 
    """
    immutable_movement_list = []
    mutable_movement_list = []
    deletable_movement_list = []
    
    for movement in applied_rule.contentValues(portal_type=self.movement_type):
      if movement.isFrozen():
        immutable_movement_list.append(movement)
      else:
        if self._isTreeDelivered([movement]):
          mutable_movement_list.append(movement)
        else:
          deletable_movement_list.append(movement)

    return (immutable_movement_list, mutable_movement_list,
            deletable_movement_list)

  def _getCompensatedMovementList(self, applied_rule,
286 287 288 289
                                  matching_property_list=[
                                  'resource',
                                  'variation_category_list',
                                  'variation_property_dict'], **kw):
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
    """
    Compute the difference between prevision and existing movements

    immutable movements need compensation, mutables needs to be modified

    XXX For now, this implementation is too simple. It could be improved by
    using MovementGroups
    """
    add_list = [] # list of movements to be added
    modify_dict = {} # dict of movements to be modified
    delete_list = [] # list of movements to be deleted
    
    prevision_list = self._generatePrevisionList(applied_rule, **kw)
    immutable_movement_list, mutable_movement_list, \
        deletable_movement_list = self._getCurrentMovementList(applied_rule,
                                                               **kw)
    movement_list = immutable_movement_list + mutable_movement_list \
                    + deletable_movement_list
    non_matched_list = movement_list[:] # list of remaining movements 

    for prevision in prevision_list:
      p_matched_list = []
      for movement in non_matched_list:
        for prop in matching_property_list:
          if prevision.get(prop) != movement.getProperty(prop):
            break
        else:
          p_matched_list.append(movement)

      # XXX hardcoded ...
320 321
#       LOG("Rule, _getCompensatedMovementList", WARNING, 
#           "Hardcoded properties check")
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
      # Movements exist, we'll try to make them match the prevision
      if p_matched_list != []:
        # Check the quantity
        m_quantity = 0.0
        for movement in p_matched_list:
          m_quantity += movement.getQuantity()#getCorrectedQuantity()
        if m_quantity != prevision.get('quantity'):
          q_diff = prevision.get('quantity') - m_quantity
          # try to find a movement that can be edited
          for movement in p_matched_list:
            if movement in (mutable_movement_list \
                + deletable_movement_list):
              # mark as requiring modification
              prop_dict = modify_dict.setdefault(movement.getId(), {})
              #prop_dict['quantity'] = movement.getCorrectedQuantity() + \
              prop_dict['quantity'] = movement.getQuantity() + \
                  q_diff
              break
          # no modifiable movement was found, need to create one
          else:
            prevision['quantity'] = q_diff
            add_list.append(prevision)
        # Check the date
        for movement in p_matched_list:
          if movement in (mutable_movement_list \
              + deletable_movement_list):
            for prop in ('start_date', 'stop_date'):
              #XXX should be >= 15
              if prevision.get(prop) != movement.getProperty(prop):
                prop_dict = modify_dict.setdefault(movement.getId(), {})
                prop_dict[prop] = prevision.get(prop)
                break
        # update movement lists
        for movement in p_matched_list:
          non_matched_list.remove(movement)
      # No movement matched, we need to create one
      else:
        add_list.append(prevision)
360

361 362 363 364 365 366 367 368 369 370 371 372
    # delete non matched movements
    for movement in non_matched_list:
      if movement in deletable_movement_list:
        # delete movement
        delete_list.append(movement.getId())
      elif movement in mutable_movement_list:
        # set movement quantity to 0 to make it "void"
        prop_dict = modify_dict.setdefault(movement.getId(), {})
        prop_dict['quantity'] = 0.0
      else:
        # movement not modifiable, we can decide to create a compensation
        # with negative quantity
373 374 375
        raise NotImplementedError(
                "Can not create a compensation movement for %s" % \
                movement.getRelativeUrl())
376
    return (add_list, modify_dict, delete_list)