Resource.py 30.1 KB
Newer Older
Jean-Paul Smets's avatar
Jean-Paul Smets committed
1 2
##############################################################################
#
3
# Copyright (c) 2002, 2005 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 29
#
# 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.
#
##############################################################################

30
from math import log
Alexandre Boeglin's avatar
Alexandre Boeglin committed
31
from warnings import warn
Jean-Paul Smets's avatar
Jean-Paul Smets committed
32

33
from AccessControl import ClassSecurityInfo
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35 36
from DateTime import DateTime

from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
Jean-Paul Smets's avatar
Jean-Paul Smets committed
37
from Products.ERP5Type.XMLMatrix import XMLMatrix
38
from Products.ERP5Type.Base import Base
Jean-Paul Smets's avatar
Jean-Paul Smets committed
39 40

from Products.ERP5.Variated import Variated
41
#from Products.ERP5.Core.Resource import Resource as CoreResource
Sebastien Robin's avatar
Sebastien Robin committed
42
from Products.CMFCore.WorkflowCore import WorkflowMethod
43
from Products.CMFCategory.Renderer import Renderer
44
from Products.CMFCore.utils import getToolByName
Jean-Paul Smets's avatar
Jean-Paul Smets committed
45

Alexandre Boeglin's avatar
Alexandre Boeglin committed
46
from zLOG import LOG, WARNING
Jean-Paul Smets's avatar
Jean-Paul Smets committed
47

48 49
#class Resource(XMLMatrix, CoreResource, Variated):
class Resource(XMLMatrix, Variated):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
50 51 52 53 54 55
    """
      A Resource
    """

    meta_type = 'ERP5 Resource'
    portal_type = 'Resource'
56
    add_permission = Permissions.AddPortalContent
Jean-Paul Smets's avatar
Jean-Paul Smets committed
57 58 59 60 61
    isPortalContent = 1
    isRADContent = 1

    # Declarative security
    security = ClassSecurityInfo()
62
    security.declareObjectProtected(Permissions.AccessContentsInformation)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
63 64 65 66 67 68 69 70 71 72 73 74

    # Declarative interfaces
    __implements__ = ( Interface.Variated, )

    # Declarative properties
    property_sheets = ( PropertySheet.Base
                      , PropertySheet.XMLObject
                      , PropertySheet.CategoryCore
                      , PropertySheet.DublinCore
                      , PropertySheet.Price
                      , PropertySheet.Resource
                      , PropertySheet.Reference
75
                      , PropertySheet.FlowCapacity
Sebastien Robin's avatar
Sebastien Robin committed
76
                      , PropertySheet.VariationRange
77
                      , PropertySheet.DefaultSupply
Jean-Paul Smets's avatar
Jean-Paul Smets committed
78 79 80 81 82 83 84
                      )

    # Is it OK now ?
    # The same method is at about 3 different places
    # Some genericity is needed
    security.declareProtected(Permissions.AccessContentsInformation,
                                           'getVariationRangeCategoryItemList')
