BalanceTransaction.py 18.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
    precision =  self.getDestinationSectionValue()\
Jérome Perrin's avatar
Jérome Perrin committed
154
                        .getPriceCurrencyValue().getQuantityPrecision()
155
    default_inventory_params = dict(
156
                        to_date=self.getStartDate().earliestTime(),
157
                        section_uid=section_uid,
Jérome Perrin's avatar
Jérome Perrin committed
158
                        precision=precision,
159
                        portal_type=self.getPortalAccountingMovementTypeList(),
160 161 162 163 164
                        simulation_state=('delivered', ))

    # node
    for movement in self._getGroupByNodeMovementList():
      node_uid = movement.getDestinationUid()
165 166
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
167 168 169 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,
                              group_by_node=1,
                              group_by_resource=1,
                              **default_inventory_params):
176 177
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
178 179 180 181 182 183 184 185 186
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   resource_uid=inventory.resource_uid,
                   quantity=inventory.total_quantity,
                   total_price=inventory.total_price, ))
    
    # mirror section
    for movement in self._getGroupByMirrorSectionMovementList():
      node_uid = movement.getDestinationUid()
187 188
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
189 190 191 192 193 194 195 196 197 198 199 200 201
      mirror_section_uid = movement.getSourceSectionUid()

      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,
                              group_by_node=1,
                              group_by_mirror_section=1,
                              group_by_resource=1,
                              **default_inventory_params):
202 203
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
204 205 206 207 208 209 210 211 212 213
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   source_section_uid=mirror_section_uid,
                   resource_uid=inventory.resource_uid,
                   quantity=inventory.total_quantity,
                   total_price=inventory.total_price, ))

    # payment
    for movement in self._getGroupByPaymentMovementList():
      node_uid = movement.getDestinationUid()
214 215
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
216 217 218 219 220 221 222 223
      payment_uid = movement.getDestinationPaymentUid()

      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,
224
                              payment_uid=payment_uid,
225 226 227 228
                              group_by_node=1,
                              group_by_payment=1,
                              group_by_resource=1,
                              **default_inventory_params):
229 230
        if inventory.total_price and inventory.total_quantity:
          stock_list.append(
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
              dict(destination_uid=node_uid,
                   destination_section_uid=section_uid,
                   destination_payment_uid=payment_uid,
                   resource_uid=inventory.resource_uid,
                   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()
249 250
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
251 252 253 254 255 256 257 258 259
      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(),
260
                   id=movement.getId(),
261 262
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
263 264 265 266 267 268 269
                   quantity=movement.getQuantity(),
                   total_price=movement\
                    .getDestinationInventoriatedTotalAssetPrice(), ))
    
    # mirror section
    for movement in self._getGroupByMirrorSectionMovementList():
      node_uid = movement.getDestinationUid()
270 271
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
272 273 274 275 276 277 278 279 280 281 282 283
      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(),
284
                   id=movement.getId(),
285 286
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
287 288 289 290 291 292 293
                   quantity=movement.getQuantity(),
                   total_price=movement\
                    .getDestinationInventoriatedTotalAssetPrice(), ))
    
    # payment
    for movement in self._getGroupByPaymentMovementList():
      node_uid = movement.getDestinationUid()
294 295
      if not node_uid:
        raise ValueError, "No destination uid for %s" % movement
296 297 298 299 300 301 302 303 304 305 306 307
      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(),
308
                   id=movement.getId(),
309 310
                   uid=movement.getUid(),
                   relative_url=movement.getRelativeUrl(),
311 312 313 314 315 316 317 318 319 320 321 322
                   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 ...)
    """
323 324
    precision = self.getResourceValue().getQuantityPrecision()

325 326 327 328 329 330 331 332 333 334 335
    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',
336
                          'total_price', 'id', 'uid', 'relative_url')]:
337 338 339 340 341 342 343
            if diff[prop] != new_stock.get(prop):
              break
          else:
            matching_diff = diff
        
        # matching_diff are negated later
        if matching_diff:
344
          matching_diff['quantity'] -= round(new_stock['quantity'], precision)
345 346 347 348 349 350
          # 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)
351 352
      
      
353 354 355
      # 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
356 357
              if round(s['quantity'], precision) and
                 round(s['total_price'], precision)]
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

    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
393
    
394
    def factory(*args, **kw):
395
      doc = newTempBalanceTransactionLine(self, kw.pop('id', self.getId()),
396
                                         uid=self.getUid())
397
      relative_url = kw.pop('relative_url', None)
398 399 400 401
      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)
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416

      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)

417 418 419 420 421 422 423 424 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 453 454 455 456
      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.
    """
    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
457
    self.portal_catalog.catalogObjectList([self])
458 459 460
    
    # Catalog differences calculated from lines
    self.portal_catalog.catalogObjectList(stock_object_list,
461 462 463
         method_id_list=('z_catalog_stock_list',
                         'z_catalog_object_list',
                         'z_catalog_movement_category_list'),
464
         disable_cache=1, check_uid=0)
Jérome Perrin's avatar
Jérome Perrin committed
465