Amount.py 20.6 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 29 30 31
#
# 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 Globals import InitializeClass
from AccessControl import ClassSecurityInfo
32 33
from Products.ERP5.Variated import Variated
from Products.ERP5.VariationValue import VariationValue
Jean-Paul Smets's avatar
Jean-Paul Smets committed
34 35
from Products.ERP5Type import Permissions, PropertySheet, Constraint, Interface
from Products.ERP5Type.Base import Base
36
from Products.ERP5Type.Base import TempBase
37
from Products.CMFCategory.Renderer import Renderer
Jean-Paul Smets's avatar
Jean-Paul Smets committed
38

39

Jean-Paul Smets's avatar
Jean-Paul Smets committed
40 41 42
from zLOG import LOG


43

Jean-Paul Smets's avatar
Jean-Paul Smets committed
44 45 46 47 48 49 50 51 52 53 54 55
class Amount(Base, Variated):
  """
    A mix-in class which provides some utilities
    (variations, conversions, etc.)

    Utilities include

    - getVariation accesors (allows to access variations of whatever)

    -
  """

56 57 58
  meta_type = 'ERP5 Amount'
  portal_type = 'Amount'

Jean-Paul Smets's avatar
Jean-Paul Smets committed
59 60
  # Declarative security
  security = ClassSecurityInfo()
61
  security.declareObjectProtected(Permissions.View)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
62 63 64 65

  # Declarative interfaces
  __implements__ = (Interface.Variated)

66 67 68 69
  property_sheets = ( PropertySheet.Base
                    , PropertySheet.SimpleItem
                    , PropertySheet.Amount
                    , PropertySheet.Price
70
                    )
71

Jean-Paul Smets's avatar
Jean-Paul Smets committed
72 73
  # A few more mix-in methods which should be relocated
  # THIS MUST BE UPDATE WITH CATEGORY ACQUISITION
