BalanceTransaction.py 19.1 KB
Newer Older
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
##############################################################################
#
# Copyright (c) 2007 Nexedi SA and Contributors. All Rights Reserved.
#                    Jerome Perrin <jerome@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 UserDict import UserDict

from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5.Document.Inventory import Inventory
from Products.ERP5.Document.AccountingTransaction import AccountingTransaction


class InventoryKey(UserDict):
  """Class to use as a key when defining inventory dicts.
  """
  def __init__(self, **kw):
    self.data = {}
    self.data.update(kw)

  def clear(self):
    raise TypeError, 'InventoryKey are immutable'
  
  def pop(self, keys, *args):
    raise TypeError, 'InventoryKey are immutable'
  
  def update(self, dict=None, **kwargs):
    raise TypeError, 'InventoryKey are immutable'
  
  def __delitem__(self, key):
    raise TypeError, 'InventoryKey are immutable'
  
  def __setitem__(self, key, item):
    raise TypeError, 'InventoryKey are immutable'
  
  def setdefault(self, key, failobj=None):
    if key in self.data:
      return self.data[key]
    raise TypeError, 'InventoryKey are immutable'

  def __hash__(self):
    return hash(tuple(self.items()))

67 68 69 70 71 72 73 74 75 76 77
  def __cmp__(self, other):
    # this is basically here so that we can see if two inventory keys are
    # equals.
    if tuple(self.keys()) != tuple(other.keys()):
      return -1
    for k, v in self.items():
      if v != other[k]:
        return -1
    return 0


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

class BalanceTransaction(AccountingTransaction, Inventory):
  """Balance Transaction 
  """

  # CMF Type Definition
  meta_type = 'ERP5 Balance Transaction'
  portal_type = 'Balance Transaction'
  add_permission = Permissions.AddPortalContent
  isPortalContent = 1
  isRADContent = 1
  isDelivery = 1
    
  #__implements__ = ( Interface.Inventory, )

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

  # Default Properties
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.XMLObject
                    , PropertySheet.CategoryCore
                    , PropertySheet.DublinCore
                    , PropertySheet.Task
                    , PropertySheet.Arrow
                    , PropertySheet.Movement
                    , PropertySheet.Delivery
                    , PropertySheet.Amount
                    , PropertySheet.Reference
                    , PropertySheet.PaymentCondition
109
                    , PropertySheet.AccountingTransaction
110
                    )
111
  
112 113 114 115

  def _getGroupByNodeMovementList(self):
    """Returns movements that implies only grouping by node."""
    movement_list = []
116 117
    for movement in self.getMovementList(
              portal_type=self.getPortalAccountingMovementTypeList()):
Jérome Perrin's avatar
Jérome Perrin committed
118 119
      if getattr(movement, 'isAccountable', 1):
        if not (movement.getSourceSection() or
120
                movement.getDestinationPayment()):
Jérome Perrin's avatar
Jérome Perrin committed
121
          movement_list.append(movement)
122 123 124 125 126
    return movement_list

  def _getGroupByPaymentMovementList(self):
    """Returns movements that implies grouping by node and payment"""
    movement_list = []
127 128
    for movement in self.getMovementList(
              portal_type=self.getPortalAccountingMovementTypeList()):
Jérome Perrin's avatar
Jérome Perrin committed
129 130 131
      if getattr(movement, 'isAccountable', 1):
        if movement.getDestinationPayment():
          movement_list.append(movement)
132 133 134 135 136
    return movement_list

  def _getGroupByMirrorSectionMovementList(self):
    """Returns movements that implies only grouping by node and mirror section"""
    movement_list = []
137 138
    for movement in self.getMovementList(
              portal_type=self.getPortalAccountingMovementTypeList()):
Jérome Perrin's avatar
Jérome Perrin committed
139 140 141
      if getattr(movement, 'isAccountable', 1):
        if movement.getSourceSection():
          movement_list.append(movement)
142 143 144 145 146 147 148 149 150 151
    return movement_list


  def _getCurrentStockDict(self):
    """Looks the current stock by calling getInventoryList, and building a
    dictionnary of InventoryKey
    """
    current_stock = dict()
    getInventoryList = self.getPortalObject()\
                            .portal_simulation.getInventoryList
152
    section_uid = self.getDestinationSectionUid()
153 154 155
    precision = 2
    if section_uid is not None:
      precision =  self.getDestinationSectionValue()\
Jérome Perrin's avatar
Jérome Perrin committed
156
                        .getPriceCurrencyValue().getQuantityPrecision()
157
    default_inventory_params = dict(
158
                        to_date=self.getStartDate().earliestTime(),
159
                        section_uid=section_uid,
Jérome Perrin's avatar
Jérome Perrin committed
160
                        precision=precision,
161
                        portal_type=self.getPortalAccountingMovementTypeList(),
162 163 164 165 166
                        simulation_state=('delivered', ))

    # node
    for movement in self._getGroupByNodeMovementList():
      node_uid = movement.getDestinationUid()
167 168
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
169
      resource_uid = movement.getResourceUid()
170 171 172 173 174 175

      stock_list = current_stock.setdefault(
                         InventoryKey(node_uid=node_uid,
                                      section_uid=section_uid), [])
      for inventory in getInventoryList(
                              node_uid=node_uid,
176
                              resource_uid=resource_uid,
177 178 179
                              group_by_node=1,
                              group_by_resource=1,
                              **default_inventory_params):
180 181
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
182 183
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
184
                   resource_uid=resource_uid,
185 186 187 188 189 190
                   quantity=inventory.total_quantity,
                   total_price=inventory.total_price, ))
    
    # mirror section
    for movement in self._getGroupByMirrorSectionMovementList():
      node_uid = movement.getDestinationUid()
191 192
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
193
      mirror_section_uid = movement.getSourceSectionUid()
194
      resource_uid = movement.getResourceUid()
195 196 197 198 199 200 201 202

      stock_list = current_stock.setdefault(
                         InventoryKey(node_uid=node_uid,
                                      mirror_section_uid=mirror_section_uid,
                                      section_uid=section_uid), [])
      for inventory in getInventoryList(
                              node_uid=node_uid,
                              mirror_section_uid=mirror_section_uid,
203
                              resource_uid=resource_uid,
204 205 206 207
                              group_by_node=1,
                              group_by_mirror_section=1,
                              group_by_resource=1,
                              **default_inventory_params):
208 209
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
210 211 212
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   source_section_uid=mirror_section_uid,
213
                   resource_uid=resource_uid,
214 215 216 217 218 219
                   quantity=inventory.total_quantity,
                   total_price=inventory.total_price, ))

    # payment
    for movement in self._getGroupByPaymentMovementList():
      node_uid = movement.getDestinationUid()
220 221
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
222
      payment_uid = movement.getDestinationPaymentUid()
223
      resource_uid = movement.getResourceUid()
224 225 226 227 228 229 230

      stock_list = current_stock.setdefault(
                         InventoryKey(node_uid=node_uid,
                                      section_uid=section_uid,
                                      payment_uid=payment_uid), [])
      for inventory in getInventoryList(
                              node_uid=node_uid,
231
                              payment_uid=payment_uid,
232
                              resource_uid=resource_uid,
233 234 235 236
                              group_by_node=1,
                              group_by_payment=1,
                              group_by_resource=1,
                              **default_inventory_params):
237 238
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
239 240 241
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   destination_payment_uid=payment_uid,
242
                   resource_uid=resource_uid,
243 244 245 246 247 248 249 250 251 252 253 254 255 256
                   quantity=inventory.total_quantity,
                   total_price=inventory.total_price, ))

    return current_stock


  def _getNewStockDict(self):
    """Looks the new stock on lines in this inventory, and building a
    dictionnary of InventoryKey
    """
    new_stock = dict()
    # node
    for movement in self._getGroupByNodeMovementList():
      node_uid = movement.getDestinationUid()
257 258
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
259 260 261 262 263 264 265 266 267
      section_uid = movement.getDestinationSectionUid()

      stock_list = new_stock.setdefault(
                 InventoryKey(node_uid=node_uid,
                              section_uid=section_uid), [])
      stock_list.append(
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   resource_uid=movement.getResourceUid(),
268
                   id=movement.getId(),
269 270
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
271 272 273 274 275 276 277
                   quantity=movement.getQuantity(),
                   total_price=movement\
                    .getDestinationInventoriatedTotalAssetPrice(), ))
    
    # mirror section
    for movement in self._getGroupByMirrorSectionMovementList():
      node_uid = movement.getDestinationUid()
278 279
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
280 281 282 283 284 285 286 287 288 289 290 291
      section_uid = movement.getDestinationSectionUid()
      mirror_section_uid = movement.getSourceSectionUid()

      stock_list = new_stock.setdefault(
                 InventoryKey(node_uid=node_uid,
                              mirror_section_uid=mirror_section_uid,
                              section_uid=section_uid), [])
      stock_list.append(
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   source_section_uid=mirror_section_uid,
                   resource_uid=movement.getResourceUid(),
292
                   id=movement.getId(),
293 294
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
295 296 297 298 299 300 301
                   quantity=movement.getQuantity(),
                   total_price=movement\
                    .getDestinationInventoriatedTotalAssetPrice(), ))
    
    # payment
    for movement in self._getGroupByPaymentMovementList():
      node_uid = movement.getDestinationUid()
302 303
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
304 305 306 307 308 309 310 311 312 313 314 315
      section_uid = movement.getDestinationSectionUid()
      payment_uid = movement.getDestinationPaymentUid()

      stock_list = new_stock.setdefault(
                 InventoryKey(node_uid=node_uid,
                              payment_uid=payment_uid,
                              section_uid=section_uid), [])
      stock_list.append(
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   destination_payment_uid=payment_uid,
                   resource_uid=movement.getResourceUid(),
316
                   id=movement.getId(),
317 318
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
319 320 321 322 323 324 325 326 327 328 329 330
                   quantity=movement.getQuantity(),
                   total_price=movement\
                    .getDestinationInventoriatedTotalAssetPrice(), ))
    
    return new_stock


  def _computeStockDifferenceList(self, current_stock_dict, new_stock_dict):
    """Compute the difference between the result of _getCurrentStockDict and
    _getNewStockDict. Returns a list of dictionnaries with similar keys that
    the ones on inventory brains (node, section, mirror_section ...)
    """
331 332
    precision = self.getResourceValue().getQuantityPrecision()

333 334 335 336 337 338 339 340 341 342 343
    def computeStockDifference(current_stock_list, new_stock_list):
      # helper function to compute difference between two stock lists.
      if not current_stock_list:
        return new_stock_list
      
      stock_diff_list = current_stock_list[::] # deep copy ?

      for new_stock in new_stock_list:
        matching_diff = None
        for diff in stock_diff_list:
          for prop in [k for k in diff.keys() if k not in ('quantity',
344
                          'total_price', 'id', 'uid', 'relative_url')]:
345 346 347 348 349 350 351
            if diff[prop] != new_stock.get(prop):
              break
          else:
            matching_diff = diff
        
        # matching_diff are negated later
        if matching_diff:
352
          matching_diff['quantity'] -= round(new_stock['quantity'], precision)
353 354 355 356 357 358
          # Matching_diff and new_stock must be consistent.
          # both with total price or none.
          if matching_diff['total_price'] and new_stock['total_price']:
            matching_diff['total_price'] -= new_stock['total_price']
        else:
          stock_diff_list.append(new_stock)
