1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
##############################################################################
#
# 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()))
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
)
def _getGroupByNodeMovementList(self):
"""Returns movements that implies only grouping by node."""
movement_list = []
for movement in self.getMovementList():
if not getattr(movement, 'isAccountable', 1):
continue
if not (movement.getSourceSection() or
movement.getDestinationPayment()):
movement_list.append(movement)
return movement_list
def _getGroupByPaymentMovementList(self):
"""Returns movements that implies grouping by node and payment"""
movement_list = []
for movement in self.getMovementList():
if not getattr(movement, 'isAccountable', 1):
continue
if movement.getDestinationPayment():
movement_list.append(movement)
return movement_list
def _getGroupByMirrorSectionMovementList(self):
"""Returns movements that implies only grouping by node and mirror section"""
movement_list = []
for movement in self.getMovementList():
if not getattr(movement, 'isAccountable', 1):
continue
if movement.getSourceSection():
movement_list.append(movement)
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
default_inventory_params = dict(
at_date=self.getStartDate(),
section_uid=self.getDestinationSectionUid(),
simulation_state=('delivered', ))
# node
for movement in self._getGroupByNodeMovementList():
node_uid = movement.getDestinationUid()
section_uid = movement.getDestinationSectionUid()
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):
stock_list.append(
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()
section_uid = movement.getDestinationSectionUid()
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):
stock_list.append(
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()
payment_uid = movement.getDestinationPaymentUid()
section_uid = movement.getDestinationSectionUid()
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,
group_by_node=1,
group_by_payment=1,
group_by_resource=1,
**default_inventory_params):
stock_list.append(
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()
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(),
quantity=movement.getQuantity(),
total_price=movement\
.getDestinationInventoriatedTotalAssetPrice(), ))
# mirror section
for movement in self._getGroupByMirrorSectionMovementList():
node_uid = movement.getDestinationUid()
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(),
quantity=movement.getQuantity(),
total_price=movement\
.getDestinationInventoriatedTotalAssetPrice(), ))
# payment
for movement in self._getGroupByPaymentMovementList():
node_uid = movement.getDestinationUid()
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(),
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 ...)
"""
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',
'total_price')]:
if diff[prop] != new_stock.get(prop):
break
else:
matching_diff = diff
# matching_diff are negated later
if matching_diff:
matching_diff['quantity'] -= new_stock['quantity']
# 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)
# 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
if s['quantity'] and s['total_price']]
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
def factory(*args, **kw):
doc = newTempBalanceTransactionLine(self, self.getId(),
uid=self.getUid())
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)
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
object_list = [self]
self.portal_catalog.catalogObjectList(object_list)
# Catalog differences calculated from lines
self.portal_catalog.catalogObjectList(stock_object_list,
method_id_list=('z_catalog_stock_list',),
disable_cache=1, check_uid=0)