Movement.py 41.4 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
#
# 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.
#
##############################################################################

29
import zope.interface
30
from warnings import warn
Jean-Paul Smets's avatar
Jean-Paul Smets committed
31 32
from AccessControl import ClassSecurityInfo

33
from Products.ERP5Type import Permissions, PropertySheet, Constraint, interfaces
34 35
from Products.ERP5Type.Base import Base

36
#from Products.ERP5.Core import MetaNode, MetaResource
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37 38 39

from Products.ERP5Type.XMLObject import XMLObject

40
from Products.ERP5.Document.Amount import Amount
Jean-Paul Smets's avatar
Jean-Paul Smets committed
41

42
from zLOG import LOG, WARNING, DEBUG
43

Jean-Paul Smets's avatar
Jean-Paul Smets committed
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
class Movement(XMLObject, Amount):
  """
    The Movement class allows to implement ERP5 universal accounting model.

    Movement instances are used in different situations:

    - Orders: Movement instances are use as a documentary object
      to define quantities in orders

    - Deliveries: movements track the actual transfer of resources
      in the past (accounting) or in the future (planning / budgetting)

    For example, the following objects are Orders:

    - a purchase order (the document we send to a supplier
      when we need some goods)

    - a sales order (the document we ask our customer
      to sign to confirm a sale)

    - a production order (the document we send to the workshop
      to confirm we need some operation / service to be achieved)

    Orders allow to describe a target, but can not be used to account
    the reality of actual transfered quantities.

    This is not the case for Deliveries:

    - an invoice (a delivery of money between abstract accounts)

    - a packing list (ie. a delivery of goods shipped)

    - a delivery report (ie. a delivery of goods received)

    - a production report (ie. a delivery of service)

    - a T/T report (a delivery of money between reals accounts)


83
    For planning, the following approach is used:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101

    1- Movements from an order are never modified once the order
       is confirmed. This is a rule. An Order is like a contract.
       It can only be amended, if all parties agree.

    2- Movements in a delivery may exist on their own
       (ex. an accounting transaction). Past movements
       can not be modified. Future movements may or may
       not be modified

    When an order is confirmed, the list of "order" movements
    it contains is copied into "delivery" movements. Each delivery
    movement contains a "causality" reference to the order
    it. This allows delivery to be completely different from order
    (ex. different resource, different date, different quantity)
    and allows to keep track of the causal relation between
    a delivery and an order.

102
    A delivery document (actually a delivery line) then points to one or more of
Jean-Paul Smets's avatar
Jean-Paul Smets committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    the "delivery" movements in the simulation. It is possible to know
    which items have been delivered by making sure each movement in the simulation
    is associated to a "delivery document".

    By looking at all "simulation"

    Delivery movements can be applied the following transformations:

    - split : one movement is cut into 2 or more movements

    - submovements : one movement "generates" many other movements.
      For example, a delivery of goods from the workshop to the stock,
      will result in a "pull" calculation which generates operations
      and sourcing based on a BOM document. The causality of each
      delivery is the "applied rule" which was used to generate submovements

    One should note that

121
    - movements are never joined (because it would break causality and
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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 167 168 169 170 171 172 173 174 175 176
      tracability)

    - movements acquire some context information from their causality

    Some submovements need no order to be "confirmed". Some submovements
    need an order to be "confirmed". For example

    - a submovement which allows to compute the CO2 emissions
      of a production facility needs no order confirmation
      (this kind of movement is mostly ised for reporting)

    - a submovement which takes some goods in a stock and
      brings them to a workshop needs some "stock movement"
      order to be "confirmed"

    - a submovement which requires someone to take his time
      for some operation nees a "service order" to be confirmed

    This means that the simulation process must make a distinction
    between different workflows applicable to a movement. For
    movements which require an order to be confirmed, the workflow
    involves the following steps:

    - an order is automaticaly generated, with "order movements"
      which become "causalities" for delivery movements (XXX
      this sound strange...)

    - each order movement is associated to one of the delivery

    As a result, a delivery movement which requires an order may
    have 2 causalities

    - one causality (ie. application of a rule)

    - another causality (ie. confirmation in an order)

    Each causality may define its own context. One context
    may be related for example to a customer request, another context
    may be related to an "internal customer" request (eg. the production manager).
    Context may eventually conflict each other.

    In a customer oriented company, movements should probably
    always be stored within the customer order and acquire
    from the order all context information.

    In a mass production facility, context may be defined in more
    than one location. This is an incentive for putting
    all movements in a simulation "box".

    The second approach is chosen for documentary consistency approach :
      in ERP5, documents rules, can be synchronized. Simulation can not be
      synchronized
  """
  meta_type = 'ERP5 Movement'
  portal_type = 'Movement'
