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

from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface

35
from Products.ERP5.Document.Movement import Movement
Jean-Paul Smets's avatar
Jean-Paul Smets committed
36 37 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 83 84 85 86 87 88 89 90 91 92 93 94 95

from zLOG import LOG

# 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()
96
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
97 98 99 100 101 102 103 104 105 106 107 108 109

  # Declarative interfaces
  __implements__ = ( Interface.Variated, )

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem
                    , PropertySheet.CategoryCore
                    , PropertySheet.Amount
                    , PropertySheet.Task
                    , PropertySheet.Arrow
                    , PropertySheet.Movement
                    , PropertySheet.Simulation
110 111 112
                    # Need industrial_phase
                    , PropertySheet.TransformedResource
                    , PropertySheet.AppliedRule
113
                    , PropertySheet.ItemAggregation
Jean-Paul Smets's avatar
Jean-Paul Smets committed
114
                    )
115

116 117 118
  def tpValues(self) :
    """ show the content in the left pane of the ZMI """
    return self.objectValues()
119

Jean-Paul Smets's avatar
Jean-Paul Smets committed
120
  # Price should be acquired
121 122
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getPrice')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
123 124 125 126 127
  def getPrice(self, context=None, REQUEST=None, **kw):
    """
    """
    return self._baseGetPrice() # Call the price method

128 129
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCausalityState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
130 131 132 133 134 135
  def getCausalityState(self):
    """
      Returns the current state in causality
    """
    return getattr(self, 'causality_state', 'solved')

136 137
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setCausalityState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
138 139 140 141 142 143
  def setCausalityState(self, value):
    """
      Change causality state
    """
    self.causality_state = value

144 145
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
146 147 148 149
  def getSimulationState(self, id_only=1):
    """
      Returns the current state in simulation

150 151
      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
152 153 154 155 156 157 158 159 160 161 162 163

      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:
      parent_state = self.aq_parent.getSimulationState()
      return parent_to_movement_simulation_state[parent_state]
164
    except (KeyError, AttributeError):
165 166
      LOG('ERP5 WARNING:',100, 'Could not acquire getSimulationState on %s'
                                % self.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
167 168
      return None

169 170
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isAccountable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
171 172 173
  def isAccountable(self):
    """
      Returns 1 if this needs to be accounted
174 175 176
      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
177
    """
178
    return self.getParentValue().isAccountable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
179 180

  # Ordering / Delivering
181 182
  security.declareProtected( Permissions.AccessContentsInformation,
                             'requiresOrder')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
183 184 185 186 187 188 189 190 191
  def requiresOrder(self):
    """
      Returns 1 if this needs to be ordered
    """
    if isOrderable():
      return len(self.getCategoryMembership('order')) is 0
    else:
      return 0

192 193
  security.declareProtected( Permissions.AccessContentsInformation,
                             'requiresDelivery')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
194 195 196 197 198 199 200 201 202 203 204 205 206 207
  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')
208
  def expand(self, force=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
209 210 211 212 213 214 215 216
    """
      Parses all existing applied rules and make sure they apply.
      Checks other possible rules and starts expansion process
      (instanciates rule and calls expand on rule)

      Only movements which applied rule parent is expanded can
      be expanded.
    """
217 218 219 220 221
    # XXX Default behaviour is not to expand if it has already been
    # expanded, but some rules are configuration rules and need to be
    # reexpanded  each time, because the rule apply only if predicates
    # are true, then this kind of rule must always be tested. Currently,
    # we know that invoicing rule acts like this, and that it comes after
222
    # invoice or invoicing_rule, so we if we come from invoince rule or
223
    # invoicing rule, we always expand regardless of the causality state.
224
    if ((self.getParentValue().getSpecialiseId() not in
225 226
         ('default_invoicing_rule', 'default_invoice_rule')
         and self.getCausalityState() == 'expanded' ) or \
227
         len(self.objectIds()) != 0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
228 229
      # Reexpand
      for my_applied_rule in self.objectValues():
230
        my_applied_rule.expand(force=force,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
231 232 233 234 235
    else:
      portal_rules = getToolByName(self, 'portal_rules')
      # Parse each rule and test if it applies
      for rule in portal_rules.objectValues():
        if rule.test(self):
236 237
          my_applied_rule = rule.constructNewAppliedRule(self, **kw)
      for my_applied_rule in self.objectValues() :
238
        my_applied_rule.expand(force=force,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
239 240 241 242 243 244 245 246 247 248 249 250
      # Set to expanded
      self.setCausalityState('expanded')

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

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

251 252
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanation')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
253
  def getExplanation(self):
254 255
    """Returns the delivery's relative_url if any or the order's
    relative_url related to the root applied rule if any.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
256
    """
257 258 259
    explanation_value = self.getExplanationValue()
    if explanation_value is not None :
      return explanation_value.getRelativeUrl()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
260

261 262
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationUid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
263
  def getExplanationUid(self):
264 265
    """Returns the delivery's uid if any or the order's uid related to
    the root applied rule if any.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
266
    """
267 268 269
    explanation_value = self.getExplanationValue()
    if explanation_value is not None :
      return explanation_value.getUid()
270

271 272 273 274 275
  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
276 277 278 279 280
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
281
        return order
Jean-Paul Smets's avatar
Jean-Paul Smets committed
282 283
      else:
        # Ex. zero stock rule
284
        return ra
Jean-Paul Smets's avatar
Jean-Paul Smets committed
285
    else:
286
      explanation_value = self.getDeliveryValue()
287 288
      while explanation_value.getPortalType() not in \
              self.getPortalDeliveryTypeList() and \
289
          explanation_value != self.getPortalObject():
290
            explanation_value = explanation_value.getParentValue()
291
      if explanation_value != self.getPortalObject():
292
        return explanation_value
293

Jean-Paul Smets's avatar
Jean-Paul Smets committed
294
  # Deliverability / orderability
295 296
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isOrderable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
297 298 299 300
  def isOrderable(self):
    applied_rule = self.aq_parent
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
301
      return rule.isOrderable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
302 303
    return 0

304 305
  getOrderable = isOrderable

306 307
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDeliverable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
308 309 310 311
  def isDeliverable(self):
    applied_rule = self.aq_parent
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
312
      return rule.isDeliverable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
313 314
    return 0

315
  getDeliverable = isDeliverable
316

317
  # Simulation Dates - acquire target dates
318 319
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStartDate')
320 321 322 323
  def getOrderStartDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStartDate()
324

325 326
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStopDate')
327 328 329 330
  def getOrderStopDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStopDate()
Romain Courteaud's avatar
Romain Courteaud committed
331

332 333
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStartDateList')
Romain Courteaud's avatar
Romain Courteaud committed
334 335
  def getDeliveryStartDateList(self):
    """
336
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
337 338 339 340 341 342
    """
    start_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      start_date_list.append(delivery_movement.getStartDate())
    return start_date_list
343

344 345
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStopDateList')
Romain Courteaud's avatar
Romain Courteaud committed
346 347
  def getDeliveryStopDateList(self):
    """
348
      Returns the stop date of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
349 350 351 352 353 354
    """
    stop_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      stop_date_list.append(delivery_movement.getStopDate())
    return stop_date_list
355

356 357
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryQuantity')
Romain Courteaud's avatar
Romain Courteaud committed
358 359
  def getDeliveryQuantity(self):
    """
360
      Returns the quantity of related delivery
Romain Courteaud's avatar
Romain Courteaud committed
361
    """
362
    quantity = 0.0
Romain Courteaud's avatar
Romain Courteaud committed
363 364 365 366
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      quantity = delivery_movement.getQuantity()
    return quantity
367

368 369
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isConvergent')
370 371
  def isConvergent(self):
    """
372
      Returns true if the Simulation Movement is convergent with the
373
      the delivery value
374 375 376
    """
    return not self.isDivergent()

377
  security.declareProtected( Permissions.AccessContentsInformation,
378
      'isDivergent')
379 380
  def isDivergent(self):
    """
381
      Returns true if the Simulation Movement is divergent from the
382
      the delivery value
383
    """
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    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)

402 403
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDefaultDeliveryProperties')
404 405
  def setDefaultDeliveryProperties(self):
    """
406 407
    Sets the delivery_ratio and delivery_error properties to the
    calculated value
408 409 410 411 412
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      delivery.updateSimulationDeliveryProperties(movement_list = [self])

413 414
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCorrectedQuantity')
415 416 417 418 419 420 421 422 423 424 425
  def getCorrectedQuantity(self):
    """
    Returns the quantity property deducted by the possible profit_quantity
    """
    quantity = self.getQuantity()
    profit_quantity = self.getProfitQuantity()
    if quantity is not None:
      if profit_quantity:
        return quantity - profit_quantity
      return quantity
    return None
426

427 428
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovement')
429 430 431
  def getRootSimulationMovement(self):
    """
      Return the root simulation movement in the simulation tree.
432
      FIXME : this method should be called getRootSimulationMovementValue
433
    """
434
    parent_applied_rule = self.getParentValue()
435 436 437 438 439
    if parent_applied_rule.getRootAppliedRule() == parent_applied_rule:
      return self
    else:
      return parent_applied_rule.getRootSimulationMovement()

440 441
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovementUid')
442 443 444 445 446 447 448 449 450
  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

451
  security.declareProtected( Permissions.AccessContentsInformation,
452
                             'getRootCausalityValueList')
453 454 455 456 457 458 459 460
  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()
461

462
  # XXX FIXME Use a interaction workflow instead
463
  # XXX This behavior is now done by simulation_movement_interaction_workflow
464
  # The call to activate() must be done after actual call to
465
  # setDelivery() on the movement,
466
  # but activate() must be called on the previous delivery...
467 468 469 470 471 472 473 474
  #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(
475
  #                activity='SQLQueue',
476
  #                after_path_and_method_id=(
477 478
  #                                        self.getPath(),
  #                                        ['immediateReindexObject',
479 480
  #                                         'recursiveImmediateReindexObject']))
  #    activity.edit()
481