SimulationMovement.py 21.7 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 35 36
#
# 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.CMFCore.WorkflowCore import WorkflowMethod

from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Core import MetaNode, MetaResource

37
from Products.ERP5.Document.Movement import Movement
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 96 97

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

  # 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
112 113 114
                    # Need industrial_phase
                    , PropertySheet.TransformedResource
                    , PropertySheet.AppliedRule
115
                    , PropertySheet.ItemAggregation
Jean-Paul Smets's avatar
Jean-Paul Smets committed
116
                    )
117 118 119 120 121
  
  def tpValues(self) :
    """ show the content in the left pane of the ZMI """
    return self.objectValues()
  
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122
  # Price should be acquired
123 124
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getPrice')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
125 126 127 128 129
  def getPrice(self, context=None, REQUEST=None, **kw):
    """
    """
    return self._baseGetPrice() # Call the price method

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

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

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

152 153
      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
154 155 156 157 158 159 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()
    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]
166
    except KeyError, AttributeError:
167 168
      LOG('ERP5 WARNING:',100, 'Could not acquire getSimulationState on %s'
                                % self.getRelativeUrl())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
169 170
      return None

171 172
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isAccountable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
173 174 175 176 177 178 179 180 181
  def isAccountable(self):
    """
      Returns 1 if this needs to be accounted
      Only account movements which are not associated to a delivery
      Whenever delivery is there, delivery has priority
    """
    return (self.getDeliveryValue() is None)

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

193 194
  security.declareProtected( Permissions.AccessContentsInformation,
                             'requiresDelivery')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
195 196 197 198 199 200 201 202 203 204 205 206 207 208
  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')