359 360
      
      
361 362 363
      # we were doing with reversed calculation, so negate deltas again.
      # Also we remove stocks that have 0 quantity and price.
      return [negateStock(s) for s in stock_diff_list
364 365
              if round(s['quantity'], precision) and
                 round(s['total_price'], precision)]
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

    def negateStock(stock):
      negated_stock = stock.copy()
      negated_stock['quantity'] = -stock['quantity']
      if stock['total_price']:
        negated_stock['total_price'] = -stock['total_price']
      return negated_stock

    delta_list = []
    for current_stock_key, current_stock_value_list in \
                            current_stock_dict.items():
      if current_stock_key in new_stock_dict:
        delta_list.extend(computeStockDifference(
                              current_stock_value_list,
                              new_stock_dict[current_stock_key]))
      else:
        delta_list.extend(
            [negateStock(s) for s in current_stock_value_list])
    
    # now add every thing in new stock which was not in current stock
    for new_stock_key, new_stock_value_list in \
                                new_stock_dict.items():
      if new_stock_key not in current_stock_dict:
        delta_list.extend(new_stock_value_list)

    return delta_list


  def _getTempObjectFactory(self):
    """Returns the factory method that will create temp object.

    This method must return a function that accepts properties keywords
    arguments and returns a temp object edited with those properties.
    """
    from Products.ERP5Type.Document import newTempBalanceTransactionLine
401
    
402
    def factory(*args, **kw):
403
      doc = newTempBalanceTransactionLine(self, kw.pop('id', self.getId()),
404
                                         uid=self.getUid())
405
      relative_url = kw.pop('relative_url', None)
406 407 408 409
      destination_total_asset_price = kw.pop('total_price', None)
      if destination_total_asset_price is not None:
        kw['destination_total_asset_price'] = destination_total_asset_price
      doc._edit(*args, **kw)
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424

      if relative_url:
        
        def URLGetter(url):
          def getRelativeUrl():
            return url
          return getRelativeUrl
        doc.getRelativeUrl = URLGetter(relative_url)
        
        def PathGetter(path):
          def getPath():
            return path
          return getPath
        doc.getPath = PathGetter(relative_url)

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452
      return doc

    return factory


  security.declarePrivate('alternateReindexObject')
  def alternateReindexObject(self, **kw):
    """This method is called when an inventory object is included in a
    group of catalogged objects.
    """
    return self.immediateReindexObject(**kw)


  def immediateReindexObject(self, **kw):
    """Reindexes the object.
    This is different indexing that the default Inventory indexing, because
    we want to take into account that lines in this balance transaction to
    represent the balance of an account (node) with different parameters,
    based on the account_type of those accounts:
      - on standards accounts: it's simply the balance for node, section
       (and maybe resource, like all of thoses)
      - on payable / receivable accounts: for node, section and mirror
        section
      - on bank accounts: for node, section and payment

    Also this uses total_price (and quantity), and ignores variations and
    subvariations as it does not exist in accounting.
    """
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
    sql_catalog_id = kw.pop("sql_catalog_id", None)
    disable_archive = kw.pop("disable_archive", 0)

    if self.getSimulationState() in self.getPortalDraftOrderStateList():
      # this prevent from trying to calculate stock
      # with not all properties defined and thus making
      # request with no condition in mysql
      object_list = [self]
      immediate_reindex_archive = sql_catalog_id is not None
      self.portal_catalog.catalogObjectList(
                    object_list,
                    sql_catalog_id = sql_catalog_id,
                    disable_archive=disable_archive,
                    immediate_reindex_archive=immediate_reindex_archive)      
      return

469 470 471 472 473 474 475 476 477 478 479 480
    current_stock_dict = self._getCurrentStockDict()
    new_stock_dict = self._getNewStockDict()
    diff_list = self._computeStockDifferenceList(
                                    current_stock_dict,
                                    new_stock_dict)
    temp_object_factory = self._getTempObjectFactory()
    stock_object_list = []
    add_obj = stock_object_list.append
    for diff in diff_list:
      add_obj(temp_object_factory(**diff))

    # Catalog this transaction as a standard document
Jérome Perrin's avatar
Jérome Perrin committed
481
    self.portal_catalog.catalogObjectList([self])
482 483 484
    
    # Catalog differences calculated from lines
    self.portal_catalog.catalogObjectList(stock_object_list,
485 486 487
         method_id_list=('z_catalog_stock_list',
                         'z_catalog_object_list',
                         'z_catalog_movement_category_list'),
488
         disable_cache=1, check_uid=0)
Jérome Perrin's avatar
Jérome Perrin committed
489