177
  add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
178 179 180 181 182 183
  isPortalContent = 1
  isRADContent = 1
  isMovement = 1

  # Declarative security
  security = ClassSecurityInfo()
184
  security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
185 186

  # Declarative interfaces
187
  zope.interface.implements( interfaces.IVariated, )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
188 189 190 191

  # Declarative properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem
192
                    , PropertySheet.CategoryCore
Jean-Paul Smets's avatar
Jean-Paul Smets committed
193 194 195 196 197 198 199 200 201 202 203
                    , PropertySheet.Amount
                    , PropertySheet.Task
                    , PropertySheet.Arrow
                    , PropertySheet.Movement
                    , PropertySheet.Price
                    )

  # Pricing methods
  # _getPrice is defined in the order / delivery
  # Pricing mehod
  def _getPrice(self, context):
204 205
    context = self.asContext(context=context,
                             quantity=self.getConvertedQuantity())
206 207
    operand_dict = self.getPriceCalculationOperandDict(context=context)
    if operand_dict is not None:
208 209 210 211 212 213 214 215
      price = operand_dict['price']
      resource = self.getResourceValue()
      quantity_unit = self.getQuantityUnit()
      if price is not None and quantity_unit and resource is not None:
        return resource.convertQuantity(price, quantity_unit,
                                        resource.getDefaultQuantityUnit(),
                                        self.getVariationCategoryList())
      return price
Jean-Paul Smets's avatar
Jean-Paul Smets committed
216

