SimulationMovement.py 14.5 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2 3 4 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 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
##############################################################################
#
# Copyright (c) 2002 Nexedi SARL and Contributors. All Rights Reserved.
#                    Jean-Paul Smets-Solane <jp@nexedi.com>
#
# 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

from Movement import Movement

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'
  add_permission = Permissions.AddERP5Content
  isPortalContent = 1
  isRADContent = 1
  isMovement = 1

  # Declarative security
  security = ClassSecurityInfo()
  security.declareObjectProtected(Permissions.View)

  # 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
                    )

  # Factory Type Information
  factory_type_information = \
      {    'id'             : portal_type
         , 'meta_type'      : meta_type
         , 'description'    : """\
An Organisation object holds the information about
an organisation (ex. a division in a company, a company,
a service in a public administration)."""
         , 'icon'           : 'segment_icon.gif'
         , 'product'        : 'ERP5'
         , 'factory'        : 'addSimulationMovement'
         , 'immediate_view' : 'predicate_view'
         , 'actions'        :
        ( { 'id'            : 'view'
          , 'name'          : 'View'
          , 'category'      : 'object_view'
          , 'action'        : 'predicate_view'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'print'
          , 'name'          : 'Print'
          , 'category'      : 'object_print'
          , 'action'        : 'segment_print'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'metadata'
          , 'name'          : 'Metadata'
          , 'category'      : 'object_view'
          , 'action'        : 'metadata_edit'
          , 'permissions'   : (
              Permissions.View, )
          }
        , { 'id'            : 'translate'
          , 'name'          : 'Translate'
          , 'category'      : 'object_action'
          , 'action'        : 'segment_view'
          , 'permissions'   : (
              Permissions.TranslateContent, )
          }
        )
      }
  # Price should be acquired
  security.declareProtected(Permissions.AccessContentsInformation, 'getPrice')
  def getPrice(self, context=None, REQUEST=None, **kw):
    """
    """
    return self._baseGetPrice() # Call the price method

Yoshinori Okuji's avatar
Yoshinori Okuji committed
167
  security.declareProtected(Permissions.AccessContentsInformation, 'getCausalityState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
168 169 170 171 172 173 174 175 176 177 178 179
  def getCausalityState(self):
    """
      Returns the current state in causality
    """
    return getattr(self, 'causality_state', 'solved')

  def setCausalityState(self, value):
    """
      Change causality state
    """
    self.causality_state = value

Yoshinori Okuji's avatar
Yoshinori Okuji committed
180
  security.declareProtected(Permissions.AccessContentsInformation, 'getSimulationState')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 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 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
  def getSimulationState(self, id_only=1):
    """
      Returns the current state in simulation

      Inherit from order or delivery or parent (but use a conversion table to make
      orders planned when parent is confirmed)

      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]
    except:
      LOG('ERP5 WARNING:',100, 'Could not acquire getSimulationState on %s' % self.getRelativeUrl())
      return None

  # Acounting
  security.declareProtected(Permissions.AccessContentsInformation, 'isAccountable')
  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
  security.declareProtected(Permissions.AccessContentsInformation, 'requiresOrder')
  def requiresOrder(self):
    """
      Returns 1 if this needs to be ordered
    """
    if isOrderable():
      return len(self.getCategoryMembership('order')) is 0
    else:
      return 0

  security.declareProtected(Permissions.AccessContentsInformation, 'requiresDelivery')
  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')
  def expand(self):
    """
      -> new status : expanded

      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.
    """
    #LOG('In simulation expand',0, str(self.id))
    self.reindexObject()
    if self.getCausalityState() is 'expanded':
      # Reexpand
      for my_applied_rule in self.objectValues():
        my_applied_rule.expand()
    else:
      portal_rules = getToolByName(self, 'portal_rules')
      # Parse each applied rule and test if it applied
      #for applied_rule in self.objectValues():
      #  if not applied_rule.test():
      #    # delete
      # Parse each rule and test if it applies
      for rule in portal_rules.objectValues():
        if rule.test(self):
          my_applied_rule = rule.constructNewAppliedRule(self)
          my_applied_rule.expand()
      # Set to expanded
      self.setCausalityState('expanded')

  #expand = WorkflowMethod(expand) USELESS NOW

  security.declareProtected(Permissions.ModifyPortalContent, 'solve')
  def solve(self, solver, new_target=None):
    """
       Makes the movement expandable again

       -> new status -> solved

       Once a movement has been updated with consistent
       target and planned values, it is marked as solved
       and can therefore be expanded again
    """
    self.portal_simulation.applyTargetSolver(self, solver, new_target=new_target)
    self.setCausalityState('solved')

  #solve = WorkflowMethod(solve) USELESS NOW

  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
  security.declareProtected(Permissions.AccessContentsInformation, 'getMovementIndex')
  def getMovementIndex(self):
    """
      Returns a list of indexable movements
    """
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
    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(),
                 'delivery_uid'                   : self.getDeliveryUid(),
                 '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(),
                 'source_total_asset_price'       : 0.0,
                 'destination_total_asset_price'  : 0.0,
Jean-Paul Smets's avatar
Jean-Paul Smets committed
339 340 341 342 343
                } ]
    for m in self.objectValues():
      result.extend(m.getMovementIndex())
    return result

Yoshinori Okuji's avatar
Yoshinori Okuji committed
344
  security.declareProtected(Permissions.View, 'hasActivity')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
345 346 347 348 349 350 351 352 353 354 355 356
  def hasActivity(self, **kw):
    """
      We reindex the whole applied rule
    """
    return self.getRootAppliedRule().hasActivity(**kw)

  security.declareProtected(Permissions.View, 'reindexObject')
  def reindexObject(self, **kw):
    """
      We reindex the whole applied rule (only once)
    """
    self.getRootAppliedRule().reindexObject() # Reindex the whole applied rule
Jean-Paul Smets's avatar
Jean-Paul Smets committed
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407

  security.declareProtected(Permissions.AccessContentsInformation, 'getExplanation')
  def getExplanation(self):
    """
      Returns the delivery if any or the order related to the root applied rule if any
      Name should be changed to generic name (getExplanationUid)
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
        return order.getRelativeUrl()
      else:
        # Ex. zero stock rule
        return ra.getRelativeUrl()
    else:
      return self.getDelivery()

  security.declareProtected(Permissions.AccessContentsInformation, 'getExplanationUid')
  def getExplanationUid(self):
    """
      Returns the delivery if any or the order related to the root applied rule if any
      Name should be changed to generic name (getExplanationUid)
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
        return order.getUid()
      else:
        # Ex. zero stock rule
        return ra.getUid()
    else:
      return self.getDeliveryUid()

  security.declareProtected(Permissions.AccessContentsInformation, 'getExplanationValue')
  def getExplanationValue(self):
    """
      Returns the delivery if any or the order related to the root applied rule if any
      Name should be changed to generic name (getExplanationUid)
    """
    if self.getDeliveryValue() is None:
      ra = self.getRootAppliedRule()
      order = ra.getCausalityValue()
      if order is not None:
        return order
      else:
        # Ex. zero stock rule
        return ra
    else:
      return self.getDeliveryValue()