Commit 7a6edd5d authored by Romain Courteaud's avatar Romain Courteaud

Remove custom getAggregatedAmountList implementation and use the generic mixin

git-svn-id: https://svn.erp5.org/repos/public/erp5/sandbox/amount_generator@34814 20353a03-c40f-0410-a6d1-a30d3c3de9de
parent caadbf43
...@@ -3,9 +3,10 @@ ...@@ -3,9 +3,10 @@
# #
# Copyright (c) 2002 Coramy SAS and Contributors. All Rights Reserved. # Copyright (c) 2002 Coramy SAS and Contributors. All Rights Reserved.
# Thierry_Faucher <Thierry_Faucher@coramy.com> # Thierry_Faucher <Thierry_Faucher@coramy.com>
# Copyright (c) 2004-2009 Nexedi SA and Contributors. All Rights Reserved. # Copyright (c) 2004-2010 Nexedi SA and Contributors. All Rights Reserved.
# Romain Courteaud <romain@nexedi.com> # Romain Courteaud <romain@nexedi.com>
# Łukasz Nowak <luke@nexedi.com> # Łukasz Nowak <luke@nexedi.com>
# Jean-Paul Smets <jp@nexedi.com>
# #
# WARNING: This program as such is intended to be used by professional # WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential # programmers who take the whole responsability of assessing all potential
...@@ -29,25 +30,23 @@ ...@@ -29,25 +30,23 @@
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# #
############################################################################## ##############################################################################
from zLOG import LOG, WARNING
import zope.interface import zope.interface
from warnings import warn from warnings import warn
from AccessControl import ClassSecurityInfo from AccessControl import ClassSecurityInfo
from Products.ERP5Type import Permissions, PropertySheet, interfaces
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5.Variated import Variated
from Products.ERP5.Document.Predicate import Predicate
from Products.CMFCategory.Renderer import Renderer from Products.CMFCategory.Renderer import Renderer
from Products.ERP5.AggregatedAmountList import AggregatedAmountList from Products.ERP5Type import Permissions, PropertySheet, interfaces
from Products.ERP5.Document.MappedValue import MappedValue
from zLOG import LOG, WARNING from Products.ERP5.mixin.amount_generator import AmountGeneratorMixin
from Products.ERP5.mixin.variated import VariatedMixin
from Products.ERP5.mixin.composition import CompositionMixin
from Products.ERP5Type.XMLObject import XMLObject
class Transformation(XMLObject, Predicate, Variated): class Transformation(MappedValue, AmountGeneratorMixin, VariatedMixin):
""" """
Build of material - contains a list of transformed resources Build of material - contains a list of transformed resources
...@@ -79,15 +78,83 @@ class Transformation(XMLObject, Predicate, Variated): ...@@ -79,15 +78,83 @@ class Transformation(XMLObject, Predicate, Variated):
, PropertySheet.TransformedResource , PropertySheet.TransformedResource
, PropertySheet.Path , PropertySheet.Path
, PropertySheet.Transformation , PropertySheet.Transformation
, PropertySheet.Order
, PropertySheet.Task
) )
# Declarative interfaces # Declarative interfaces
zope.interface.implements(interfaces.IVariated, zope.interface.implements(interfaces.IVariated,
interfaces.IVariationRange,
interfaces.IAmountGenerator interfaces.IAmountGenerator
) )
# Predicate Value implementation
# asPredicate takes into account the resource
# XXX-JPS not Impl.
def getCellAggregateKey(self, amount_generator_cell):
"""Define a key in order to aggregate amounts at cell level
Transformed Resource (Transformation)
key must be None because:
- quantity and variation are defined in different cells so that the
user does not need to enter values depending on all axes
- amount_generator_cell.test should filter only 1 variant
current key = (acquired resource, acquired variation)
Assorted Resource (Transformation)
key = (assorted resource, assorted resource variation)
usually resource and quantity provided together
Payroll
key = (payroll resource, payroll resource variation)
Tax
key = (tax resource, tax resource variation)
"""
if len(amount_generator_cell.contentValues()):
key = (amount_generator_cell.getRelativeUrl(),)
else:
key = (amount_generator_cell.getParentValue().getRelativeUrl(),)
return key
# Mapped Value implementation
# Transformation itself provides no properties or categories
def getMappedValuePropertyList(self):
return ()
def getMappedValueBaseCategoryList(self):
return ()
# Amount Generator Mixin
def _getGlobalPropertyDict(self, context, amount_list=None, rounding=False):
"""
No global properties needed
"""
return {
}
def _getAmountPropertyDict(self, amount, amount_list=None, rounding=False):
"""
Produced amount quantity is needed to initialize transformation
"""
# XXX 1 is for compatibility
return {
'produced_quantity' : amount.getQuantity(1),
}
def getBaseApplication(self):
"""
"""
# It is OK to try to acquire
if getattr(self, '_baseGetBaseApplication', None) is not None:
result = self._baseGetBaseApplication()
if result:
return result
return 'produced_quantity'
# IVariationRange and IVariated Implementation
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
'updateVariationCategoryList') 'updateVariationCategoryList')
def updateVariationCategoryList(self): def updateVariationCategoryList(self):
...@@ -162,15 +229,6 @@ class Transformation(XMLObject, Predicate, Variated): ...@@ -162,15 +229,6 @@ class Transformation(XMLObject, Predicate, Variated):
base_category_list, base=1, display_none_category=0) base_category_list, base=1, display_none_category=0)
return result return result
security.declareProtected(Permissions.AccessContentsInformation,
'setVariationBaseCategoryList')
def setVariationBaseCategoryList(self, value):
"""
Define the possible base categories and reindex object
"""
self._setVariationBaseCategoryList(value)
self.reindexObject()
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
'getVariationCategoryItemList') 'getVariationCategoryItemList')
def getVariationCategoryItemList(self, base_category_list=(), base=1, def getVariationCategoryItemList(self, base_category_list=(), base=1,
...@@ -216,89 +274,3 @@ class Transformation(XMLObject, Predicate, Variated): ...@@ -216,89 +274,3 @@ class Transformation(XMLObject, Predicate, Variated):
display_id=display_id,**kw).\ display_id=display_id,**kw).\
render(object_list)) render(object_list))
return variation_category_item_list return variation_category_item_list
security.declareProtected(Permissions.AccessContentsInformation,
'getAggregatedAmountList')
def getAggregatedAmountList(self, context=None, REQUEST=None,
trade_phase_list=None,
# obsolete, use trade_phase_list instead
ind_phase_url_list=None,
rejected_resource_uid_list=None,
**kw):
"""
getAggregatedAmountList returns an AggregatedAmountList which
can be used either to do some calculation (ex. price, BOM)
or to display a detailed view of a transformation.
"""
if context is None:
warn("Calling Transformation.getAggregatedAmountList without context " \
"is wrong. Context should be an Amount defining the resource to " \
"produce", DeprecationWarning)
from Products.ERP5Type.Document import newTempAmount
context = newTempAmount(self, "deprecated_usage")
context.setResourceValue(self.getResourceValue())
context.setQuantity(1.0)
# A list of functions taking a transformation_line as sole argument
# and returning True iif the line should be kept in the result
filter_list = []
# Get only lines related to a precise trade_phase
if trade_phase_list is not None:
def trade_phase_filter(line):
return line.getTradePhase() in trade_phase_list
filter_list.append(trade_phase_filter)
# Get only lines related to a precise industrial_phase
if ind_phase_url_list is not None:
LOG("Transformation", WARNING, "ind_phase_list is obsolete")
def industrial_phase_filter(line):
ind_ph = line.getIndustrialPhaseValue()
if ind_ph is not None:
return ind_ph.getRelativeUrl() in ind_phase_url_list
return False
filter_list.append(industrial_phase_filter)
# Filter lines with resource we do not want to see
if rejected_resource_uid_list is not None:
def rejected_uid_filter(line):
return line.getResourceUid() not in rejected_resource_uid_list
filter_list.append(rejected_uid_filter)
def line_is_included(line):
# XXX > 2.5 : all(f(line) for f in filter_list)
for filterr in filter_list:
if not filterr(line):
return False
return True
# First we need to get the list of transformations which this
# transformation depends on
# At this moment, we only consider 1 dependency
template_transformation_list = self.getSpecialiseValueList()
# Browse all involved transformations and create one line per
# line of transformation
# Currently, we do not consider abstractions, we just add
# whatever we find in all transformations
result = AggregatedAmountList()
for transformation in ([self] + template_transformation_list):
for transformation_line in transformation.objectValues():
# Browse each transformed or assorted resource of the current
# transformation
if line_is_included(transformation_line):
try:
line_result = transformation_line.getAggregatedAmountList(context)
except KeyError:
# KeyError is raised by TransformedResource.getAggregatedAmountList
# in case of misconfiguration of a Cell.
# Just ignore the line
pass
else:
result.extend(line_result)
return result
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
# Copyright (c) 2002, 2004 Nexedi SARL and Contributors. All Rights Reserved. # Copyright (c) 2002, 2004 Nexedi SARL and Contributors. All Rights Reserved.
# Jean-Paul Smets-Solanes <jp@nexedi.com> # Jean-Paul Smets-Solanes <jp@nexedi.com>
# Romain Courteaud <romain@nexedi.com> # Romain Courteaud <romain@nexedi.com>
# Copyright (c) 2010 Nexedi SA and Contributors. All Rights Reserved.
# Jean-Paul Smets-Solanes <jp@nexedi.com>
# #
# WARNING: This program as such is intended to be used by professional # WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential # programmers who take the whole responsability of assessing all potential
...@@ -37,24 +39,22 @@ from Products.ERP5Type.XMLObject import XMLObject ...@@ -37,24 +39,22 @@ from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type.XMLMatrix import XMLMatrix from Products.ERP5Type.XMLMatrix import XMLMatrix
from Products.ERP5.Document.Amount import Amount from Products.ERP5.Document.Amount import Amount
from Products.ERP5.AggregatedAmountList import AggregatedAmountList from Products.ERP5.Document.MappedValue import MappedValue
from Products.ERP5.Document.Predicate import Predicate from Products.ERP5.Document.Predicate import Predicate
class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount): class TransformedResource(MappedValue, XMLMatrix, Amount):
""" """
TransformedResource defines which TransformedResource defines which resource is being transformed
resource is being transformed in order to produce a product define in the parent Transformation
document.
- variation
- quantity TODO:
- transformations used to work perfectly for more than 3 dimensions
Maybe defined by mapped values inside the transformed resource of variations. However, this feature was broken with time and
is no longer usable. It is time to reimplement it. This is
XXX Transformation works only for a miximum of 3 variation base category... completely unrelated to MatrixBox reimplementation unlike
Matrixbox must be rewrite for a clean implementation of n base category what is stated in some comments.
""" """
meta_type = 'ERP5 Transformed Resource' meta_type = 'ERP5 Transformed Resource'
...@@ -74,10 +74,38 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount): ...@@ -74,10 +74,38 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount):
) )
# Declarative interfaces # Declarative interfaces
zope.interface.implements(interfaces.IAmountGenerator,) zope.interface.implements(interfaces.IAmountGenerator,
interfaces.IVariated,
interfaces.IVariationRange,)
### Mapped Value Definition
# Provide default mapped value properties and categories if
# not defined
def getMappedValuePropertyList(self):
result = self._baseGetMappedValuePropertyList()
if result:
return result
return ('quantity',)
def getMappedValueBaseCategoryList(self):
result = self._baseGetMappedValueBaseCategoryList()
if not result:
if not self.hasCellContent(base_id='variation'):
result = self.getVariationRangeBaseCategoryList() # The current resource variation
return list(result) + ['quantity_unit']
def getBaseApplication(self):
"""
"""
# It is OK to try to acquire
if getattr(self, '_baseGetBaseApplication', None) is not None:
result = self._baseGetBaseApplication()
if result:
return result
return 'produced_quantity'
### Variation matrix definition ### Variation matrix definition
# # XXX-JPS Some explanation needed
security.declareProtected(Permissions.AccessContentsInformation, security.declareProtected(Permissions.AccessContentsInformation,
'updateVariationCategoryList') 'updateVariationCategoryList')
def updateVariationCategoryList(self): def updateVariationCategoryList(self):
...@@ -98,16 +126,6 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount): ...@@ -98,16 +126,6 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount):
self._baseSetQVariationBaseCategoryList(value) self._baseSetQVariationBaseCategoryList(value)
self._updateCellRange('quantity') self._updateCellRange('quantity')
security.declareProtected(Permissions.ModifyPortalContent,
'setQVariationBaseCategoryList')
def setQVariationBaseCategoryList(self, value):
"""
Defines the possible base categories which Quantity value (Q)
variate on and reindex the object
"""
self._setQVariationBaseCategoryList(value)
self.reindexObject()
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'_setVVariationBaseCategoryList') '_setVVariationBaseCategoryList')
def _setVVariationBaseCategoryList(self, value): def _setVVariationBaseCategoryList(self, value):
...@@ -116,7 +134,10 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount): ...@@ -116,7 +134,10 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount):
variate on variate on
""" """
self._baseSetVVariationBaseCategoryList(value) self._baseSetVVariationBaseCategoryList(value)
# XXX calling updatecellRange is better
self._updateCellRange('variation') self._updateCellRange('variation')
# XXX-JPS This should be handled by interaction workflow or interactor
# XXX-JPS SO many cases are not handled well...
security.declareProtected(Permissions.ModifyPortalContent, security.declareProtected(Permissions.ModifyPortalContent,
'setVVariationBaseCategoryList') 'setVVariationBaseCategoryList')
...@@ -127,205 +148,3 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount): ...@@ -127,205 +148,3 @@ class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount):
""" """
self._setVVariationBaseCategoryList(value) self._setVVariationBaseCategoryList(value)
self.reindexObject() self.reindexObject()
security.declareProtected(Permissions.AccessContentsInformation,
'getAggregatedAmountList')
def getAggregatedAmountList(self, context, REQUEST=None, **kw):
"""
Get all interesting amount value and return AggregatedAmountList
"""
# Create the result object
aggregated_amount_list = AggregatedAmountList()
test_result = self.test(context)
if test_result:
# The line must match the context
# If no predicate is defined on line, the result of the test
# must be true
# Create temporary object to store amount
parent = self.getParentValue()
# Be careful: this id must be unique, and change when the context is
# changing. Failure to do so exposes to possible erroneous cache hits
# for physical path based caching.
tmp_id = '_'.join((parent.getId(), self.getId(), context.getId()))
tmp_amount = parent.newContent(id=tmp_id,
temp_object=1, portal_type=self.getPortalType())
# Create error string
error_string = ''
# Add resource relation
resource = self.getDefaultResourceValue()
if resource is not None:
tmp_amount.setResourceValue(resource)
else:
error_string += 'No resource defined on %s' % self.getRelativeUrl()
# First, we set initial values for quantity and variation
# Currently, we only consider discrete variations
# Continuous variations will be implemented in a future version
# of ERP5
# Set quantity unit
quantity_unit = self.getQuantityUnit()
if quantity_unit is not None:
tmp_amount.setQuantityUnitValue(quantity_unit)
# Set efficiency
efficiency = self.getEfficiency()
if efficiency is None or efficiency is '' or efficiency == 0.0:
efficiency = 1.0
else:
efficiency = float(efficiency)
### current get quantity comportment exemple ###
# We define on transformation line:
# default_quantity = q
# quantity matrix
# | Child | Child/32 | Child/34 | Men | Women |
# | a | | b | c | |
# Result from getAggregatedAmountList:
# context | quantity
# _________________________
# Child | a
# Child/32 | a => acquired from Child
# Child/34 | a or b => we do not know which cell will be choosed
# Child/36 | a => acquired from Child
# Men | c
# Women | Error => no cell found
# noContext | Error => cell exist, but no context given
### comportment that JPS want ?? ###
# We define on transformation line:
# default_quantity = q
# quantity matrix
# | Child | Child/32 | Child/34 | Men | Women |
# | a | | b | c | |
# Result from getAggregatedAmountList:
# context | quantity
# _________________________
# Child | a
# Child/32 | a => acquired from Child
# Child/34 | a or b => we do not know which cell will be choosed
# Child/36 | Error => no such key in matrixbox cell range
# Men | c
# Women | Error => no cell found
# noContext | Error => cell exist, but no context given
# futur cool get quantity comportment exemple
# We define on transformation line:
# default_quantity = q
# quantity matrix
# | Child | Child/32 | Child/34 | Men | Women |
# | a | | b | c | |
# Result from getAggregatedAmountList:
# context | quantity
# _________________________
# Child | a
# Child/32 | a => acquired from Child
# Child/34 | b => test method must return a priority to choose between Child and Child/34
# Child/36 | Error => no such key in matrixbox cell range
# Men | c
# Women | q => acquired from default quantity
# noContext | q => acquired from default quantity
# get Quantity
quantity_defined_by = None
quantity = None
# We will browse the mapped values and determine which apply
cell_key_list = self.getCellKeyList(base_id='quantity')
if cell_key_list not in [(),[]]:
if context is None:
raise KeyError, \
"No context defined on TransformedResource '%s'" % \
(self.getRelativeUrl(), )
for key in cell_key_list:
if self.hasCell(base_id='quantity', *key):
mapped_value = self.getCell(base_id='quantity', *key)
if mapped_value.test(context):
if 'quantity' in mapped_value.getMappedValuePropertyList():
quantity = mapped_value.getProperty('quantity')
quantity_defined_by = mapped_value.getRelativeUrl()
if quantity in [None,'']:
raise KeyError, \
"No cell quantity matching on TransformedResource '%s' for "\
"current context" % ( self.getRelativeUrl() , )
else:
quantity = self.getQuantity()
quantity_defined_by = self.getRelativeUrl()
if quantity in [None,'']:
raise KeyError, \
"No quantity defined on TransformedResource '%s' for "\
"current context" % (self.getRelativeUrl(), )
# If we have to do this, then there is a problem....
# We'd better have better API for this,
# like an update function in the mapped_value
try:
quantity = float(quantity)
except ValueError:
error_string += 'Quantity is not a float.'
# If IAmount specifies that 4 resources are needed, all quantities
# need to be multiplicated by 4...
context_quantity = None
quantity_getter = getattr(context, "getQuantity", None)
if quantity_getter is not None:
_marker = object()
context_quantity = quantity_getter(_marker)
if context_quantity is _marker:
# XXX Backwards compatibility:
# previously, quantity property of the Amount was completely
# ignored, and was assumed to be 1.0 . Re-enact this old
# behavior (quantity default value is 0.0) to avoid breakages
warn("No quantity was defined on the Amount passed to " \
"getAggregatedAmountList, 1.0 was assumed", DeprecationWarning)
context_quantity = 1.0
else:
raise KeyError("No quantity defined on context")
quantity *= float(context_quantity)
# Get the variation category list
variation_category_list_defined_by = None
variation_category_list = None
# We will browse the mapped values and determine which apply
cell_key_list = self.getCellKeyList( base_id = 'variation')
if cell_key_list not in [(),[]]:
if context is None:
raise KeyError, \
"No context defined on TransformedResource '%s'" % \
(self.getRelativeUrl(), )
for key in cell_key_list:
if self.hasCell(base_id='variation', *key):
mapped_value = self.getCell(base_id='variation', *key)
if mapped_value.test(context):
vcl = mapped_value.getCategoryList()
if vcl != []:
variation_category_list = vcl
variation_category_list_defined_by = \
mapped_value.getRelativeUrl()
if variation_category_list in [None,'',[], ()]:
if quantity == 0:
return aggregated_amount_list
else:
raise KeyError, \
"No cell variation matching on TransformedResource '%s' "\
"for current context" % (self.getRelativeUrl(), )
else:
variation_category_list = self._getVariationCategoryList()
variation_category_list_defined_by = self.getRelativeUrl()
if hasattr(self,"getTradePhase"):
# After installing BPM, trade_phase category to be exists
trade_phase = self.getTradePhase()
else:
trade_phase = None
# Store values in Amount
tmp_amount._edit(
# Properties define on transformation line
title=self.getTitle(),
description=self.getDescription(),
efficiency=efficiency,
quantity=quantity,
# This fields only store some informations for debugging if necessary
quantity_defined_by=quantity_defined_by,
variation_category_list_defined_by=variation_category_list_defined_by,
trade_phase=trade_phase,
error_string=error_string
)
tmp_amount.setVariationCategoryList(variation_category_list)
# Variation property dict
tmp_amount.setVariationPropertyDict(self.getVariationPropertyDict())
aggregated_amount_list.append(tmp_amount)
return aggregated_amount_list
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment