SimulationMovement.py 18.5 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
#
# 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 Globals import InitializeClass
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import getToolByName

33
from Products.ERP5Type import Permissions, PropertySheet, Constraint, interfaces
34
from Products.ERP5Type.TransactionalVariable import getTransactionalVariable
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35

36
from Products.ERP5.Document.Movement import Movement
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37

38
from zLOG import LOG, WARNING
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39

40 41
from Acquisition import aq_base

42
from Products.ERP5.Document.AppliedRule import TREE_DELIVERED_CACHE_KEY, TREE_DELIVERED_CACHE_ENABLED
43

Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
# XXX Do we need to create groups ? (ie. confirm group include confirmed, getting_ready and ready

parent_to_movement_simulation_state = {
  'cancelled'        : 'cancelled',
  'draft'            : 'draft',
  'auto_planned'     : 'auto_planned',
  'planned'          : 'planned',
  'ordered'          : 'planned',
  'confirmed'        : 'planned',
  'getting_ready'    : 'planned',
  'ready'            : 'planned',
  'started'          : 'planned',
  'stopped'          : 'planned',
  'delivered'        : 'planned',
  'invoiced'         : 'planned',
}

class SimulationMovement(Movement):
  """
      Simulation movements belong to a simulation workflow which includes
      the following steps

      - planned

      - ordered

      - confirmed (the movement is now confirmed in qty or date)

      - started (the movement has started)

      - stopped (the movement is now finished)

      - delivered (the movement is now archived in a delivery)

      The simulation worklow uses some variables, which are
      set by the template

      - is_order_required

      - is_delivery_required


      XX
      - is_problem_checking_required ?

      Other flag
      (forzen flag)

      NEW: we do not use DCWorklow so that the simulation process
      can be as much as possible independent of a Zope / CMF implementation.
  """
  meta_type = 'ERP5 Simulation Movement'
  portal_type = 'Simulation Movement'
  isMovement = 1

  # Declarative security
  security = ClassSecurityInfo()
101
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
102 103

  # Declarative interfaces
104
  __implements__ = ( interfaces.IVariated, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
105 106 107 108 109 110 111 112 113 114

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem
                    , PropertySheet.CategoryCore
                    , PropertySheet.Amount
                    , PropertySheet.Task
                    , PropertySheet.Arrow
                    , PropertySheet.Movement
                    , PropertySheet.Simulation
115 116 117
                    # Need industrial_phase
                    , PropertySheet.TransformedResource
                    , PropertySheet.AppliedRule
118
                    , PropertySheet.ItemAggregation
Jean-Paul Smets's avatar
Jean-Paul Smets committed
119
                    )
120

121 122 123
  def tpValues(self) :
    """ show the content in the left pane of the ZMI """
    return self.objectValues()
124

Jean-Paul Smets's avatar
Jean-Paul Smets committed
125
  # Price should be acquired
126 127
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getPrice')
128
  def getPrice(self, default=None, context=None, REQUEST=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
129 130
    """
    """
131
    return self._baseGetPrice(default) # Call the price method
Jean-Paul Smets's avatar
Jean-Paul Smets committed
132

133 134
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCausalityState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
135 136 137 138
  def getCausalityState(self):
    """
      Returns the current state in causality
    """
139
    return getattr(aq_base(self), 'causality_state', 'solved')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
140

141 142
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setCausalityState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
143 144 145 146 147 148
  def setCausalityState(self, value):
    """
      Change causality state
    """
    self.causality_state = value

149 150
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
151 152 153 154
  def getSimulationState(self, id_only=1):
    """
      Returns the current state in simulation

155 156
      Inherit from order or delivery or parent (but use a conversion
      table to make orders planned when parent is confirmed)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158 159 160 161 162 163 164 165 166

      XXX: movements in zero stock rule can not acquire simulation state
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      return delivery.getSimulationState()
    order = self.getOrderValue()
    if order is not None:
      return order.getSimulationState()
    try:
167
      parent_state = self.getParentValue().getSimulationState()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
168
      return parent_to_movement_simulation_state[parent_state]
169
    except (KeyError, AttributeError):
170 171 172
      LOG('SimulationMovement.getSimulationState', WARNING,
          'Could not acquire simulation state from %s'
          % self.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
173 174
      return None

175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getTranslatedSimulationStateTitle')
  def getTranslatedSimulationStateTitle(self):
    """Returns translated simulation state title, for user interface, such as
    stock browser.
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      return delivery.getTranslatedSimulationStateTitle()
    order = self.getOrderValue()
    if order is not None:
      return order.getTranslatedSimulationStateTitle()
    # The simulation_state of a simulation movement is calculated by a
    # mapping, there's no reliable way of getting the translated title from a
    # simulation state ID, so we just return the state ID because we got
    # nothing better to return.
    return self.getSimulationState()

193 194
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isAccountable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
195 196 197
  def isAccountable(self):
    """
      Returns 1 if this needs to be accounted
198 199 200
      Some Simulation movement corresponds to non accountable movements,
      the parent applied rule decide wether this movement is accountable
      or not.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
201
    """
202
    return self.getParentValue().isAccountable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
203 204

  # Ordering / Delivering
205 206
  security.declareProtected( Permissions.AccessContentsInformation,
                             'requiresOrder')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
207 208 209 210 211 212 213 214 215
  def requiresOrder(self):
    """
      Returns 1 if this needs to be ordered
    """
    if isOrderable():
      return len(self.getCategoryMembership('order')) is 0
    else:
      return 0

216 217
  security.declareProtected( Permissions.AccessContentsInformation,
                             'requiresDelivery')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
218 219 220 221 222 223 224 225 226 227 228 229 230 231
  def requiresDelivery(self):
    """
      Returns 1 if this needs to be accounted
    """
    if isDeliverable():
      return len(self.getCategoryMembership('delivery')) is 0
    else:
      return 0


  #######################################################
  # Causality Workflow Methods

  security.declareProtected(Permissions.ModifyPortalContent, 'expand')
232
  def expand(self, force=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 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
    Checks all existing applied rules and make sure they still apply.
    Checks for other possible rules and starts expansion process (instanciates
    applied rules and calls expand on them).

    First get all applicable rules,
    then, delete all applied rules that no longer match and are not linked to
    a delivery,
    finally, apply new rules if no rule with the same type is already applied.
    """
    portal_rules = getToolByName(self, 'portal_rules')

    tv = getTransactionalVariable(self)
    cache = tv.setdefault(TREE_DELIVERED_CACHE_KEY, {})
    cache_enabled = cache.get(TREE_DELIVERED_CACHE_ENABLED, 0)

    # enable cache
    if not cache_enabled:
      cache[TREE_DELIVERED_CACHE_ENABLED] = 1

    applied_rule_dict = {}
    applicable_rule_dict = {}
    for rule in portal_rules.searchRuleList(self, sort_on='version',
        sort_order='descending'):
      ref = rule.getReference()
      if ref and ref not in applicable_rule_dict.iterkeys():
        applicable_rule_dict[ref] = rule

    for applied_rule in self.objectValues():
      rule = applied_rule.getSpecialiseValue()
      if not applied_rule._isTreeDelivered() and not rule.test(self):
        self._delObject(applied_rule.getId())
      else:
        applied_rule_dict[rule.getPortalType()] = applied_rule

    for rule in applicable_rule_dict.itervalues():
      rule_type = rule.getPortalType()
      if rule_type not in applied_rule_dict.iterkeys():
        applied_rule = rule.constructNewAppliedRule(self, **kw)
        applied_rule_dict[rule_type] = applied_rule

    self.setCausalityState('expanded')
    # expand
    for applied_rule in applied_rule_dict.itervalues():
      applied_rule.expand(force=force, **kw)

    # disable and clear cache
    if not cache_enabled:
      try:
        del tv[TREE_DELIVERED_CACHE_KEY]
      except KeyError:
        pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
285 286 287 288 289 290 291 292 293 294

  security.declareProtected(Permissions.ModifyPortalContent, 'diverge')
  def diverge(self):
    """
       -> new status -> diverged

       Movements which diverge can not be expanded
    """
    self.setCausalityState('diverged')

295 296 297 298 299
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationValue')
  def getExplanationValue(self):
    """Returns the delivery if any or the order related to the root
    applied rule if any.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
300 301 302 303 304
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
305
        return order
Jean-Paul Smets's avatar
Jean-Paul Smets committed
306 307
      else:
        # Ex. zero stock rule
308
        return ra
Jean-Paul Smets's avatar
Jean-Paul Smets committed
309
    else:
310
      explanation_value = self.getDeliveryValue()
311 312
      while explanation_value.getPortalType() not in \
              self.getPortalDeliveryTypeList() and \
313
          explanation_value != self.getPortalObject():
314
            explanation_value = explanation_value.getParentValue()
315
      if explanation_value != self.getPortalObject():
316
        return explanation_value
317

Jean-Paul Smets's avatar
Jean-Paul Smets committed
318
  # Deliverability / orderability
319 320
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isOrderable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
321
  def isOrderable(self):
322
    applied_rule = self.getParentValue()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
323 324
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
325
      return rule.isOrderable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
326 327
    return 0

328 329
  getOrderable = isOrderable

330 331
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDeliverable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
332
  def isDeliverable(self):
333
    applied_rule = self.getParentValue()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
334 335
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
336
      return rule.isDeliverable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
337 338
    return 0

339
  getDeliverable = isDeliverable
340

341
  # Simulation Dates - acquire target dates
342 343
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStartDate')
344 345 346 347
  def getOrderStartDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStartDate()
348

349 350
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStopDate')
351 352 353 354
  def getOrderStopDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStopDate()
Romain Courteaud's avatar
Romain Courteaud committed
355

356 357
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStartDateList')
Romain Courteaud's avatar
Romain Courteaud committed
358 359
  def getDeliveryStartDateList(self):
    """
360
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
361 362 363 364 365 366
    """
    start_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      start_date_list.append(delivery_movement.getStartDate())
    return start_date_list
367

368 369
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStopDateList')
Romain Courteaud's avatar
Romain Courteaud committed
370 371
  def getDeliveryStopDateList(self):
    """
372
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
373 374 375 376 377 378
    """
    stop_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      stop_date_list.append(delivery_movement.getStopDate())
    return stop_date_list
379

380 381
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryQuantity')
Romain Courteaud's avatar
Romain Courteaud committed
382 383
  def getDeliveryQuantity(self):
    """
384
      Returns the quantity of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
385
    """
386
    quantity = 0.0
Romain Courteaud's avatar
Romain Courteaud committed
387 388 389 390
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      quantity = delivery_movement.getQuantity()
    return quantity
391

392 393
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isConvergent')
394 395
  def isConvergent(self):
    """
396
      Returns true if the Simulation Movement is convergent with the
397
      the delivery value
398 399 400
    """
    return not self.isDivergent()

401
  security.declareProtected( Permissions.AccessContentsInformation,
402
      'isDivergent')
403 404
  def isDivergent(self):
    """
405
      Returns true if the Simulation Movement is divergent from the
406
      the delivery value
407
    """
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
    return self.getParentValue().isDivergent(self)

  security.declareProtected( Permissions.AccessContentsInformation,
      'getDivergenceList')
  def getDivergenceList(self):
    """
    Returns detailed information about the divergence
    """
    return self.getParentValue().getDivergenceList(self)

  security.declareProtected( Permissions.AccessContentsInformation,
      'getSolverList')
  def getSolverList(self):
    """
    Returns solvers that can fix the current divergence
    """
    return self.getParentValue().getSolverList(self)

426 427
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDefaultDeliveryProperties')
428 429
  def setDefaultDeliveryProperties(self):
    """
430 431
    Sets the delivery_ratio and delivery_error properties to the
    calculated value
432 433 434 435 436
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      delivery.updateSimulationDeliveryProperties(movement_list = [self])

437 438
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCorrectedQuantity')
439 440
  def getCorrectedQuantity(self):
    """
441 442
    Returns the quantity property deducted by the possible profit_quantity and
    taking into account delivery error
443 444
    """
    quantity = self.getQuantity()
445 446 447
    profit_quantity = self.getProfitQuantity() or 0
    delivery_error = self.getDeliveryError() or 0
    return quantity - profit_quantity + delivery_error
448

449 450
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovement')
451 452 453
  def getRootSimulationMovement(self):
    """
      Return the root simulation movement in the simulation tree.
454
      FIXME : this method should be called getRootSimulationMovementValue
455
    """
456
    parent_applied_rule = self.getParentValue()
457 458 459 460 461
    if parent_applied_rule.getRootAppliedRule() == parent_applied_rule:
      return self
    else:
      return parent_applied_rule.getRootSimulationMovement()

462 463
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovementUid')
464 465 466 467 468 469 470 471 472
  def getRootSimulationMovementUid(self):
    """
      Return the uid of the root simulation movement in the simulation tree.
    """
    root_simulation_movement = self.getRootSimulationMovement()
    if root_simulation_movement is not None:
      return root_simulation_movement.getUid()
    return None

473
  security.declareProtected( Permissions.AccessContentsInformation,
474
                             'getRootCausalityValueList')
475 476 477 478 479 480 481 482
  def getRootCausalityValueList(self):
    """
      Returns the initial causality value for this movement.
      This method will look at the causality and check if the
      causality has already a causality
    """
    root_rule = self.getRootAppliedRule()
    return root_rule.getCausalityValueList()
483

484
  # XXX FIXME Use a interaction workflow instead
485
  # XXX This behavior is now done by simulation_movement_interaction_workflow
486
  # The call to activate() must be done after actual call to
487
  # setDelivery() on the movement,
488
  # but activate() must be called on the previous delivery...
489 490 491 492 493 494 495 496
  #def _setDelivery(self, value):
  #  LOG('setDelivery before', 0, '')
  #  delivery_value = self.getDeliveryValue()
  #  Movement.setDelivery(value)
  #  LOG('setDelivery', 0, '')
  #  if delivery_value is not None:
  #    LOG('delivery_value = ', 0, repr(delivery_value))
  #    activity = delivery_value.activate(
497
  #                activity='SQLQueue',
498
  #                after_path_and_method_id=(
499 500
  #                                        self.getPath(),
  #                                        ['immediateReindexObject',
501 502
  #                                         'recursiveImmediateReindexObject']))
  #    activity.edit()
503

504 505 506 507 508 509 510 511 512 513 514 515 516
  def _isTreeDelivered(self, ignore_first=0):
    """
    checks if subapplied rules  of this movement (going down the complete
    simulation tree) have a child with a delivery relation.
    Returns True if at least one is delivered, False if none of them are.

    see AppliedRule._isTreeDelivered
    """
    tv = getTransactionalVariable(self)
    cache = tv.setdefault(TREE_DELIVERED_CACHE_KEY, {})
    cache_enabled = cache.get(TREE_DELIVERED_CACHE_ENABLED, 0)

    def getTreeDelivered(movement, ignore_first=0):
517
      if not ignore_first:
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538
        if len(movement.getDeliveryList()) > 0:
          return True
      for applied_rule in movement.objectValues():
        if applied_rule._isTreeDelivered():
          return True
      return False

    if ignore_first:
      rule_key = (self.getRelativeUrl(), 1)
    else:
      rule_key = self.getRelativeUrl()
    if cache_enabled:
      try:
        return cache[rule_key]
      except:
        result = getTreeDelivered(self, ignore_first=ignore_first)
        cache[rule_key] = result
        return result
    else:
      return getTreeDelivered(self, ignore_first=ignore_first)