TransformedResource.py 14.8 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3
# Copyright (c) 2002, 2004 Nexedi SARL and Contributors. All Rights Reserved.
4
#                    Jean-Paul Smets-Solanes <jp@nexedi.com>
5
#                    Romain Courteaud <romain@nexedi.com>
Jean-Paul Smets's avatar
Jean-Paul Smets committed
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
Jean-Paul Smets's avatar
Jean-Paul Smets committed
30

31
from Products.ERP5Type.Globals import InitializeClass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32 33
from AccessControl import ClassSecurityInfo

34
from Products.ERP5Type import Permissions, PropertySheet, interfaces
Jean-Paul Smets's avatar
Jean-Paul Smets committed
35 36 37
from Products.ERP5Type.XMLObject import XMLObject
from Products.ERP5Type.XMLMatrix import XMLMatrix
from Products.ERP5Type.Utils import cartesianProduct
Yoshinori Okuji's avatar
Yoshinori Okuji committed
38
from Products.ERP5Type.Base import TempBase
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39

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

43
from Products.CMFCore.Expression import Expression
44
from Products.ERP5.Document.Predicate import Predicate
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45 46 47

from zLOG import LOG

48
class TransformedResource(Predicate, XMLObject, XMLMatrix, Amount):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
49 50 51 52 53 54 55 56 57
    """
        TransformedResource defines which
        resource is being transformed

        - variation
        - quantity

        Maybe defined by mapped values inside the transformed resource

58 59 60
      XXX Transformation works only for a miximum of 3 variation base category...
      Matrixbox must be rewrite for a clean implementation of n base category

Jean-Paul Smets's avatar
Jean-Paul Smets committed
61 62 63 64 65 66 67 68

    """

    meta_type = 'ERP5 Transformed Resource'
    portal_type = 'Transformed Resource'

    # Declarative security
    security = ClassSecurityInfo()
69
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
70 71 72 73

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.SimpleItem
Jean-Paul Smets's avatar
Jean-Paul Smets committed
74
                      , PropertySheet.CategoryCore
Jean-Paul Smets's avatar
Jean-Paul Smets committed
75
                      , PropertySheet.Amount
76
                      , PropertySheet.Reference
Jean-Paul Smets's avatar
Jean-Paul Smets committed
77 78 79 80
                      , PropertySheet.TransformedResource
                      )

    # Declarative interfaces
81
    zope.interface.implements( interfaces.ITransformation )
Jean-Paul Smets's avatar
Jean-Paul Smets committed
82 83 84

    ### Variation matrix definition
    #
85 86
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'updateVariationCategoryList')
87 88
    def updateVariationCategoryList(self):
      """
89 90
        Check if variation category list of the resource changed and 
        update transformed resource by doing a set cell range
91
      """
92 93
      self.setQVariationBaseCategoryList(self.getQVariationBaseCategoryList())
      self.setVVariationBaseCategoryList(self.getVVariationBaseCategoryList())
94

95 96
    security.declareProtected(Permissions.ModifyPortalContent, 
                              '_updateQMatrixCellRange')
97
    def _updateQMatrixCellRange(self):
Romain Courteaud's avatar
Romain Courteaud committed
98
      # XXX use base_id parameter instead
99
      cell_range =  self.TransformedResource_asCellRange('quantity')
100 101 102 103
      # XXX TransformedResource works only for a maximum of 3 variation
      # base category...
      # Matrixbox must be rewrite for a clean implementation of n base
      # category
104 105 106 107 108
      if len(cell_range) <= 3:
        self.setCellRange(base_id='quantity', *cell_range)
      else:
        raise MoreThan3VariationBaseCategory