74 75 76 77
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getVariationCategoryList')
  def getVariationCategoryList(self, base_category_list=(),
                               omit_option_base_category=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
78 79 80 81 82 83 84
    """
      Returns the possible discrete variations
      (as a list of relative urls to categories)
    """
    result = []
    resource = self.getDefaultResourceValue()
    if resource is not None:
85 86
      resource_variation_list = resource.getVariationBaseCategoryList(
                           omit_option_base_category=omit_option_base_category)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
87
      if len(base_category_list) > 0 :
88 89
        variation_list = filter(lambda x: x in base_category_list,
                                resource_variation_list)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
90 91 92
      else :
        variation_list = resource_variation_list
      if len(variation_list) > 0:
93
        result = self.getAcquiredCategoryMembershipList(variation_list, base=1)
Jean-Paul Smets's avatar
Jean-Paul Smets committed
94 95
    return result

96
  security.declareProtected(Permissions.AccessContentsInformation,
97
                            'getVariationCategoryItemList')
98 99
  def getVariationCategoryItemList(self, base_category_list=(), base=1,
                                   display_id='title',
100
                                   current_category=None,**kw):
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    """
      Returns the list of possible variations
      XXX Copied and modified from Variated
      Result is left display.
    """
    variation_category_item_list = []
    if base_category_list == ():
      base_category_list = self.getVariationRangeBaseCategoryList()

    for base_category in base_category_list:
      variation_category_list = self.getVariationCategoryList(
                                          base_category_list=[base_category])

      resource_list = [self.portal_categories.resolveCategory(x) for x in\
                       variation_category_list]
      category_list = [x for x in resource_list \
                       if x.getPortalType() == 'Category']
      variation_category_item_list.extend(Renderer(
                             is_right_display=0,
                             display_none_category=0, base=base,
                             current_category=current_category,
122
                             display_id='logical_path',**kw).\
123 124 125 126 127
                                               render(category_list))
      object_list = [x for x in resource_list \
                       if x.getPortalType() != 'Category']
      variation_category_item_list.extend(Renderer(
                             is_right_display=0,
128
                             base_category=base_category,
129 130
                             display_none_category=0, base=base,
                             current_category=current_category,
131
                             display_id=display_id,**kw).\
132 133 134
                                               render(object_list))
    return variation_category_item_list

Jean-Paul Smets's avatar
Jean-Paul Smets committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148
  security.declareProtected(Permissions.ModifyPortalContent, '_setVariationCategoryList')
  def _setVariationCategoryList(self, value):
    result = []
    resource = self.getDefaultResourceValue()
    if resource is not None:
      variation_list = resource.getVariationBaseCategoryList()
      if len(variation_list) > 0:
        self._setCategoryMembership(variation_list, value, base = 1)

  security.declareProtected(Permissions.ModifyPortalContent, 'setVariationCategoryList')
  def setVariationCategoryList(self, value):
    self._setVariationCategoryList(value)
    self.reindexObject()

149
  security.declareProtected(Permissions.ModifyPortalContent,
150 151
                            'getVariationBaseCategoryList')
  def getVariationBaseCategoryList(self, omit_option_base_category=0):
152
    """
153
      Return the list of base_category from all variation related to
154
      amount.
155 156
      It is maybe a nonsense, but useful for correcting user errors.
    """
157
    base_category_list = []
158 159
    for category in self.getVariationCategoryList(
                      omit_option_base_category=omit_option_base_category):
160 161 162 163
      base_category = category.split('/')[0]
      if base_category not in base_category_list:
        base_category_list.append(base_category)
    return base_category_list
164

Jean-Paul Smets's avatar
Jean-Paul Smets committed
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
  security.declareProtected(Permissions.AccessContentsInformation, 'getVariationValue')
  def getVariationValue(self):
    """
      New Method for dicrete and countinuous variations
      using a VariantValue instance

      A new instance of VariationValue is created with categories
      and attributes set to what they should be.

      A this point, we only implement discrete variations
    """
    return VariationValue(context = self)

  security.declareProtected(Permissions.ModifyPortalContent, '_setVariationValue')
  def _setVariationValue(self, variation_value):
    return variation_value.setVariationValue(self)

  security.declareProtected(Permissions.ModifyPortalContent, 'setVariationValue')
  def setVariationValue(self, variation_value):
    self._setVariationValue(variation_value)
    self.reindexObject()

187 188
  security.declareProtected(Permissions.AccessContentsInformation, \
                            'getVariationRangeCategoryItemList')
189
  def getVariationRangeCategoryItemList(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
190
    """
191 192 193 194 195 196
      Returns possible variation category values for the
      order line according to the default resource.
      Possible category values is provided as a list of
      tuples (id, title). This is mostly
      useful in ERP5Form instances to generate selection
      menus.
Jean-Paul Smets's avatar
Jean-Paul Smets committed
197
    """
198 199 200
    resource = self.getResourceValue()
    if resource != None:
      result = resource.getVariationCategoryItemList(
201
                               omit_individual_variation=0,**kw)
202 203 204
    else:
      result = []
    return result
205

206 207
  security.declareProtected(Permissions.AccessContentsInformation, \
                            'getVariationRangeCategoryList')
208
  def getVariationRangeCategoryList(self, base_category_list=(), base=1, **kw):
209
    """
210 211
      Returns possible variation category values for the
      order line according to the default resource.
212
    """
213 214
    return [x[1] for x in self.getVariationRangeCategoryItemList(
                                     base_category_list=base_category_list,
215
                                     base=base, **kw)]
Jean-Paul Smets's avatar
Jean-Paul Smets committed
216 217 218

  security.declareProtected(Permissions.AccessContentsInformation,
                                            'getVariationRangeBaseCategoryList')
219
  def getVariationRangeBaseCategoryList(self, omit_option_base_category=0):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
220 221 222 223 224 225 226 227 228 229
    """
        Returns possible variations base categories for this amount ie.
        the variation base category of the resource (not the
        variation range).

        Should be a range because we shall variate the amount
        into cells (ie. the line into cells) on part of the
        getVariationRangeBaseCategoryList -> notion of
        getVariationBaseCategoryList is different
    """
230
    resource = self.getDefaultResourceValue()
231
    if resource is not None:
232 233
      result = resource.getVariationBaseCategoryList(
                          omit_option_base_category=omit_option_base_category)
234 235 236
    else:
      result = self.portal_categories.getBaseCategoryList()
    return result
Jean-Paul Smets's avatar
Jean-Paul Smets committed
237

238 239 240 241 242 243 244 245 246 247
  #####################################################################
  #  Variation property API
  #####################################################################
  security.declareProtected(Permissions.AccessContentsInformation,
                            'getVariationPropertyDict')
  def getVariationPropertyDict(self):
    """
      Return a dictionary of:
        {property_id: property_value,}
      Each property is a variation of the resource.
248
      The variation property list is defined on resource,
249 250 251
      with setVariationPropertyList.
    """
    property_dict = {}
252
    resource = self.getDefaultResourceValue()
253 254 255 256
    if resource is not None:
      variation_list = resource.getVariationPropertyList()
      for variation_property in variation_list:
        property_dict[variation_property] = \
257
            self.getProperty(variation_property)
258 259
    return property_dict

260
  security.declareProtected(Permissions.ModifyPortalContent,
261 262 263 264 265 266
                            'setVariationPropertyDict')
  def setVariationPropertyDict(self, property_dict):
    """
      Take a parameter a property dict like:
        {property_id: property_value,}
      Each property is a variation of the resource.
267
      If one of the property_id is not a variation, a exception
268 269
      KeyError is raised.
    """
270
    resource = self.getDefaultResourceValue()
271 272 273 274 275 276 277 278 279
    if resource is not None:
      variation_list = resource.getVariationPropertyList()
    else:
      variation_list = []
    for property_id, property_value in property_dict.items():
      if property_id not in variation_list:
        raise KeyError, "Can not set the property variation '%s'" % \
                        property_id
      else:
280
        self.setProperty(property_id, property_value)
281

Jean-Paul Smets's avatar
Jean-Paul Smets committed
282 283 284
  security.declareProtected(Permissions.AccessContentsInformation,
                                                 'getQuantityUnitRangeItemList')
  def getQuantityUnitRangeItemList(self, base_category_list=()):
285 286 287 288
    resource = self.getDefaultResourceValue()
    if resource is not None:
      result = resource.getQuantityUnitList()
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
289 290 291 292 293 294
      result = ()
    if result is ():
      return self.portal_categories.quantity_unit.getFormItemList()
    else:
      return result

295 296 297 298 299 300

  security.declareProtected(Permissions.AccessContentsInformation, 'getResourceDefaultQuantityUnit')
  def getResourceDefaultQuantityUnit(self):
    """
      Return default quantity unit of the resource
    """
301 302 303
    resource = self.getResourceValue()
    resource_quantity_unit = None
    if resource is not None:
304 305
      resource_quantity_unit = resource.getDefaultQuantityUnit()
      #LOG("ERP5 WARNING:", 100, 'could not convert quantity for %s' % self.getRelativeUrl())
306
    return  resource_quantity_unit
307

308 309
  security.declareProtected(Permissions.AccessContentsInformation, 'getResourcePrice')
  def getResourcePrice(self):
310 311 312 313
    """
      Return default quantity unit of the resource
    """
    resource = self.getResourceValue()
314
    unit_base_price = resource.getPrice(context=self)
315 316 317 318 319 320 321 322 323
    return unit_base_price

  security.declareProtected(Permissions.AccessContentsInformation, 'getDuration')
  def getDuration(self):
    """
      Return duration in minute
    """
    quantity = self.getQuantity()
    quantity_unit = self.getQuantityUnit()
324 325
    if quantity_unit is None:
      return None
326
    common_time_category = 'time'
327
    if common_time_category in quantity_unit[:len(common_time_category)]:
328 329 330 331 332 333
      duration = quantity
    else:
      duration = None
    return duration

  security.declareProtected(Permissions.AccessContentsInformation, 'getTotalBasePrice')
334
  def getTotalPrice(self):
335 336 337
    """
      Return duration in minute
    """
338 339 340
    result = None
    efficiency = self.getEfficiency()
    if efficiency != 0:
341
      resource_price = self.getResourcePrice()
342 343 344 345 346 347
      if resource_price is not None:
        return resource_price * self.getConvertedQuantity() / efficiency
    price = self.getPrice()
    quantity = self.getQuantity()
    if type(price) in (type(1.0), type(1)) and type(quantity) in (type(1.0), type(1)):
      result = quantity * price
348
    return result
349

Jean-Paul Smets's avatar
Jean-Paul Smets committed
350 351 352 353 354 355
  # Conversion to standard unit
  security.declareProtected(Permissions.AccessContentsInformation, 'getConvertedQuantity')
  def getConvertedQuantity(self):
    """
      Converts quantity to default unit
    """
356 357 358 359 360
    resource = self.getResourceValue()
    quantity_unit = self.getQuantityUnit()
    quantity = self.getQuantity()
    converted_quantity = None
    if resource is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
361 362
      resource_quantity_unit = resource.getDefaultQuantityUnit()
      converted_quantity = resource.convertQuantity(quantity, quantity_unit, resource_quantity_unit)
363
    else:
364 365
      #LOG("ERP5 WARNING:", 100, 'could not convert quantity for %s' % self.getRelativeUrl())
      pass
Jean-Paul Smets's avatar
Jean-Paul Smets committed
366 367
    return converted_quantity

368 369
  security.declareProtected(Permissions.ModifyPortalContent, 'setConvertedQuantity')
  def setConvertedQuantity(self, value):
370 371 372
    resource = self.getResourceValue()
    quantity_unit = self.getQuantityUnit()
    if resource is not None:
373 374 375
      resource_quantity_unit = resource.getDefaultQuantityUnit()
      quantity = resource.convertQuantity(value, resource_quantity_unit, quantity_unit)
      self.setQuantity(quantity)
376
    else:
377 378
      LOG("ERP5 WARNING:", 100, 'could not set converted quantity for %s' % self.getRelativeUrl())

Jean-Paul Smets's avatar
Jean-Paul Smets committed
379 380 381 382 383 384 385
  security.declareProtected(Permissions.AccessContentsInformation, 'getNetQuantity')
  def getNetQuantity(self):
    """
      Take into account efficiency in quantity
    """
    quantity = self.getQuantity()
    efficiency = self.getEfficiency()
386
    if efficiency in (0, 0.0, None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
387 388 389 390 391 392 393 394 395 396
      efficiency = 1.0
    return float(quantity) / efficiency

  security.declareProtected(Permissions.AccessContentsInformation, 'getNetTargetQuantity')
  def getNetTargetQuantity(self):
    """
      Take into account efficiency in target quantity
    """
    quantity = self.getTargetQuantity()
    efficiency = self.getTargetEfficiency()
397
    if efficiency in (0, 0.0, None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
398 399 400 401 402 403 404 405 406 407
      efficiency = 1.0
    return float(quantity) / efficiency

  security.declareProtected(Permissions.AccessContentsInformation, 'getNetConvertedQuantity')
  def getNetConvertedQuantity(self):
    """
      Take into account efficiency in converted quantity
    """
    quantity = self.getConvertedQuantity()
    efficiency = self.getEfficiency()
408
    if efficiency in (0, 0.0, None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
409
      efficiency = 1.0
410
    if quantity not in (None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
411 412 413 414
      return float(quantity) / efficiency
    else:
      return None

415 416 417 418 419 420
  security.declareProtected(Permissions.ModifyPortalContent, 'setNetConvertedQuantity')
  def setNetConvertedQuantity(self, value):
    """
      Take into account efficiency in converted quantity
    """
    efficiency = self.getEfficiency()
421
    if efficiency in (0, 0.0, None, ''):
422
      efficiency = 1.0
423
    if value not in (None, ''):
424
      quantity = float(value) * efficiency
425 426
    else:
      quantity = value
427 428
    self.setConvertedQuantity(quantity)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
429 430 431 432 433 434 435
  security.declareProtected(Permissions.AccessContentsInformation, 'getNetConvertedTargetQuantity')
  def getNetConvertedTargetQuantity(self):
    """
      Take into account efficiency in converted target quantity
    """
    quantity = self.getConvertedTargetQuantity()
    efficiency = self.getTargetEfficiency()
436
    if efficiency in (0, 0.0, None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
437
      efficiency = 1.0
438
    if quantity not in (None, ''):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
439 440 441 442
      return float(quantity) / efficiency
    else:
      return None

443 444 445 446 447 448 449 450
  security.declareProtected(Permissions.ModifyPortalContent, 'setNetConvertedTargetQuantity')
  def setNetConvertedTargetQuantity(self, value):
    """
      Take into account efficiency in converted quantity
    """
    efficiency = self.getEfficiency()
    if efficiency in (0, 0.0, None):
      efficiency = 1.0
451
    if value not in (None, ''):
452
      quantity = float(value) * efficiency
453 454
    else:
      quantity = value
455 456
    self.setConvertedTargetQuantity(quantity)

Jean-Paul Smets's avatar
Jean-Paul Smets committed
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  security.declareProtected(Permissions.AccessContentsInformation, 'getInventoriatedQuantity')
  def getInventoriatedQuantity(self):
    """
      Take into account efficiency in converted target quantity
    """
    return self.getNetConvertedQuantity()

  # Helper methods to display quantities as produced / consumed
  security.declareProtected(Permissions.AccessContentsInformation, 'getProductionQuantity')
  def getProductionQuantity(self):
    """
      Return the produced quantity
    """
    quantity = self.getQuantity()
    source = self.getSource()
    destination = self.getDestination()

474
    if quantity is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
475
      quantity = float(quantity)
476
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
      quantity = 0.0

    if source in (None, ''):
      if quantity > 0:
        return quantity
      else:
        return 0.0

    if destination in (None, ''):
      if quantity < 0:
        return - quantity
      else:
        return 0.0

  security.declareProtected(Permissions.AccessContentsInformation, 'getConsumptionQuantity')
  def getConsumptionQuantity(self):
    """
      Return the produced quantity
    """
    quantity = self.getQuantity()
    source = self.getSource()
    destination = self.getDestination()

500
    if quantity is not None:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
501
      quantity = float(quantity)
502
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
      quantity = 0.0

    if destination in (None, ''):
      if quantity > 0:
        return quantity
      else:
        return 0.0

    if source in (None, ''):
      if quantity < 0:
        return - quantity
      else:
        return 0.0

  security.declareProtected(Permissions.ModifyPortalContent, 'setProductionQuantity')
  def setProductionQuantity(self, value):
    """
      Return the produced quantity
    """
    source = self.getSource()
    destination = self.getDestination()

525 526 527
    if quantity is not None:
      quantity = float(quantity)
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
528 529 530
      quantity = 0.0

    if source in (None, ''):
531
      if quantity >= 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
532 533 534 535 536
        self.setQuantity(quantity)
      else:
        return 0.0

    if destination in (None, ''):
537
      if quantity >= 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
538 539 540 541 542 543 544 545 546 547 548 549
        self.setQuantity(- quantity)
      else:
        return 0.0

  security.declareProtected(Permissions.ModifyPortalContent, 'setConsumptionQuantity')
  def setConsumptionQuantity(self, value):
    """
      Return the produced quantity
    """
    source = self.getSource()
    destination = self.getDestination()

550 551 552
    if quantity is not None:
      quantity = float(quantity)
    else:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
553 554 555
      quantity = 0.0

    if destination in (None, ''):
556
      if quantity >= 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
557 558 559 560 561
        self.setQuantity(quantity)
      else:
        return 0.0

    if source in (None, ''):
562
      if quantity >= 0:
Jean-Paul Smets's avatar
Jean-Paul Smets committed
563 564 565 566
        self.setQuantity(- quantity)
      else:
        return 0.0

567 568 569 570 571 572 573 574 575
  # Inventory
  security.declareProtected(Permissions.AccessContentsInformation, 'getConvertedInventory')
  def getConvertedInventory(self):
    """
      provides a default inventory value - None since
      no inventory was defined.
    """
    return None

576 577 578 579 580 581 582 583 584 585 586
  # Profit and Loss
  security.declareProtected(Permissions.ModifyPortalContent, 'getLostQuantity')
  def getLostQuantity(self):
    return - self.getProfitQuantity()

  security.declareProtected(Permissions.AccessContentsInformation, 'setLostQuantity')
  def setLostQuantity(self, value):
    return self.setProfitQuantity(- value)

  def _setLostQuantity(self, value):
    return self._setProfitQuantity(- value)