SimulationMovement.py 29.1 KB
Newer Older
1
# -*- coding: utf-8 -*-
Jean-Paul Smets's avatar
Jean-Paul Smets committed
2 3 4
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
5
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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.
#
##############################################################################

30
import zope.interface
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32 33
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import getToolByName

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

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

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

41 42
from Acquisition import aq_base

43
from Products.ERP5.Document.AppliedRule import TREE_DELIVERED_CACHE_KEY, TREE_DELIVERED_CACHE_ENABLED
44
from Products.ERP5.mixin.property_recordable import PropertyRecordableMixin
45
from Products.ERP5.mixin.explainable import ExplainableMixin
46

Jean-Paul Smets's avatar
Jean-Paul Smets committed
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
# 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',
}

64
class SimulationMovement(PropertyRecordableMixin, Movement, ExplainableMixin):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 101 102
  """
      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'

  # Declarative security
  security = ClassSecurityInfo()
103
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
104 105 106 107 108 109 110 111 112 113

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

121 122 123
  # Declarative interfaces
  zope.interface.implements(interfaces.IPropertyRecordable, )

124 125 126
  def tpValues(self) :
    """ show the content in the left pane of the ZMI """
    return self.objectValues()
127

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

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

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

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

158 159
      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
160 161 162 163 164 165

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

179 180 181 182 183 184 185 186 187
  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()
188
    # 'order' category is deprecated. it is kept for compatibility.
189 190 191 192 193 194 195 196 197
    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()

198 199 200
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isCompleted')
  def isCompleted(self):
201 202 203
    """Lookup business path and, if any, return True whenever
    simulation_state is in of completed state list defined on business path
    """
204
    # only available in BPM, so fail totally in case of working without BPM
205 206 207
    business_link =  self.getCausalityValue(
                         portal_type=self.getPortalBusinessLinkTypeList())
    if business_link is None:
208
      return False
209
    return self.getSimulationState() in business_link.getCompletedStateList()
210 211 212 213 214 215 216

  security.declareProtected(Permissions.AccessContentsInformation,
                            'isFrozen')
  def isFrozen(self):
    """Lookup business path and, if any, return True whenever
    simulation_state is in one of the frozen states defined on business path
    """
217 218 219
    business_link =  self.getCausalityValue(
                         portal_type=self.getPortalBusinessLinkTypeList())
    if business_link is None:
220 221 222 223 224 225 226
      # Legacy support - this should never happen
      # XXX-JPS ADD WARNING
      if self.getSimulationState() in ('stopped', 'delivered', 'cancelled'):
        return True
      if self._baseIsFrozen() == 0:
        self._baseSetFrozen(None)
      return self._baseGetFrozen() or False
227
    return self.getSimulationState() in business_link.getFrozenStateList()
228

229 230
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isAccountable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
231 232 233
  def isAccountable(self):
    """
      Returns 1 if this needs to be accounted
234 235 236
      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
237
    """
238
    return self.getParentValue().isAccountable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
239 240 241 242 243 244


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

  security.declareProtected(Permissions.ModifyPortalContent, 'expand')
245
  def expand(self, force=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
246
    """
247 248 249 250 251 252 253 254 255
    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.
    """
Sebastien Robin's avatar
Sebastien Robin committed
256
    portal_rules = getToolByName(self.getPortalObject(), 'portal_rules')
257 258 259 260 261 262 263 264 265 266 267 268 269 270

    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()
271
      if ref and ref not in applicable_rule_dict:
272 273
        applicable_rule_dict[ref] = rule

274
    for applied_rule in list(self.objectValues()):
275 276 277 278 279 280 281 282
      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()
283
      if rule_type not in applied_rule_dict:
284 285 286 287 288 289 290 291 292 293 294 295 296 297
        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
298 299 300 301 302 303 304 305 306 307

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

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

308 309 310 311 312
  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
313
    """