109 110
    security.declareProtected(Permissions.ModifyPortalContent, 
                              '_setQVariationBaseCategoryList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
111 112 113 114 115 116
    def _setQVariationBaseCategoryList(self, value):
      """
        Defines the possible base categories which Quantity value (Q)
        variate on
      """
      self._baseSetQVariationBaseCategoryList(value)
Romain Courteaud's avatar
Romain Courteaud committed
117
      # XXX calling updatecellRange is better
118
      self._updateQMatrixCellRange()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
119

120 121
    security.declareProtected(Permissions.ModifyPortalContent, 
                              'setQVariationBaseCategoryList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
122 123 124 125 126 127 128 129
    def setQVariationBaseCategoryList(self, value):
      """
        Defines the possible base categories which Quantity value (Q)
        variate on and reindex the object
      """
      self._setQVariationBaseCategoryList(value)
      self.reindexObject()

130 131
    security.declareProtected(Permissions.ModifyPortalContent, 
                              '_updateVMatrixCellRange')
132
    def _updateVMatrixCellRange(self):
Romain Courteaud's avatar
Romain Courteaud committed
133
      # XXX use base_id parameter instead
134
      cell_range =  self.TransformedResource_asCellRange('variation')
135 136 137 138
      # XXX TransformedResource works only for a maximum of 3 variation
      # base category...
      # Matrixbox must be rewrite for a clean implementation of n base
      # category
139 140 141 142 143
      if len(cell_range) <= 3:
        self.setCellRange(base_id='variation', *cell_range)
      else:
        raise MoreThan3VariationBaseCategory

144 145
    security.declareProtected(Permissions.ModifyPortalContent, 
                              '_setVVariationBaseCategoryList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
146 147 148 149 150 151
    def _setVVariationBaseCategoryList(self, value):
      """
        Defines the possible base categories which Variation value (V)
        variate on
      """
      self._baseSetVVariationBaseCategoryList(value)
Romain Courteaud's avatar
Romain Courteaud committed
152
      # XXX calling updatecellRange is better
153
      self._updateVMatrixCellRange()
Jean-Paul Smets's avatar
Jean-Paul Smets committed
154

155 156
    security.declareProtected(Permissions.ModifyPortalContent, 
                              'setVVariationBaseCategoryList')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158 159 160 161 162 163 164
    def setVVariationBaseCategoryList(self, value):
      """
        Defines the possible base categories which Variation value (V)
        variate on and reindex the object
      """
      self._setVVariationBaseCategoryList(value)
      self.reindexObject()

165 166 167
    def updateAggregatedAmountList(self, context, **kw):
      raise NotImplementedError('TODO')

168 169
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getAggregatedAmountList')
170
    def getAggregatedAmountList(self, context=None, REQUEST=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
171
      """
172
        Get all interesting amount value and return AggregatedAmountList
Jean-Paul Smets's avatar
Jean-Paul Smets committed
173
      """
174 175 176
      context = self.asContext(context=context, REQUEST=REQUEST, **kw)
      # Create the result object
      aggregated_amount_list = AggregatedAmountList()
177 178 179 180 181 182
      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
183 184 185
        # XXX changed by TB getParentID()+getId() instead of getId()
        # This might not be enough if we have different transformation
        # with the same id (for example in several modules)
186 187 188
        parent = self.getParentValue()
        tmp_amount = parent.newContent(id=self.getParentId()+'_'+self.getId(),
                        temp_object=1, portal_type=self.getPortalType())
189 190 191 192
        # Create error string
        error_string = ''
        # Add resource relation
        resource = self.getDefaultResourceValue()
Fabien Morin's avatar
Fabien Morin committed
193
        if resource is not None:
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
          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')
Fabien Morin's avatar
Fabien Morin committed
267 268
        if cell_key_list not in [(),[]]:
          if context is None:
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
            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()
286
        if quantity in [None,'']:
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
          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.'
        # 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')
Fabien Morin's avatar
Fabien Morin committed
302 303
        if cell_key_list not in [(),[]]:
          if context is None:
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
            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()
326 327 328 329 330
        if hasattr(self,"getTradePhase"):
          # After installing BPM, trade_phase category to be exists
          trade_phase = self.getTradePhase()
        else:
          trade_phase = None
331 332 333
        # Store values in Amount
        tmp_amount._edit(
          # Properties define on transformation line
334 335 336 337
          title=self.getTitle(),
          description=self.getDescription(),
          efficiency=efficiency,
          quantity=quantity,
338
          # This fields only store some informations for debugging if necessary
339 340 341 342
          quantity_defined_by=quantity_defined_by,
          variation_category_list_defined_by=variation_category_list_defined_by,
          trade_phase=trade_phase,
          error_string=error_string
343 344
        )
        tmp_amount.setVariationCategoryList(variation_category_list)
345
        # Variation property dict
346
        tmp_amount.setVariationPropertyDict(self.getVariationPropertyDict())
347
        aggregated_amount_list.append(tmp_amount)
348
      return aggregated_amount_list