217
  def _getTotalPrice(self, default=None, context=None, fast=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
218 219
    price = self.getPrice(context=context)
    quantity = self.getQuantity()
220 221
    if isinstance(price, (int, float)) and \
      isinstance(quantity, (int, float)):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
222 223
      return quantity * price
    else:
224
      return default
Jean-Paul Smets's avatar
Jean-Paul Smets committed
225

226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
  security.declareProtected(Permissions.AccessContentsInformation, 
          'getPriceCalculationOperandDict')
  def getPriceCalculationOperandDict(self, default=None, context=None, **kw):
    """Return a dict object which contains operands used for price
    calculation. The returned items depend on a site configuration,
    because this will invoke a custom script at the end. The only
    assumption is that the dict must contain a key 'price'
    which represents the final result of the price calculation.
    
    The purpose is to obtain descriptive information to notify the user
    of how a price is calculated in details, in particular, for invoices
    and quotations. So a script which is eventually called should provide
    all values required for generating such reports (e.g. a price,
    a price without a discount, and a discount).
    """
    # First, try a type-based method, and if not present, use 
    # the good-old-days way (which only returns a final result).
    if context is None:
      context = self
    method = context._getTypeBasedMethod('getPriceCalculationOperandDict')
246 247 248 249 250
    if method is None:
      # Try this, because when the context is an instance of a derived
      # class of Movement, Movement_getPriceCalculationOperandDict is
      # not searched.
      method = getattr(context, 'Movement_getPriceCalculationOperandDict', None)
251 252 253 254 255 256 257 258
    if method is not None:
      operand_dict = method(**kw)
      if operand_dict is None:
        return default
      assert 'price' in operand_dict 
      return operand_dict
    return {'price': context.Movement_lookupPrice()}

Jean-Paul Smets's avatar
Jean-Paul Smets committed
259
  security.declareProtected(Permissions.AccessContentsInformation, 'getPrice')
260
  def getPrice(self, default=None, context=None, evaluate=1, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
261
    """
262 263 264
      Get the Price in the context.

      If price is not stored locally, lookup a price and store it.
265 266 267

      FIXME: Don't trust this docstring, this method is not at all using the
      passed context, but uses this movement as context.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
268
    """
269 270 271 272 273 274 275
    # XXX As all accessors can recieve the default value as first positional
    # argument, so we changed the first positional argument from context to
    # default. Here we try to provide backward compatibility for scripts
    # passing the context as first positional argument, and advice them to use:
    #   context.getPrice(context=context)
    # instead of:
    #   context.getPrice(context)
Jérome Perrin's avatar
Jérome Perrin committed
276
    if isinstance(default, Base):
277 278 279 280 281 282 283 284
      msg = 'getPrice first argument is supposed to be the default value'\
            ' accessor, the context should be passed as with the context='\
            ' keyword argument'
      warn(msg, DeprecationWarning)
      LOG('ERP5', WARNING, msg)
      context = default
      default = None

285 286 287 288
    if len(kw):
      warn('Passing keyword arguments to Movement.getPrice has no effect',
           DeprecationWarning)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
289 290
    local_price = self._baseGetPrice()
    if local_price is None:
291
      # We must find a price for this movement
292
      local_price = self._getPrice(context=self)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
293 294
    return local_price

295 296
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getTotalPrice')
297
  def getTotalPrice(self, default=0.0, context=None, REQUEST=None, fast=None,
Yoshinori Okuji's avatar
Yoshinori Okuji committed
298 299 300 301
                    **kw):
    """Return the total price in the context.

    The optional parameter "fast" is for compatibility, and will be ignored.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
302
    """
303 304 305 306 307 308 309 310 311
    # see getPrice
    if isinstance(default, Base) and context is None:
      msg = 'getTotalPrice first argument is supposed to be the default value'\
            ' accessor, the context should be passed as with the context='\
            ' keyword argument'
      warn(msg, DeprecationWarning)
      LOG('ERP5', WARNING, msg)
      context = default
      default = None
Yoshinori Okuji's avatar
Yoshinori Okuji committed
312 313
    
    tmp_context = self.asContext(context=context, REQUEST=REQUEST, **kw)
314
    result = self._getTotalPrice(default=default, context=tmp_context, fast=fast, **kw)
315
    method = self._getTypeBasedMethod('convertTotalPrice')
316 317 318
    if method is None:
      return result
    return method(result)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
319

320 321
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getTotalQuantity')
322
  def getTotalQuantity(self, default=0.0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
323 324 325
    """
      Returns the quantity if no cell or the total quantity if cells
    """
326
    return self.getQuantity(default=default)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
327

328
  # Industrial price API
329 330
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getIndustrialPrice')
331 332 333 334 335 336 337 338 339
  def getIndustrialPrice(self):
    """
      Calculates industrial price in context of this movement
    """
    resource = self.getResourceValue()
    if resource is not None:
      return resource.getIndustrialPrice(context=self)
    return None

340
  # Asset price calculation
341 342
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceInventoriatedTotalAssetPrice')
343
  def getSourceInventoriatedTotalAssetPrice(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
344
    """
345 346
      Returns a price which can be used to calculate stock value (asset)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
347 348
      Asset price is used for calculation of inventory asset value
      and for accounting
349 350 351 352 353 354 355 356 357

      If the asset price is specified (as in accounting for multi-currency),
      then it is returned. If no asset price is specified, then we use
      the price as defined on the line, but only for incoming quantities
      (purchase price, industrial price, etc.).

      For outgoing quantities, it is the responsability of database
      to calculate asset prices based on calculation rules (FIFO,
      FILO, AVERAGE, etc.).
Jean-Paul Smets's avatar
Jean-Paul Smets committed
358
    """
359 360 361 362
    # This is what we use for accounting
    result = self.getSourceTotalAssetPrice()
    if result is not None:
      return result
363
    quantity = self.getQuantity()
364 365 366
    if quantity :
      source_asset_price = self.getSourceAssetPrice()
      if source_asset_price :
367
        return source_asset_price * - quantity
368
    return None
369 370 371 372 373 374 375 376 377
  
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceInventoriatedTotalAssetDebit')
  def getSourceInventoriatedTotalAssetDebit(self) :
    """
      Returns the debit part of inventoriated source total asset price.
    """
    result = self.getSourceInventoriatedTotalAssetPrice()
    if result is not None :
378 379 380
      if result > 0 and not self.isCancellationAmount():
        return result
      if result < 0 and self.isCancellationAmount():
381
        return result
382
    return 0.0
383 384 385 386 387 388 389 390 391

  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceInventoriatedTotalAssetCredit')
  def getSourceInventoriatedTotalAssetCredit(self) :
    """
      Returns the credit part of inventoriated source total asset price.
    """
    result = self.getSourceInventoriatedTotalAssetPrice()
    if result is not None :
392 393 394
      if result < 0 and not self.isCancellationAmount():
        return -result
      if result > 0 and self.isCancellationAmount():
395
        return -result
396
    return 0.0
397

398 399
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationInventoriatedTotalAssetPrice')
400
  def getDestinationInventoriatedTotalAssetPrice(self):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
401
    """
402 403
      Returns a price which can be used to calculate stock value (asset)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
404 405 406
      Asset price is used for calculation of inventory asset value
      and for accounting
    """
407 408 409 410
    # This is what we use for accounting
    result = self.getDestinationTotalAssetPrice()
    if result is not None:
      return result
411
    quantity = self.getQuantity()
412 413 414 415
    if quantity :
      destination_asset_price = self.getDestinationAssetPrice()
      if destination_asset_price :
        return destination_asset_price * quantity
416
    return None
Jean-Paul Smets's avatar
Jean-Paul Smets committed
417

418 419 420 421 422 423 424 425
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationInventoriatedTotalAssetDebit')
  def getDestinationInventoriatedTotalAssetDebit(self) :
    """
      Returns the debit part of inventoriated destination total asset price.
    """
    result = self.getDestinationInventoriatedTotalAssetPrice()
    if result is not None :
426 427 428
      if result > 0 and not self.isCancellationAmount():
        return result
      if result < 0 and self.isCancellationAmount():
429
        return result
430
    return 0.0
431 432 433 434 435 436 437 438 439

  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationInventoriatedTotalAssetCredit')
  def getDestinationInventoriatedTotalAssetCredit(self) :
    """
      Returns the credit part of inventoriated destination total asset price.
    """
    result = self.getDestinationInventoriatedTotalAssetPrice()
    if result is not None :
440 441 442
      if result < 0 and not self.isCancellationAmount():
        return -result
      if result > 0 and self.isCancellationAmount():
443
        return -result
444
    return 0.0
445

446 447
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceAssetPrice')
448 449 450 451
  def getSourceAssetPrice(self):
    """
      Returns the price converted to the currency of the source section

452
      This will be implemeted by calling currency conversion on currency resources
453
    """
454
    return self.getPrice() # XXX Not implemented yet TODO
455

456 457
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationAssetPrice')
458 459 460 461
  def getDestinationAssetPrice(self):
    """
      Returns the price converted to the currency of the destination section
    """
462
    return self.getPrice() # XXX Not implemented yet TODO
463

Jean-Paul Smets's avatar
Jean-Paul Smets committed
464
  # Causality computation
465 466
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isConvergent')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
467 468 469 470
  def isConvergent(self):
    """
      Returns 0 if the target is not met
    """
471
    return int(not self.isDivergent())
Jean-Paul Smets's avatar
Jean-Paul Smets committed
472

473 474
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isDivergent')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
475 476
  def isDivergent(self):
    """
477
      XXX documentation out of sync with actual use
Jean-Paul Smets's avatar
Jean-Paul Smets committed
478 479 480 481 482 483
      Returns 1 if the target is not met according to the current information
      After and edit, the isOutOfTarget will be checked. If it is 1,
      a message is emitted

      emit targetUnreachable !
    """
Sebastien Robin's avatar
Sebastien Robin committed
484 485 486
    for simulation_movement in self.getDeliveryRelatedValueList():
      if simulation_movement.isDivergent():
        return 1
487
    return 0
Jean-Paul Smets's avatar
Jean-Paul Smets committed
488

489 490 491 492 493 494 495 496 497 498
  def getDivergenceList(self):
    """
    Return a list of messages that contains the divergences 
    """
    divergence_list = [] 
    for simulation_movement in self.getDeliveryRelatedValueList():
      divergence_list.extend(simulation_movement.getDivergenceList())

    return divergence_list

499 500 501 502
  security.declareProtected(Permissions.AccessContentsInformation,
                            'isFrozen')
  def isFrozen(self):
    """
503
    Returns the frozen status of this movement.
504
    a movement in stopped, delivered or cancelled states is automatically frozen.
505 506
    If frozen is locally set to '0', we must check for a parent set to '1', in
    which case, we want the children to be frozen as well.
507 508

    BPM evaluation allows to set frozen state list per Business Path.
509
    """
510 511 512 513 514 515 516 517 518 519
    business_path = self.getCausalityValue(portal_type='Business Path')
    if business_path is None:
      # XXX Hardcoded
      # Maybe, we should use getPortalCurrentInventoryStateList
      # and another portal method for cancelled (and deleted)
      #     LOG("Movement, isFrozen", DEBUG, "Hardcoded state list")
      if self.getSimulationState() in ('stopped', 'delivered', 'cancelled'):
        return 1
    else:
      # conditional BPM enabled frozen state check
520 521
      LOG("Movement.isFrozen", WARNING, "%s is using BPM experimental "
          "evaluation" % self.getPath())
522 523 524 525 526
      # BPM dynamic configuration
      if self.getSimulationState() in business_path.getFrozenStateList():
        return True

    # manually frozen
527 528
    if self._baseIsFrozen() == 0:
      self._baseSetFrozen(None)
529
    return self._baseGetFrozen() or False
530

531 532
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanation')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
533
  def getExplanation(self):
534
    """
535
      Returns the relative_url of the explanation of this movement.
536
    """
537 538 539
    explanation = self.getExplanationValue()
    if explanation is not None:
      return explanation.getRelativeUrl()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
540

541 542
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationUid')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
543
  def getExplanationUid(self):
544
    """
545
      Returns the uid of the explanation of this movement.
546
    """
547 548 549
    explanation = self.getExplanationValue()
    if explanation is not None:
      return explanation.getUid()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
550

551 552
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationValue')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
553
  def getExplanationValue(self):
554
    """
555
      Returns the object explanation of this movement.
556
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557
    return self.getDeliveryValue()
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
 
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationTitle')
  def getExplanationTitle(self, default=''):
    """
      Returns the title of the explanation of this movement.
    """
    explanation_value = self.getExplanationValue()
    if explanation_value is not None:
      return explanation_value.getTitle()
    return default

  security.declareProtected( Permissions.AccessContentsInformation,
                             'getExplanationReference')
  def getExplanationReference(self, default=''):
    """
      Returns the reference of the explanation of this movement.
    """
    explanation_value = self.getExplanationValue()
    if explanation_value is not None:
      return explanation_value.getReference()
    return default

581
  security.declareProtected( Permissions.AccessContentsInformation,
582
                             'getRootCausalityValueList')
583 584 585 586 587 588 589 590
  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
    """
    return self.getExplanationValue().getRootCausalityValueList()
    
591 592

  # Simulation
593 594
  security.declareProtected( Permissions.AccessContentsInformation,
                             'isSimulated')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
595
  def isSimulated(self):
596 597
    return (len(self.getDeliveryRelatedValueList()) > 0) or\
           (len(self.getOrderRelatedValueList()) > 0)
598

599
  # New Causality API
600 601
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderQuantity')
602 603 604 605 606
  def getOrderQuantity(self):
    """
      Returns the quantity of related order(s)
    """
    return self.getQuantity()
607

608 609
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryQuantity')
610 611 612 613
  def getDeliveryQuantity(self):
    """
      Returns the quantity of related delivery(s)
    """
614 615
    return self.getQuantity()

616 617
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationQuantity')
618 619 620 621
  def getSimulationQuantity(self):
    """
      Returns the sum of quantities in related simulation movements
    """
622 623
    return self.getQuantity()

624 625
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStartDateList')
626 627
  def getOrderStartDateList(self):
    """
628
      Returns the list of start date of related order(s)
629 630
    """
    return [self.getStartDate()]
631

632 633
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStartDateList')
634 635
  def getDeliveryStartDateList(self):
    """
636
      Returns the list of start date of related delivery(s)
637 638
    """
    return [self.getStartDate()]
639

640 641
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationStartDateList')
642 643
  def getSimulationStartDateList(self):
    """
644
      Returns the list of start date related simulation movements
645 646
    """
    return [self.getStartDate()]
647

648 649
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderStopDateList')
650 651
  def getOrderStopDateList(self):
    """
652
      Returns the list of stop date of related order(s)
653 654
    """
    return [self.getStopDate()]
655

656 657
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryStopDateList')
658 659
  def getDeliveryStopDateList(self):
    """
660
      Returns the list of stop date of related delivery(s)
661 662
    """
    return [self.getStopDate()]
663

664 665
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationStopDateList')
666 667
  def getSimulationStopDateList(self):
    """
668
      Returns the list of stop date related simulation movements
669 670
    """
    return [self.getStopDate()]
671

672 673
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderSourceList')
674 675 676 677
  def getOrderSourceList(self):
    """
      Returns the source of related orders
    """
678 679
    return self.getSourceList()

680 681
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliverySourceList')
682 683 684 685
  def getDeliverySourceList(self):
    """
      Returns the source of related deliveries
    """
686 687
    return self.getSourceList()

688 689
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationSourceList')
690 691 692 693
  def getSimulationSourceList(self):
    """
      Returns the source of related simulation movements
    """
694 695
    return self.getSourceList()

696 697
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderDestinationList')
698 699 700 701
  def getOrderDestinationList(self):
    """
      Returns the destination of related orders
    """
702 703
    return self.getDestinationList()

704 705
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryDestinationList')
706 707 708 709
  def getDeliveryDestinationList(self):
    """
      Returns the destination of related deliveries
    """
710 711
    return self.getDestinationList()

712 713
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationDestinationList')
714 715 716 717
  def getSimulationDestinationList(self):
    """
      Returns the destination of related simulation movements
    """
718 719
    return self.getDestinationList()

720 721
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderSourceSectionList')
722 723 724 725
  def getOrderSourceSectionList(self):
    """
      Returns the source_section of related orders
    """
726 727
    return self.getSourceSectionList()

728 729
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliverySourceSectionList')
730 731 732 733
  def getDeliverySourceSectionList(self):
    """
      Returns the source_section of related deliveries
    """
734 735
    return self.getSourceSectionList()

736 737
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationSourceSectionList')
738 739 740 741
  def getSimulationSourceSectionList(self):
    """
      Returns the source_section of related simulation movements
    """
742 743
    return self.getSourceSectionList()

744 745
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getOrderDestinationSectionList')
746 747 748 749
  def getOrderDestinationSectionList(self):
    """
      Returns the destination_section of related orders
    """
750 751
    return self.getDestinationSectionList()

752 753
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDeliveryDestinationSectionList')
754 755 756 757
  def getDeliveryDestinationSectionList(self):
    """
      Returns the destination_section of related deliveries
    """
758 759
    return self.getDestinationSectionList()

760 761
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSimulationDestinationSectionList')
762 763 764 765
  def getSimulationDestinationSectionList(self):
    """
      Returns the destination_section of related simulation movements
    """
766 767
    return self.getDestinationSectionList()

768
  # Debit and credit methods
769 770
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceDebit')
771 772 773 774 775 776 777
  def getSourceDebit(self):
    """
      Return the quantity
    """
    quantity = self.getQuantity()
    try:
      quantity = float(quantity)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
778
    except TypeError:
779
      quantity = 0.0
780 781 782
    if (quantity < 0 and not self.isCancellationAmount()):
      return - quantity
    elif quantity > 0 and self.isCancellationAmount():
783
      return - quantity
784
    return 0.0
785

786 787
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceCredit')
788 789 790 791 792 793 794
  def getSourceCredit(self):
    """
      Return the quantity
    """
    quantity = self.getQuantity()
    try:
      quantity = float(quantity)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
795
    except TypeError:
796
      quantity = 0.0
797 798
    if quantity < 0 and not self.isCancellationAmount() \
      or quantity > 0 and self.isCancellationAmount():
799
      return 0.0
800
    return quantity
801

802 803
  security.declareProtected( Permissions.AccessContentsInformation,
                    'getDestinationDebit', 'getDestinationCredit')
804 805 806 807 808 809 810 811 812 813 814 815
  getDestinationDebit = getSourceCredit
  getDestinationCredit = getSourceDebit

  security.declareProtected(Permissions.ModifyPortalContent, 'setSourceDebit')
  def setSourceDebit(self, source_debit):
    """
      Set the quantity
    """
    if source_debit in (None, ''):
      return 0.0
    try:
      source_debit = float(source_debit)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
816
    except TypeError:
817
      source_debit = 0.0
818
    self.setCancellationAmount(source_debit < 0)
819 820 821 822 823 824 825 826 827 828 829
    self.setQuantity(- source_debit)

  security.declareProtected(Permissions.ModifyPortalContent, 'setSourceCredit')
  def setSourceCredit(self, source_credit):
    """
      Set the quantity
    """
    if source_credit in (None, ''):
      return 0.0
    try:
      source_credit = float(source_credit)
Yoshinori Okuji's avatar
Yoshinori Okuji committed
830
    except TypeError:
831
      source_credit = 0.0
832
    self.setCancellationAmount(source_credit < 0)
833 834
    self.setQuantity(source_credit)

835 836 837 838
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDestinationDebit', 'setDestinationCredit' )
  setDestinationDebit = setSourceCredit
  setDestinationCredit = setSourceDebit
839

840
  security.declarePrivate('_edit')
841
  def _edit(self, edit_order=(), **kw):
842
    """Overloaded _edit to support setting debit and credit at the same time,
843 844
    which is required for the GUI.
    Also sets the variation category list at the end, because 
845
    _setVariationCategoryList needs the resource to be set.
846 847 848
    """
    quantity = 0
    if kw.has_key('source_debit') and kw.has_key('source_credit'):
849 850 851
      source_credit = kw.pop('source_credit') or 0
      source_debit = kw.pop('source_debit') or 0
      quantity += (source_credit - source_debit)
852
      kw['quantity'] = quantity
853
      kw['cancellation_amount'] = (source_credit < 0 or source_debit < 0)
854
    if kw.has_key('destination_debit') and kw.has_key('destination_credit'):
855 856 857
      destination_credit = kw.pop('destination_credit') or 0
      destination_debit = kw.pop('destination_debit') or 0
      quantity += (destination_debit - destination_credit)
858
      kw['quantity'] = quantity
859
      kw['cancellation_amount'] = (destination_credit < 0 or destination_debit < 0)
860
    if not edit_order:
861
      edit_order = ('variation_category_list', )
862
    return XMLObject._edit(self, edit_order=edit_order, **kw)
863

864
  # Debit and credit methods for asset
865 866
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceAssetDebit' )
867 868 869 870 871
  def getSourceAssetDebit(self):
    """
      Return the debit part of the source total asset price.

      This is the same as getSourceDebit where quantity is replaced
872 873
      by source_total_asset_price.
      This method returns 0 if the total asset price is not set.
874 875 876 877 878 879
    """
    quantity = self.getSourceTotalAssetPrice()
    try:
      quantity = float(quantity)
    except TypeError:
      quantity = 0.0
880 881
    if quantity < 0 and not self.isCancellationAmount() \
      or quantity > 0 and self.isCancellationAmount():
882
      return 0.0
883
    return quantity
884

885 886
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getSourceAssetCredit' )
887 888
  def getSourceAssetCredit(self):
    """
889 890 891
      Return the credit part of the source total asset price.

      This is the same as getSourceCredit where quantity is replaced
892 893
      by source_total_asset_price.
      This method returns 0 if the total asset price is not set.
894 895 896 897 898 899
    """
    quantity = self.getSourceTotalAssetPrice()
    try:
      quantity = float(quantity)
    except TypeError:
      quantity = 0.0
900
    if (quantity < 0 and not self.isCancellationAmount()):
901
      return - quantity
902 903 904
    elif quantity > 0 and self.isCancellationAmount():
      return - quantity
    return 0.0
905 906 907 908 909 910
  
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationAssetDebit' )
  def getDestinationAssetDebit(self):
    """
      Return the debit part of the destination total asset price.
911

912
      This is the same as getDestinationDebit where quantity is replaced
913 914
      by destination_total_asset_price.
      This method returns 0 if the total asset price is not set.
915 916 917 918 919 920
    """
    quantity = self.getDestinationTotalAssetPrice()
    try:
      quantity = float(quantity)
    except TypeError:
      quantity = 0.0
921 922
    if quantity < 0 and not self.isCancellationAmount() \
      or quantity > 0 and self.isCancellationAmount():
923
      return 0.0
924
    return quantity
925

926 927 928 929 930 931 932
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getDestinationAssetCredit' )
  def getDestinationAssetCredit(self):
    """
      Return the credit part of the destination total asset price.

      This is the same as getDestinationCredit where quantity is replaced
933 934
      by destination_total_asset_price.
      This method returns 0 if the total asset price is not set.
935 936 937 938 939 940
    """
    quantity = self.getDestinationTotalAssetPrice()
    try:
      quantity = float(quantity)
    except TypeError:
      quantity = 0.0
941 942 943 944 945
    if (quantity < 0 and not self.isCancellationAmount()):
      return - quantity
    elif quantity > 0 and self.isCancellationAmount():
      return - quantity
    return 0.0
946 947 948
  
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setSourceAssetDebit' )
949 950
  def setSourceAssetDebit(self, source_debit):
    """
951
      Set the source total asset price
952 953
    """
    if source_debit in (None, ''):
954
      self.setSourceTotalAssetPrice(None)
955
      return
956 957 958 959
    try:
      source_debit = float(source_debit)
    except TypeError:
      source_debit = 0.0
960
    self.setCancellationAmount(source_debit < 0)
961
    self.setSourceTotalAssetPrice(source_debit)
962

963 964 965 966
  security.declareProtected( Permissions.ModifyPortalContent,
                             'setSourceAssetCredit' )
  def setSourceAssetCredit(self, source_credit):
    """
967
      Set the source total asset price
968 969
    """
    if source_credit in (None, ''):
970
      self.setSourceTotalAssetPrice(None)
971
      return
972 973 974 975
    try:
      source_credit = float(source_credit)
    except TypeError:
      source_credit = 0.0
976
    self.setCancellationAmount(source_credit < 0)
977
    self.setSourceTotalAssetPrice( - source_credit)
978 979 980 981 982

  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDestinationAssetDebit' )
  def setDestinationAssetDebit(self, destination_debit):
    """
983
      Set the destination total asset price
984 985
    """
    if destination_debit in (None, ''):
986
      self.setDestinationTotalAssetPrice(None)
987
      return
988 989 990 991
    try:
      destination_debit = float(destination_debit)
    except TypeError:
      destination_debit = 0.0
992
    self.setCancellationAmount(destination_debit < 0)
993 994 995 996 997 998
    self.setDestinationTotalAssetPrice(destination_debit)

  security.declareProtected( Permissions.ModifyPortalContent,
                             'setDestinationAssetCredit' )
  def setDestinationAssetCredit(self, destination_credit):
    """
999
      Set the destination total asset price
1000 1001
    """
    if destination_credit in (None, ''):
1002
      self.setDestinationTotalAssetPrice(None)
1003
      return
1004 1005 1006 1007
    try:
      destination_credit = float(destination_credit)
    except TypeError:
      destination_credit = 0.0
1008
    self.setCancellationAmount(destination_credit < 0)
1009
    self.setDestinationTotalAssetPrice( - destination_credit)
1010

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1011
  # Item Access (tracking)
1012 1013
  security.declareProtected(Permissions.AccessContentsInformation,
      'getTrackedItemUidList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1014
  def getTrackedItemUidList(self):
1015
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1016
      Return a list of uid for related items
1017
    """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1018 1019 1020
    ### XXX We should filter by portal type here
    return self.getAggregateUidList()

1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
  # Helper methods to display total quantities as produced / consumed
  security.declareProtected(Permissions.AccessContentsInformation,
      'getProductionTotalQuantity')
  def getProductionTotalQuantity(self):
    """
      Return the produced quantity
    """
    quantity = self.getTotalQuantity()
    return self.getProductionQuantity(quantity=quantity)

  security.declareProtected(Permissions.AccessContentsInformation,
      'getConsumptionTotalQuantity')
  def getConsumptionTotalQuantity(self):
    """
      Return the produced quantity
    """
    quantity = self.getTotalQuantity()
    return self.getConsumptionQuantity(quantity=quantity)

1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
  security.declareProtected(Permissions.AccessContentsInformation,
      'getSubVariationText')
  def getSubVariationText(self,**kw):
    """
    Provide a string representation of XXX
    """
    base_category_list = self.getPortalSubVariationBaseCategoryList()
    portal_type_list = self.getPortalSubVariationTypeList()
    return_list = []
    for base_category in base_category_list:
      variation_list = self.getAcquiredCategoryMembershipList(base_category,
          portal_type=portal_type_list,base=1)
      return_list.extend(variation_list)
    return "\n".join(return_list)

1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
  security.declareProtected( Permissions.AccessContentsInformation,
                             'getParentExplanationValue')
  def getParentExplanationValue(self):
    """
      This method should be removed as soon as movement groups
      will be rewritten. It is a temp hack
    """
    return self.getParentValue().getExplanationValue()


Jean-Paul Smets's avatar
Jean-Paul Smets committed
1065 1066 1067 1068 1069
  # SKU vs. CU
#   security.declareProtected(Permissions.AccessContentsInformation, 'getSourceStandardInventoriatedQuantity')
#   def getSourceStandardInventoriatedQuantity(self):
#     """
#       The inventoriated quantity converted in a default unit
1070
#
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1071 1072
#       For assortments, returns the inventoriated quantity in terms of number of items
#       in the assortemnt.
1073
#
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1074 1075
#       For accounting, returns the quantity converted in a default unit
#     """
1076 1077
#     return self.getStandardInventoriatedQuantity()

Jean-Paul Smets's avatar
Jean-Paul Smets committed
1078 1079 1080 1081
#   security.declareProtected(Permissions.AccessContentsInformation, 'getDestinationStandardInventoriatedQuantity')
#   def getDestinationStandardInventoriatedQuantity(self):
#     """
#       The inventoriated quantity converted in a default unit
1082
#
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1083 1084
#       For assortments, returns the inventoriated quantity in terms of number of items
#       in the assortemnt.
1085
#
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1086 1087
#       For accounting, returns the quantity converted in a default unit
#     """
1088
#     return self.getStandardInventoriatedQuantity()
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

  security.declareProtected( Permissions.AccessContentsInformation,
                             'asMovementList')
  def asMovementList(self):
    """
    Placeholder method called when indexing a movement.

    It can be overloaded to generate multiple movements 
    from a single one.
    It is used for cataloging a movement multiple time in 
    the movement/stock tables.

    Ex: a movement have multiple destinations.
    asMovementList returns a list a movement context with different 
    single destination.
    """
    return (self, )
1106 1107 1108 1109 1110 1111

  # Experimental Arrow Interface (will be improved in the future)
  security.declareProtected(Permissions.AccessContentsInformation, 'getSourceArrowList')
  def getSourceArrowList(self, context=None):
    # Naive implementation - XXX
    return self._getCategoryMembershipList(self, ('source', 'source_section', 'source_project', 
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1112
                                                  'source_trade', 'source_function', ))
1113 1114 1115 1116 1117 1118

  security.declareProtected(Permissions.AccessContentsInformation, 'getDestinationArrowList')
  def getDestinationArrowList(self, context=None):
    # Naive implementation - XXX
    return self._getCategoryMembershipList(self, ('destination', 'destination_section',
                                                  'destination_project', 
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1119
                                                  'destination_trade', 'destination_function', ))
1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136

  security.declareProtected(Permissions.ModifyPortalContent, 'setSourceArrowList')
  def setSourceArrowList(self, path):
    # Naive implementation - XXX
    self.setCategoryMembership(('source', 'source_section', 'source_project', 
                                                  'source_trade', 'source_function', ),
                                path)

  security.declareProtected(Permissions.ModifyPortalContent, 'setDestinationArrowList')
  def setDestinationArrowList(self, path):
    # Naive implementation - XXX
    self.setCategoryMembership(('destination', 'destination_section',
                                                  'destination_project', 
                                                  'destination_trade', 'destination_function', ),
                                path)