314 315
    delivery_value = self.getDeliveryValue()
    if delivery_value is None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
316 317 318
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
319
        return order
Jean-Paul Smets's avatar
Jean-Paul Smets committed
320 321
      else:
        # Ex. zero stock rule
322
        return ra
Jean-Paul Smets's avatar
Jean-Paul Smets committed
323
    else:
324 325
      explanation_value = delivery_value
      portal = self.getPortalObject()
Sebastien Robin's avatar
Sebastien Robin committed
326 327
      delivery_type_list = self.getPortalDeliveryTypeList() \
              + self.getPortalOrderTypeList()
328 329
      while explanation_value.getPortalType() not in delivery_type_list and \
          explanation_value != portal:
330
            explanation_value = explanation_value.getParentValue()
331
      if explanation_value != portal:
332
        return explanation_value
333

Jean-Paul Smets's avatar
Jean-Paul Smets committed
334
  # Deliverability / orderability
335 336
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isOrderable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
337
  def isOrderable(self):
338 339
    # the value of this method is no longer used.
    return True
Jean-Paul Smets's avatar
Jean-Paul Smets committed
340

341 342
  getOrderable = isOrderable

343 344
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDeliverable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
345
  def isDeliverable(self):
346 347
    # the value of this method is no longer used.
    return True
Jean-Paul Smets's avatar
Jean-Paul Smets committed
348

349
  getDeliverable = isDeliverable
350

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
351 352 353
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDeletable')
  def isDeletable(self):
Nicolas Dumazet's avatar
Nicolas Dumazet committed
354
    return not self.isFrozen() and not self._isTreeDelivered()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
355

356
  # Simulation Dates - acquire target dates
357 358
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStartDate')
359
  def getOrderStartDate(self):
360
    # 'order' category is deprecated. it is kept for compatibility.
361 362 363
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStartDate()
364 365 366
    delivery_value = self.getDeliveryValue()
    if delivery_value is not None:
      return delivery_value.getStartDate()
367

368 369
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStopDate')
370
  def getOrderStopDate(self):
371
    # 'order' category is deprecated. it is kept for compatibility.
372 373 374
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStopDate()
375 376 377
    delivery_value = self.getDeliveryValue()
    if delivery_value is not None:
      return delivery_value.getStopDate()
Romain Courteaud's avatar
Romain Courteaud committed
378

379 380
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStartDateList')
Romain Courteaud's avatar
Romain Courteaud committed
381 382
  def getDeliveryStartDateList(self):
    """
383
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
384 385 386 387 388 389
    """
    start_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      start_date_list.append(delivery_movement.getStartDate())
    return start_date_list
390

391 392
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStopDateList')
Romain Courteaud's avatar
Romain Courteaud committed
393 394
  def getDeliveryStopDateList(self):
    """
395
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
396 397 398 399 400 401
    """
    stop_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      stop_date_list.append(delivery_movement.getStopDate())
    return stop_date_list
402

403 404
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryQuantity')
Romain Courteaud's avatar
Romain Courteaud committed
405 406
  def getDeliveryQuantity(self):
    """
407
      Returns the quantity of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
408
    """
409
    quantity = 0.0
Romain Courteaud's avatar
Romain Courteaud committed
410 411 412 413
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      quantity = delivery_movement.getQuantity()
    return quantity
414

415 416
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isConvergent')
417 418
  def isConvergent(self):
    """
419
      Returns true if the Simulation Movement is convergent with the
420
      the delivery value
421 422 423
    """
    return not self.isDivergent()

424
  security.declareProtected( Permissions.AccessContentsInformation,
425
      'isDivergent')
426 427
  def isDivergent(self):
    """
428
      Returns true if the Simulation Movement is divergent from the
429
      the delivery value
430
    """
431 432 433 434 435 436 437 438 439 440
    return self.getParentValue().isDivergent(self)

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

441 442
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDefaultDeliveryProperties')
443 444
  def setDefaultDeliveryProperties(self):
    """
445 446
    Sets the delivery_ratio and delivery_error properties to the
    calculated value
447 448 449 450 451
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      delivery.updateSimulationDeliveryProperties(movement_list = [self])

452 453
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCorrectedQuantity')
454 455
  def getCorrectedQuantity(self):
    """
456 457
    Returns the quantity property deducted by the possible profit_quantity and
    taking into account delivery error
458 459 460 461 462

    NOTE: XXX-JPS This method should not use profit_quantity. Profit and loss
          quantities are now only handled through explicit movements.
          Look are invocations of _isProfitAndLossMovement in
          ERP5.mixin.rule to understand how.
463
    """
464
    quantity = self.getQuantity()
465 466 467
    profit_quantity = self.getProfitQuantity() or 0
    delivery_error = self.getDeliveryError() or 0
    return quantity - profit_quantity + delivery_error
468

469 470
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovement')
471 472 473
  def getRootSimulationMovement(self):
    """
      Return the root simulation movement in the simulation tree.
474
      FIXME : this method should be called getRootSimulationMovementValue
475
    """
476
    parent_applied_rule = self.getParentValue()
477 478 479 480 481
    if parent_applied_rule.getRootAppliedRule() == parent_applied_rule:
      return self
    else:
      return parent_applied_rule.getRootSimulationMovement()

482 483
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovementUid')
484 485 486 487 488 489 490 491 492
  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

493
  security.declareProtected( Permissions.AccessContentsInformation,
494
                             'getRootCausalityValueList')
495 496 497 498 499 500 501 502
  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()
503

504
  # XXX FIXME Use a interaction workflow instead
505
  # XXX This behavior is now done by simulation_movement_interaction_workflow
506
  # The call to activate() must be done after actual call to
507
  # setDelivery() on the movement,
508
  # but activate() must be called on the previous delivery...
509 510 511 512 513 514 515 516
  #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(
517
  #                activity='SQLQueue',
518
  #                after_path_and_method_id=(
519 520
  #                                        self.getPath(),
  #                                        ['immediateReindexObject',
521 522
  #                                         'recursiveImmediateReindexObject']))
  #    activity.edit()
523

524 525 526 527 528 529 530 531
  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
    """
532
    tv = getTransactionalVariable(self) # XXX-JPS abbreviation wrong
533 534 535 536
    cache = tv.setdefault(TREE_DELIVERED_CACHE_KEY, {})
    cache_enabled = cache.get(TREE_DELIVERED_CACHE_ENABLED, 0)

    def getTreeDelivered(movement, ignore_first=0):
537
      if not ignore_first:
538 539 540 541 542 543 544 545 546 547 548 549 550 551
        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]
552
      except KeyError:
553 554 555 556 557 558
        result = getTreeDelivered(self, ignore_first=ignore_first)
        cache[rule_key] = result
        return result
    else:
      return getTreeDelivered(self, ignore_first=ignore_first)

559 560 561 562 563 564 565
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isBuildable')
  def isBuildable(self):
    """Simulation Movement buildable logic"""
    if self.getDeliveryValue() is not None:
      # already delivered
      return False
566

Sebastien Robin's avatar
Sebastien Robin committed
567
    # might be buildable - business path dependent
568
    business_link = self.getCausalityValue(portal_type='Business Link')
569
    explanation_value = self.getExplanationValue()
570
    if business_link is None or explanation_value is None:
571
      return True
Sebastien Robin's avatar
Sebastien Robin committed
572

Julien Muchembled's avatar
Julien Muchembled committed
573 574 575
    ## XXX Code below following line has been moved to BusinessPath (cf r37116)
    #return len(business_path.filterBuildableMovementList([self])) == 1

576
    predecessor_state = business_link.getPredecessorValue()
Sebastien Robin's avatar
Sebastien Robin committed
577
    if predecessor_state is None:
578
      # first one, can be built
579
      return True # XXX-JPS wrong cause root is marked
580

Sebastien Robin's avatar
Sebastien Robin committed
581 582 583 584 585 586 587 588 589 590 591 592 593
    # movement is not built, and corresponding business path
    # has predecessors: check movements related to those predecessors!
    predecessor_path_list = predecessor_state.getSuccessorRelatedValueList()

    def isBuiltAndCompleted(simulation, path):
      return simulation.getCausalityValue() is not None and \
          simulation.getSimulationState() in path.getCompletedStateList()

    ### Step 1:
    ## Explore ancestors in ZODB (cheap)
    #

    # store a causality -> causality_related_movement_list mapping
Julien Muchembled's avatar
Julien Muchembled committed
594 595 596 597 598 599
    causality_dict = {}
    current = self.getParentValue().getParentValue()
    while current.getPortalType() == "Simulation Movement":
      causality_dict[current.getCausality(portal_type='Business Link')] = \
        current
      current = current.getParentValue().getParentValue()
Sebastien Robin's avatar
Sebastien Robin committed
600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722

    remaining_path_set = set()
    for path in predecessor_path_list:
      related_simulation = causality_dict.get(path.getRelativeUrl())
      if related_simulation is None:
        remaining_path_set.add(path)
        continue
      # XXX assumption is made here that if we find ONE completed ancestor
      # movement of self that is related to a predecessor path, then
      # that predecessor path is completed. Is it True? (aka when
      # Business Process goes downwards, is the maximum movements per
      # predecessor 1 or can we have more?)
      if not isBuiltAndCompleted(related_simulation, path):
        return False

    # in 90% of cases, Business Path goes downward and this is enough
    if not remaining_path_set:
      return True

    # But sometimes we have to dig deeper

    ### Step 2:
    ## Try catalog to find descendant movements, knowing
    # that it can be incomplete

    class treeNode(dict):
      """
      Used to cache accesses to ZODB objects.
      The idea is to put in visited_movement_dict the objects we've already
      loaded from ZODB in Step #2 to avoid loading them again in Step #3.

      - self represents a single ZODB container c
      - self.visited_movement_dict contains an id->(ZODB obj) cache for
        subobjects of c
      - self[id] contains the treeNode representing c[id]
      """
      def __init__(self):
        dict.__init__(self)
        self.visited_movement_dict = dict()

    path_tree = treeNode()
    def updateTree(simulation_movement, path):
      tree_node = path_tree
      movement_path = simulation_movement.getPhysicalPath()
      simulation_movement_id = movement_path[-1]
      # find container
      for path_id in movement_path[:-1]:
        tree_node = tree_node.setdefault(path_id, treeNode())
      # and mark the object as visited
      tree_node.visited_movement_dict[simulation_movement_id] = (simulation_movement, path)

    portal_catalog = self.getPortalObject().portal_catalog
    catalog_simulation_movement_list = portal_catalog(
      portal_type='Simulation Movement',
      causality_uid=[p.getUid() for p in remaining_path_set],
      path='%s/%%' % self.getPath())

    for movement in catalog_simulation_movement_list:
      path = movement.getCausalityValue()
      if not isBuiltAndCompleted(movement, path):
        return False
      updateTree(movement, path)

    ### Step 3:
    ## We had no luck, we have to explore descendant movements in ZODB
    #
    def descendantGenerator(document, tree_node, path_set_to_check):
      """
      generator yielding Simulation Movement descendants of document.
      It does _not_ explore the whole subtree if iteration is stopped.

      It uses the tree we built previously to avoid loading again ZODB
      objects that we already loaded during catalog querying

      path_set_to_check contains a set of Business Paths that we are
      interested in. A branch is only explored if this set is not
      empty; a movement is only yielded if its causality value is in this set
      """
      object_id_list = document.objectIds()
      for id in object_id_list:
        if id not in tree_node.visited_movement_dict:
          # we had not visited it in step #2
          subdocument = document._getOb(id)
          if subdocument.getPortalType() == "Simulation Movement":
            path = subdocument.getCausalityValue()
            t = (subdocument, path)
            tree_node.visited_movement_dict[id] = t
            if path in path_set_to_check:
              yield t
          else:
            # it must be an Applied Rule
            subtree = tree_node.get(id, treeNode())
            for d in descendantGenerator(subdocument,
                                         subtree,
                                         path_set_to_check):
              yield d

      for id, t in tree_node.visited_movement_dict.iteritems():
        subdocument, path = t
        to_check = path_set_to_check
        # do we need to change/copy the set?
        if path in to_check:
          if len(to_check) == 1:
            # no more paths to check in this branch
            continue
          to_check = to_check.copy()
          to_check.remove(path)
        subtree = tree_node.get(id, treeNode())
        for d in descendantGenerator(subdocument, subtree, to_check):
          yield d

    # descend in the tree to find self:
    tree_node = path_tree
    for path_id in self.getPhysicalPath():
      tree_node = tree_node.get(path_id, treeNode())

    # explore subobjects of self
    for descendant, path in descendantGenerator(self,
                                                tree_node,
                                                remaining_path_set):
      if not isBuiltAndCompleted(descendant, path):
        return False