85 86 87
    def getVariationRangeCategoryItemList(self, base_category_list=(), base=1, 
                                          root=1, display_id='title', 
                                          display_base_category=1,
88
                                          current_category=None, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
89 90
        """
          Returns possible variations
91 92 93

          resource.getVariationRangeCategoryItemList
            => [(display, value)]
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
        
      ## Variation API (exemple) ##
        Base categories defined:
          - colour
          - morphology
          - size
        Categories defined:
          - colour/blue
          - colour/red
          - size/Man
          - size/Woman
        Resource 'resource' created with variation_base_category_list:
            (colour, morphology, size)

        resource.getVariationRangeCategoryList
        variation   | individual variation | result
        ____________________________________________________________________________________
                    |                      | (colour/blue, colour/red, size/Man, size/Woman)
        size/Man    |                      | (colour/blue, colour/red, size/Man, size/Woman)
        colour/blue |                      | (colour/blue, colour/red, size/Man, size/Woman)
                    |  colour/1            | (colour/1, size/Man, size/Woman)
                    |  morphology/2        | (colour/blue, colour/red, size/Man, size/Woman, morphology/2)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
116
        """
117
        result = []
Jean-Paul Smets's avatar
Jean-Paul Smets committed
118 119 120 121
        if base_category_list is ():
          base_category_list = self.getVariationBaseCategoryList()
        elif type(base_category_list) is type('a'):
          base_category_list = (base_category_list,)
122

123
        other_base_category_dict = dict([(i,1) for i in base_category_list])
Yoshinori Okuji's avatar
Yoshinori Okuji committed
124
        other_variations = self.searchFolder( \
125 126
                               portal_type=self.getPortalVariationTypeList(),
                               sort_on=[('title','ascending')])
Yoshinori Okuji's avatar
Yoshinori Okuji committed
127 128
        other_variations = [x.getObject() for x in other_variations]
        other_variations = [x for x in other_variations if x is not None]
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

        for object in other_variations:
          for base_category in object.getVariationBaseCategoryList():
            if (base_category_list is ()) or \
               (base_category in base_category_list):
              other_base_category_dict[base_category] = 0
              # XXX now, call Renderer a lot of time.
              # Better implementation needed
              result.extend(Renderer(
                                   base_category=base_category, 
                                   display_base_category=display_base_category,
                                   display_none_category=0, base=base,
                                   current_category=current_category,
                                   display_id=display_id).\
                                                     render([object]))
144

145 146 147 148
        other_base_category_item_list = filter(lambda x: x[1]==1, 
            other_base_category_dict.items())
        other_base_category_list = map(lambda x: x[0],
            other_base_category_item_list)
149 150 151 152
        # Get category variation
        if len(other_base_category_list) != 0:
          result += Variated.getVariationRangeCategoryItemList(
              self, base_category_list=other_base_category_list,
153
              base=base, display_base_category=display_base_category, **kw)
154
        # Return result
155
        return result
156

Jean-Paul Smets's avatar
Jean-Paul Smets committed
157 158
    security.declareProtected(Permissions.AccessContentsInformation,
                                           'getVariationCategoryItemList')
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
    def getVariationCategoryItemList(self, base_category_list=(), 
                                     omit_individual_variation=1, base=1,
                                     current_category=None,
                                     display_base_category=1,
                                     display_id='title', **kw):
      """
        Returns variations of the resource.
        If omit_individual_variation==1, does not return individual 
        variation.
        Else, returns them.
        Display is on left.
            => [(display, value)]

        *old parameters: base=1, current_category=None, 
                         display_id='getTitle' (default value getTitleOrId)
      """
      result = Variated.getVariationCategoryItemList(self, 
                            base_category_list=base_category_list, 
177 178
                            display_base_category=display_base_category, 
                            base=base, **kw)
179
      if not omit_individual_variation:
180 181
        other_variations = self.searchFolder(
                              portal_type=self.getPortalVariationTypeList())
182 183 184 185 186 187 188 189 190 191 192 193

        other_variations = map(lambda x: x.getObject(), other_variations)
        other_variations = filter(lambda x: x is not None, other_variations)

        for object in other_variations:
          for base_category in object.getVariationBaseCategoryList():
            if (base_category_list is ()) or \
               (base_category in base_category_list):
              # XXX append object, relative_url ?
              # XXX now, call Renderer a lot of time.
              # Better implementation needed
              result.extend(Renderer(
194 195 196 197 198 199
                             base_category=base_category, 
                             display_base_category=display_base_category,
                             display_none_category=0, base=base,
                             current_category=current_category,
                             display_id=display_id, **kw).\
                                               render([object]))
200 201 202
      return result

    security.declareProtected(Permissions.AccessContentsInformation,
203
                              'getVariationCategoryList')
204
    def getVariationCategoryList(self, default=[], base_category_list=(),
205
                                 omit_individual_variation=1, **kw):
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
      """
        Returns variations of the resource.
        If omit_individual_variation==1, does not return individual 
        variation.
        Else, returns them.

        ## Variation API (exemple) ##
        Base categories defined:
          - colour
          - morphology
          - size
        Categories defined:
          - colour/blue
          - colour/red
          - size/Man
          - size/Woman
        Resource 'resource' created with variation_base_category_list:
            (colour, morphology, size)

        resource.getVariationCategoryList
        variation   | individual variation | result
        _____________________________________________________
                    |                      | ()
        size/Man    |                      | (size/Man, )
        colour/blue |                      | (colour/blue, )
                    |  colour/1            | (colour/1, )
                    |  morphology/2        | (morphology/2, )
      """
      vcil = self.getVariationCategoryItemList(
235 236
                    base_category_list=base_category_list,
                    omit_individual_variation=omit_individual_variation,**kw)
237
      return map(lambda x: x[1], vcil)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
238 239 240 241 242 243 244 245 246 247 248 249

    # Unit conversion
    security.declareProtected(Permissions.AccessContentsInformation, 'convertQuantity')
    def convertQuantity(self, quantity, from_unit, to_unit):
      return quantity

# This patch is temporary and allows to circumvent name conflict in ZSQLCatalog process for Coramy
    security.declareProtected(Permissions.AccessContentsInformation,
                                              'getDefaultDestinationAmountBis')
    def getDefaultDestinationAmountBis(self, unit=None, variation=None, REQUEST=None):
      try:
        return self.getDestinationReference()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
250
      except AttributeError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
251 252 253 254 255 256 257 258
        return None

# This patch is temporary and allows to circumvent name conflict in ZSQLCatalog process for Coramy
    security.declareProtected(Permissions.AccessContentsInformation,
                                              'getDefaultSourceAmountBis')
    def getDefaultSourceAmountBis(self, unit=None, variation=None, REQUEST=None):
      try:
        return self.getSourceReference()
Yoshinori Okuji's avatar
Yoshinori Okuji committed
259
      except AttributeError:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
260 261 262 263 264 265 266 267 268 269
        return None


    # This patch allows variations to find a resource
    security.declareProtected(Permissions.AccessContentsInformation,
                                              'getDefaultResourceValue')
    def getDefaultResourceValue(self):
      return self


Romain Courteaud's avatar
Romain Courteaud committed
270
    ####################################################
Jean-Paul Smets's avatar
Jean-Paul Smets committed
271
    # Stock Management
Romain Courteaud's avatar
Romain Courteaud committed
272 273 274
    ####################################################
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventory')
275
    def getInventory(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
276
      """
277
      Returns inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
278
      """
279 280 281
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
282

Romain Courteaud's avatar
Romain Courteaud committed
283 284
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getCurrentInventory')
285
    def getCurrentInventory(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
286
      """
287
      Returns current inventory
Jean-Paul Smets's avatar
Jean-Paul Smets committed
288
      """
289 290 291
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getCurrentInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
292

Romain Courteaud's avatar
Romain Courteaud committed
293 294
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getAvailableInventory')
295
    def getAvailableInventory(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
296
      """
297 298
      Returns available inventory
      (current inventory - deliverable)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
299
      """
300 301 302
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getAvailableInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
303

Romain Courteaud's avatar
Romain Courteaud committed
304 305
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getFutureInventory')
306
    def getFutureInventory(self, **kw):
307 308 309
      """
      Returns inventory at infinite
      """
310 311 312
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getFutureInventory(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
313

Romain Courteaud's avatar
Romain Courteaud committed
314 315
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryList')
316 317 318 319
    def getInventoryList(self, **kw):
      """
      Returns list of inventory grouped by section or site
      """
320 321 322
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
323

Romain Courteaud's avatar
Romain Courteaud committed
324 325
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getCurrentInventoryList')
326
    def getCurrentInventoryList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
327
      """
328
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
329
      """
330 331 332 333 334 335 336 337 338 339 340 341 342
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getCurrentInventoryList(**kw)

    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getAvailableInventoryList')
    def getAvailableInventoryList(self, **kw):
      """
      Returns list of inventory grouped by section or site
      """
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getAvailableInventoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
343

Romain Courteaud's avatar
Romain Courteaud committed
344 345
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getFutureInventoryList')
346
    def getFutureInventoryList(self, **kw):
347 348 349
      """
      Returns list of inventory grouped by section or site
      """
350 351 352
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getFutureInventoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
353

Romain Courteaud's avatar
Romain Courteaud committed
354 355
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryStat')
356
    def getInventoryStat(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
357
      """
358
      Returns statistics of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
359
      """
360 361 362
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
363

Romain Courteaud's avatar
Romain Courteaud committed
364 365
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getCurrentInventoryStat')
366
    def getCurrentInventoryStat(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
367
      """
368
      Returns statistics of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
369
      """
370 371 372 373 374 375 376 377 378 379 380 381 382
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getCurrentInventoryStat(**kw)

    security.declareProtected(Permissions.AccessContentsInformation,
                              'getAvailableInventoryStat')
    def getAvailableInventoryStat(self, **kw):
      """
      Returns statistics of inventory grouped by section or site
      """
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getAvailableInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
383

Romain Courteaud's avatar
Romain Courteaud committed
384 385
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getFutureInventoryStat')
386
    def getFutureInventoryStat(self, **kw):
387 388 389
      """
      Returns statistics of inventory grouped by section or site
      """
390 391 392
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getFutureInventoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
393

Romain Courteaud's avatar
Romain Courteaud committed
394 395
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryChart')
396
    def getInventoryChart(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
397
      """
398
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
399
      """
400 401 402
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
403

Romain Courteaud's avatar
Romain Courteaud committed
404 405
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getCurrentInventoryChart')
406
    def getCurrentInventoryChart(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
407
      """
408
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
409
      """
410 411 412
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getCurrentInventoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
413

Romain Courteaud's avatar
Romain Courteaud committed
414 415
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getFutureInventoryChart')
416
    def getFutureInventoryChart(self, **kw):
417 418 419
      """
      Returns list of inventory grouped by section or site
      """
420 421 422
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getFutureInventoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
423

Romain Courteaud's avatar
Romain Courteaud committed
424 425
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryHistoryList')
426
    def getInventoryHistoryList(self, **kw):
427 428 429
      """
      Returns list of inventory grouped by section or site
      """
430 431 432
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryHistoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
433

Romain Courteaud's avatar
Romain Courteaud committed
434 435
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getInventoryHistoryChart')
436
    def getInventoryHistoryChart(self, **kw):
437 438 439
      """
      Returns list of inventory grouped by section or site
      """
440 441 442
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryHistoryChart(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
443

444 445 446 447
    # XXX FIXME
    # Method getCurrentMovementHistoryList, 
    # getAvailableMovementHistoryList, getFutureMovementHistoryList
    # can be added
Romain Courteaud's avatar
Romain Courteaud committed
448 449
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getMovementHistoryList')
450
    def getMovementHistoryList(self, **kw):
451 452 453
      """
      Returns list of inventory grouped by section or site
      """
454 455 456
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getMovementHistoryList(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
457

Romain Courteaud's avatar
Romain Courteaud committed
458 459
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getMovementHistoryStat')
460
    def getMovementHistoryStat(self, **kw):
461 462 463
      """
      Returns list of inventory grouped by section or site
      """
464 465 466
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getMovementHistoryStat(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
467

Romain Courteaud's avatar
Romain Courteaud committed
468 469
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getNextNegativeInventoryDate')
470
    def getNextNegativeInventoryDate(self, **kw):
471 472 473
      """
      Returns list of inventory grouped by section or site
      """
474 475 476
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getNextNegativeInventoryDate(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
477 478


479
    # Asset Price API
480 481
    security.declareProtected(Permissions.AccessContentsInformation,
        'getInventoryAssetPrice')
482
    def getInventoryAssetPrice(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
483
      """
484
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
485
      """
486 487 488
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getInventoryAssetPrice(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
489

490 491
    security.declareProtected(Permissions.AccessContentsInformation,
        'getCurrentInventoryAssetPrice')
492
    def getCurrentInventoryAssetPrice(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
493
      """
494
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
495
      """
496 497 498
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getCurrentInventoryAssetPrice(**kw)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
499

500 501
    security.declareProtected(Permissions.AccessContentsInformation,
        'getAvailableInventoryAssetPrice')
502
    def getAvailableInventoryAssetPrice(self, **kw):
503 504 505
      """
      Returns list of inventory grouped by section or site
      """
506 507 508
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getAvailableInventoryAssetPrice(**kw)
509

510 511
    security.declareProtected(Permissions.AccessContentsInformation,
        'getFutureInventoryAssetPrice')
512
    def getFutureInventoryAssetPrice(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
513
      """
514
      Returns list of inventory grouped by section or site
Jean-Paul Smets's avatar
Jean-Paul Smets committed
515
      """
516 517 518
      kw['resource_uid'] = self.getUid()
      portal_simulation = getToolByName(self, 'portal_simulation')
      return portal_simulation.getFutureInventoryAssetPrice(**kw)
519

Jean-Paul Smets's avatar
Jean-Paul Smets committed
520

521
    # Industrial price API
522 523
    security.declareProtected(Permissions.AccessContentsInformation,
        'getIndustrialPrice')
524 525 526 527 528 529 530 531 532 533 534 535
    def getIndustrialPrice(self, context=None, REQUEST=None, **kw):
      """
        Returns industrial price
      """
      context = self.asContext(context=context, REQUEST=REQUEST, **kw)
      result = self._getIndustrialPrice(context)
      return result

    def _getIndustrialPrice(self, context):
      # Default value is None
      return None

536
    # Predicate handling
537 538
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'asPredicate')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
539 540 541 542 543 544 545
    def asPredicate(self):
      """
      Returns a temporary Predicate based on the Resource properties
      """
      from Products.ERP5 import newTempPredicateGroup as newTempPredicate
      p = newTempPredicate(self.getId(), uid = self.getUid())
      p.setMembershipCriterionBaseCategoryList(('resource',))
546 547
      p.setMembershipCriterionCategoryList(('resource/%s'
          % self.getRelativeUrl(),))
Jean-Paul Smets's avatar
Jean-Paul Smets committed
548
      return p
549

550
    def _pricingSortMethod(self, a, b):
Alexandre Boeglin's avatar
Alexandre Boeglin committed
551 552 553 554 555 556 557
      # Simple method : the one that defines a destination wins
      parent = a.getParentValue()
      if parent.getPortalType().endswith(' Line'):
        parent = parent.getParentValue()
      if parent.getDestination():
        return -1 # a has a destination and wins
      return 1 # a has no destination ans loses
558

559
    security.declareProtected(Permissions.AccessContentsInformation, 
560 561
                              'getPriceParameterDict')
    def getPriceParameterDict(self, context=None, REQUEST=None, **kw):
562
      """
563
      Get all pricing parameters from Predicate.
564
      """
565
      # Search all categories context
566
      new_category_list = []
567
      if context is not None:
568
        new_category_list += context.getCategoryList()
569 570
      #XXX This should be 'category_list' instead of 'categories' to respect
      # the naming convention. Must take care of side effects when fixing
571 572 573
      if kw.has_key('categories'):
        new_category_list.extend(kw['categories'])
        del kw['categories']
574 575
      resource_category = 'resource/' + self.getRelativeUrl()
      if not resource_category in new_category_list:
576 577 578
        new_category_list += (resource_category, )
      # Generate the predicate mapped value
      # to get some price values.
579
      domain_tool = getToolByName(self,'portal_domains')
580
      portal_type_list = self.getPortalSupplyPathTypeList()
581

Alexandre Boeglin's avatar
Alexandre Boeglin committed
582 583 584 585 586 587 588 589 590 591 592
      # Generate the fake context
      tmp_context = self.asContext(context=context, 
                                   categories=new_category_list,
                                   REQUEST=REQUEST, **kw)
      tmp_kw = kw.copy()
      if 'sort_method' not in tmp_kw:
        tmp_kw['sort_method'] = self._pricingSortMethod
      mapped_value = domain_tool.generateMultivaluedMappedValue(
                                             tmp_context,
                                             portal_type=portal_type_list,
                                             has_cell_content=0, **tmp_kw)
593 594 595
      # Get price parameters
      price_parameter_dict = {
        'base_price': None,
596 597 598
        'additional_price': [],
        'surcharge_ratio': [],
        'discount_ratio': [],
599
        'exclusive_discount_ratio': None,
600 601
        'variable_additional_price': [],
        'non_discountable_additional_price': [],
602
      }
Alexandre Boeglin's avatar
Alexandre Boeglin committed
603 604 605 606 607 608 609 610 611 612 613 614
      if mapped_value is None:
        return price_parameter_dict
      for price_parameter_name in price_parameter_dict.keys():
        price_parameter_value = \
          mapped_value.getProperty(price_parameter_name)
        if price_parameter_value not in [None, '']:
          try:
            price_parameter_dict[price_parameter_name].extend(
                                            price_parameter_value)
          except AttributeError:
            if price_parameter_dict[price_parameter_name] is None:
              if price_parameter_name == 'exclusive_discount_ratio':
615
                price_parameter_dict[price_parameter_name] = \
Alexandre Boeglin's avatar
Alexandre Boeglin committed
616 617 618 619
                    max(price_parameter_value)
              else:
                price_parameter_dict[price_parameter_name] = \
                    price_parameter_value[0]
620 621
      return price_parameter_dict
      
622
    security.declareProtected(Permissions.AccessContentsInformation,
623 624
        'getPricingVariable')
    def getPricingVariable(self, context=None):
625 626 627 628
      """
      Return the value of the property used to calculate variable pricing
      This basically calls a script like Product_getPricingVariable
      """
629
      method = None
630
      if context is not None:
631
        method = context._getTypeBasedMethod('getPricingVariable')
632
      if method is None or context is None:
633
        method = self._getTypeBasedMethod('getPricingVariable')
634

635 636 637 638
      if method is None:
        return 0.0
      return float(method())

639 640
    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getPrice')
641
    def getPrice(self, default=None, context=None, REQUEST=None, **kw):
642 643 644
      """
      Return the unit price of a resource in a specific context.
      """
645 646 647 648 649 650 651 652 653 654
      # see Movement.getPrice
      if isinstance(default, Base) and context is None:
        msg = 'getPrice first argument is supposed to be the default value'\
              ' accessor, the context should be passed as with the context='\
              ' keyword argument'
        warn(msg, DeprecationWarning)
        LOG('ERP5', WARNING, msg)
        context = default
        default = None
      
655
      price_parameter_dict = self.getPriceParameterDict(
656 657 658
                                     context=context, REQUEST=REQUEST, **kw)
      # Calculate the unit price
      unit_base_price = None
659
      # Calculate
660 661 662 663 664
#     ((base_price + SUM(additional_price) +
#     variable_value * SUM(variable_additional_price)) *
#     (1 - MIN(1, MAX(SUM(discount_ratio) , exclusive_discount_ratio ))) +
#     SUM(non_discountable_additional_price)) *
#     (1 + SUM(surcharge_ratio))
665 666 667 668 669
      # Or, as (nearly) one single line :
#     ((bp + S(ap) + v * S(vap))
#       * (1 - m(1, M(S(dr), edr)))
#       + S(ndap))
#     * (1 + S(sr))
670 671 672
      # Variable value is dynamically configurable through a python script.
      # It can be anything, depending on business requirements.
      # It can be seen as a way to define a pricing model that not only
673 674
      # depends on discrete variations, but also on a continuous property
      # of the object
675

676
      base_price = price_parameter_dict['base_price']
677
      if base_price in [None, '']:
678 679
        # XXX Compatibility
        # base_price must not be defined on resource
680 681
        base_price = self.getBasePrice()
      if base_price not in [None, '']:
682 683
        unit_base_price = base_price
        # Sum additional price
684
        for additional_price in price_parameter_dict['additional_price']:
685
          unit_base_price += additional_price
686
        # Sum variable additional price
687
        variable_value = self.getPricingVariable(context=context)
688 689
        for variable_additional_price in \
            price_parameter_dict['variable_additional_price']:
690
          unit_base_price += variable_additional_price * variable_value
691
        # Discount
692 693 694
        sum_discount_ratio = 0
        for discount_ratio in price_parameter_dict['discount_ratio']:
          sum_discount_ratio += discount_ratio
695 696 697
        exclusive_discount_ratio = \
            price_parameter_dict['exclusive_discount_ratio']
        d_ratio = 0
698
        d_ratio = max(d_ratio, sum_discount_ratio)
699 700 701 702 703
        if exclusive_discount_ratio not in [None, '']:
          d_ratio = max(d_ratio, exclusive_discount_ratio)
        if d_ratio != 0:
          d_ratio = 1 - min(1, d_ratio)
          unit_base_price = unit_base_price * d_ratio
704 705 706 707 708 709 710 711 712
        # Sum non discountable additional price
        for non_discountable_additional_price in\
            price_parameter_dict['non_discountable_additional_price']:
          unit_base_price += non_discountable_additional_price
        # Surcharge ratio
        sum_surcharge_ratio = 1
        for surcharge_ratio in price_parameter_dict['surcharge_ratio']:
          sum_surcharge_ratio += surcharge_ratio
        unit_base_price = unit_base_price * sum_surcharge_ratio
713 714
      # Divide by the priced quantity
      if unit_base_price is not None:
715
        priced_quantity = self.getPricedQuantity()
716
        unit_base_price = unit_base_price / priced_quantity
717 718
      # Return result
      return unit_base_price
Yoshinori Okuji's avatar
Yoshinori Okuji committed
719 720 721 722 723 724

    security.declareProtected(Permissions.AccessContentsInformation, 
                              'getQuantityPrecision')
    def getQuantityPrecision(self):
      """Return the floating point precision of a quantity.
      """
725 726 727
      try:
        return int(round(- log(self.getBaseUnitQuantity(), 10),0))
      except TypeError:
Yoshinori Okuji's avatar
Yoshinori Okuji committed
728
        return 0
729
      return 0