209
  def expand(self, force=0, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
210 211 212 213 214 215 216 217
    """
      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.
    """
218 219 220 221 222 223 224
    # 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
    # invoice or invoicing_rule, so we if we come from invoince rule or 
    # invoicing rule, we always expand regardless of the causality state.
225
    if ((self.getParentValue().getSpecialiseId() not in 
226 227
         ('default_invoicing_rule', 'default_invoice_rule')
         and self.getCausalityState() == 'expanded' ) or \
228
         len(self.objectIds()) != 0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
229 230
      # Reexpand
      for my_applied_rule in self.objectValues():
231
        my_applied_rule.expand(force=force,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
232 233 234 235 236
    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):
237 238
          my_applied_rule = rule.constructNewAppliedRule(self, **kw)
      for my_applied_rule in self.objectValues() :
239
        my_applied_rule.expand(force=force,**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
      # 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')

  #diverge = WorkflowMethod(diverge) USELESS NOW

  # isDivergent is defined in movement

  # Optimized Reindexing
257 258
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getMovementIndex')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
259 260 261 262
  def getMovementIndex(self):
    """
      Returns a list of indexable movements
    """
263 264 265 266 267 268 269 270 271
    result = [ { 'uid'                            : self.getUid(),
                 'id'                             : self.getId(),
                 'portal_type'                    : self.getPortalType(),
                 'url'                            : self.getUrl(),
                 'relative_url'                   : self.getRelativeUrl(),
                 'parent_uid'                     : self.getParentUid(),
                 'simulation_state'               : self.getSimulationState(),
                 'order_uid'                      : self.getOrderUid(),
                 'explanation_uid'                : self.getExplanationUid(),
272
                 #'delivery_uid'                   : self.getDeliveryUid(),
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                 'source_uid'                     : self.getSourceUid(),
                 'destination_uid'                : self.getDestinationUid(),
                 'source_section_uid'             : self.getSourceSectionUid(),
                 'destination_section_uid'        : self.getDestinationSectionUid(),
                 'resource_uid'                   : self.getResourceUid(),
                 'quantity'                       : self.getNetConvertedQuantity(),
                 'start_date'                     : self.getStartDate(),
                 'stop_date'                      : self.getStopDate(),
                 'target_quantity'                : self.getNetConvertedTargetQuantity(),
                 'target_start_date'              : self.getTargetStartDate(),
                 'target_stop_date'               : self.getTargetStopDate(),
                 'price'                          : self.getPrice(),
                 'total_price'                    : self.getTotalPrice(),
                 'target_total_price'             : self.getTargetTotalPrice(),
                 'has_cell_content'               : 0,
                 'accountable'                    : self.isAccountable(),
                 'orderable'                      : self.isOrderable(),
                 'deliverable'                    : self.isDeliverable(),
                 'variation_text'                 : self.getVariationText(),
                 'inventory'                      : self.getInventoriatedQuantity(),
293 294
                 'source_asset_price'             : self.getSourceAssetPrice(),
                 'destination_asset_price'        : self.getDestinationAssetPrice(),
Jean-Paul Smets's avatar
Jean-Paul Smets committed
295 296 297 298 299
                } ]
    for m in self.objectValues():
      result.extend(m.getMovementIndex())
    return result

300 301
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanation')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
302
  def getExplanation(self):
303 304
    """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
305
    """
306 307 308
    explanation_value = self.getExplanationValue()
    if explanation_value is not None :
      return explanation_value.getRelativeUrl()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
309

310 311
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationUid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
312
  def getExplanationUid(self):
313 314
    """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
315
    """
316 317 318 319 320 321 322 323 324
    explanation_value = self.getExplanationValue()
    if explanation_value is not None :
      return explanation_value.getUid()
    
  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
325 326 327 328 329
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
330
        return order
Jean-Paul Smets's avatar
Jean-Paul Smets committed
331 332
      else:
        # Ex. zero stock rule
333
        return ra
Jean-Paul Smets's avatar
Jean-Paul Smets committed
334
    else:
335
      explanation_value = self.getDeliveryValue()
336 337
      while explanation_value.getPortalType() not in \
              self.getPortalDeliveryTypeList() and \
338
          explanation_value != self.getPortalObject():
339
            explanation_value = explanation_value.getParentValue()
340
      if explanation_value != self.getPortalObject():
341
        return explanation_value
342 343 344 345 346 347 348 349 350

  def isFrozen(self):
    """
      A frozen simulation movement can not change its target anylonger

      Also, once a movement is frozen, we do not calculate anylonger
      its direct consequences. (ex. we do not calculate again a transformation)
    """
    return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
351 352

  # Deliverability / orderability
353 354
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isOrderable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
355 356 357 358
  def isOrderable(self):
    applied_rule = self.aq_parent
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
359
      return rule.isOrderable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
360 361
    return 0

362 363
  getOrderable = isOrderable

364 365
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDeliverable')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
366 367 368 369
  def isDeliverable(self):
    applied_rule = self.aq_parent
    rule = applied_rule.getSpecialiseValue()
    if rule is not None:
370
      return rule.isDeliverable(self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
371 372
    return 0

373
  getDeliverable = isDeliverable
374 375

  # Simulation Dates - acquire target dates 
376 377
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStartDate')
378 379 380 381 382
  def getOrderStartDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStartDate()
  
383 384
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStopDate')
385 386 387 388
  def getOrderStopDate(self):
    order_value = self.getOrderValue()
    if order_value is not None:
      return order_value.getStopDate()
Romain Courteaud's avatar
Romain Courteaud committed
389

390 391
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStartDateList')
Romain Courteaud's avatar
Romain Courteaud committed
392 393 394 395 396 397 398 399 400 401
  def getDeliveryStartDateList(self):
    """
      Returns the stop date of related delivery(s)
    """
    start_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      start_date_list.append(delivery_movement.getStartDate())
    return start_date_list
    
402 403
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStopDateList')
Romain Courteaud's avatar
Romain Courteaud committed
404 405 406 407 408 409 410 411 412
  def getDeliveryStopDateList(self):
    """
      Returns the stop date of related delivery(s)
    """
    stop_date_list = []
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      stop_date_list.append(delivery_movement.getStopDate())
    return stop_date_list
413
  
414 415
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryQuantity')
Romain Courteaud's avatar
Romain Courteaud committed
416 417 418 419
  def getDeliveryQuantity(self):
    """
      Returns the quantity of related delivery(s)
    """
420
    quantity = 0.0
Romain Courteaud's avatar
Romain Courteaud committed
421 422 423 424 425
    delivery_movement = self.getDeliveryValue()
    if delivery_movement is not None:
      quantity = delivery_movement.getQuantity()
    return quantity
    
426 427
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isConvergent')
428 429
  def isConvergent(self):
    """
430 431
      Returns true if the Simulation Movement is convergent comparing to
      the delivery value
432 433 434
    """
    return not self.isDivergent()

435 436
  security.declareProtected( Permissions.AccessContentsInformation,
                            'isDivergent')
437 438
  def isDivergent(self):
    """
439 440
      Returns true if the Simulation Movement is divergent comparing to
      the delivery value
441 442 443 444
    """
    delivery = self.getDeliveryValue()
    if delivery is None:
      return 0
445 446
    # XXX Those properties are the same than defined in DeliveryBuilder.
    # We need to defined it only 1 time.
447 448 449
    #LOG('SimulationMovement.isDivergent',0,delivery.getPath())
    #LOG('SimulationMovement.isDivergent self.getStartDate()',0,self.getStartDate())
    #LOG('SimulationMovement.isDivergent delivery.getStartDate()',0,delivery.getStartDate())
450 451 452 453 454
    if self.getSourceSection()      != delivery.getSourceSection() or \
       self.getDestinationSection() != delivery.getDestinationSection() or \
       self.getSource()             != delivery.getSource() or \
       self.getDestination()        != delivery.getDestination() or \
       self.getResource()           != delivery.getResource() or \
455 456
       self.getVariationCategoryList() != delivery.getVariationCategoryList()\
                                                                       or \
457
       self.getAggregateList() != delivery.getAggregateList() or \
458 459
       self.getStartDate()          != delivery.getStartDate() or \
       self.getStopDate()           != delivery.getStopDate():
460 461 462 463 464 465 466 467 468 469 470
#       for method in ["getSourceSection",
#                      "getDestinationSection",
#                      "getSource",
#                      "getDestination",
#                      "getResource",
#                      "getVariationCategoryList",
#                      "getStartDate",
#                      "getStopDate"]:
#         LOG("SimulationMovement, isDivergent", 0,
#             "method: %s, self: %s , delivery: %s" % \
#             tuple([method]+[str(getattr(x,method)()) for x in (self, delivery)]))
471 472 473 474 475 476 477 478
      return 1
    d_quantity = delivery.getQuantity()
    quantity = self.getCorrectedQuantity()
    d_error = self.getDeliveryError()
    if quantity is None:
      if d_quantity is None:
        return 0
      return 1
479 480
    if d_quantity is None:
      d_quantity = 0
481 482 483
    if d_error is None:
      d_error = 0
    delivery_ratio = self.getDeliveryRatio()
484 485
    # if the delivery_ratio is None, make sure that we are
    # divergent even if the delivery quantity is 0
486
    if delivery_ratio is not None:
487
      d_quantity *= delivery_ratio
488 489
      if delivery_ratio == 0 and quantity >0:
        return 1
490 491 492 493
    if d_quantity != quantity + d_error:
      return 1
    return 0  
 
494 495
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDefaultDeliveryProperties')
496 497
  def setDefaultDeliveryProperties(self):
    """
498 499
    Sets the delivery_ratio and delivery_error properties to the
    calculated value
500 501 502 503 504
    """
    delivery = self.getDeliveryValue()
    if delivery is not None:
      delivery.updateSimulationDeliveryProperties(movement_list = [self])

505 506
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getCorrectedQuantity')
507 508 509 510 511 512 513 514 515 516 517
  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
518

519 520
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovement')
521 522 523
  def getRootSimulationMovement(self):
    """
      Return the root simulation movement in the simulation tree.
524
      FIXME : this method should be called getRootSimulationMovementValue
525
    """
526
    parent_applied_rule = self.getParentValue()
527 528 529 530 531
    if parent_applied_rule.getRootAppliedRule() == parent_applied_rule:
      return self
    else:
      return parent_applied_rule.getRootSimulationMovement()

532 533
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getRootSimulationMovementUid')
534 535 536 537 538 539 540 541 542
  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

543
  security.declareProtected( Permissions.AccessContentsInformation,
544
                             'getRootCausalityValueList')
545 546 547 548 549 550 551 552 553
  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()
    
554
  # XXX FIXME Use a interaction workflow instead
555
  # XXX This behavior is now done by simulation_movement_interaction_workflow
556 557
  # The call to activate() must be done after actual call to 
  # setDelivery() on the movement,
558
  # but activate() must be called on the previous delivery...
559 560 561 562 563 564 565 566 567 568 569 570 571 572
  #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(
  #                activity='SQLQueue', 
  #                after_path_and_method_id=(
  #                                        self.getPath(), 
  #                                        ['immediateReindexObject', 
  #                                         'recursiveImmediateReindexObject']))
  #    activity.edit()
573