723
    return True
724

725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762
  def getSolverProcessValueList(self, movement=None, validation_state=None):
    """
    Returns the list of solver processes which are
    are in a given state and which apply to delivery_or_movement.
    This method is useful to find applicable solver processes
    for a delivery.

    movement -- not applicable

    validation_state -- a state of a list of states
                        to filter the result
    """
    raise NotImplementedError

  def getSolverDecisionValueList(self, movement=None, validation_state=None):
    """
    Returns the list of solver decisions which apply
    to a given movement.

    movement -- not applicable

    validation_state -- a state of a list of states
                        to filter the result
    """
    raise NotImplementedError

  def getSolvedPropertyApplicationValueList(self, movement=None, divergence_tester=None):
    """
    Returns the list of documents at which a given divergence resolution
    can be resolved at. For example, in most cases, date divergences can
    only be resolved at delivery level whereas quantities are usually
    resolved at cell level.

    The result of this method is a list of ERP5 documents.

    movement -- not applicable
    """
    raise NotImplementedError
763 764 765 766

  security.declareProtected(Permissions.AccessContentsInformation,
                            'getMappedProperty')
  def getMappedProperty(self, property):
767
    mapping = self.getPropertyMappingValue()
768
    if mapping is not None:
769
      # Special case: corrected quantity is difficult to handle,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
770
      # because, if quantity is inverse in the mapping, other
771
      # parameters, profit quantity (deprecated) and delivery error,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
772
      # must be inverse as well.
773 774 775 776 777 778 779 780 781 782 783
      if property == 'corrected_quantity':
        mapped_quantity_id = mapping.getMappedPropertyId('quantity')
        quantity = mapping.getMappedProperty(self, 'quantity')
        profit_quantity = self.getProfitQuantity() or 0
        delivery_error = self.getDeliveryError() or 0
        if mapped_quantity_id[:1] == '-':
          # XXX what about if "quantity | -something_different" is
          # specified?
          return quantity + profit_quantity - delivery_error
        else:
          return quantity - profit_quantity + delivery_error
784 785 786
      return mapping.getMappedProperty(self, property)
    else:
      return self.getProperty(property)
787 788 789 790 791 792 793 794 795

  security.declareProtected(Permissions.ModifyPortalContent,
                            'setMappedProperty')
  def setMappedProperty(self, property, value):
    mapping = self.getPropertyMappingValue()
    if mapping is not None:
      return mapping.setMappedProperty(self, property, value)
    else:
      return self.setProperty(property, value)