testInventoryAPI.py 158 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
##############################################################################
#
# Copyright (c) 2004 Nexedi SARL and Contributors. All Rights Reserved.
#          Jerome Perrin <jerome@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
##############################################################################

"""Unit Tests for Inventory API.
30 31

TODO: test variation
32
      test selection_domain, selection_report
33 34
"""

35
import os
36 37
import random
import unittest
38

39 40
from AccessControl.SecurityManagement import newSecurityManager
from DateTime import DateTime
41
from Testing import ZopeTestCase
42 43

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
44
from Products.ERP5Type.tests.utils import reindex
Sebastien Robin's avatar
Sebastien Robin committed
45
from Products.ERP5Type.tests.backportUnittest import expectedFailure
46
from Products.DCWorkflow.DCWorkflow import ValidationFailed
47
from Products.ERP5Type.Base import _aq_reset
48
from Products.ERP5Type.tests.utils import createZODBPythonScript
49

50 51 52
class InventoryAPITestCase(ERP5TypeTestCase):
  """Base class for Inventory API Tests {{{
  """
Julien Muchembled's avatar
Julien Muchembled committed
53
  business_process = 'business_process_module/erp5_default_business_process'
54 55 56 57 58 59 60 61 62

  GROUP_CATEGORIES = ( 'group/test_group/A1/B1/C1',
                       'group/test_group/A1/B1/C2',
                       'group/test_group/A1/B2/C1',
                       'group/test_group/A1/B2/C2',
                       'group/test_group/A2/B1/C1',
                       'group/test_group/A2/B1/C2',
                       'group/test_group/A2/B2/C1',
                       'group/test_group/A2/B2/C2', )
63 64 65 66 67 68 69 70 71

  VARIATION_CATEGORIES = ( 'colour/red',
                           'colour/green',
                           'colour/blue',
                           'size/big',
                           'size/small',
                           'industrial_phase/phase1',
                           'industrial_phase/phase2', )

72 73
  def getTitle(self):
    """Title of the test."""
74 75
    return 'Inventory API'

76
  def getPortalName(self):
77 78 79 80 81 82 83
    """ID of the portal. """
    forced_portal_id = os.environ.get('erp5_tests_portal_id')
    if forced_portal_id:
      return str(forced_portal_id)
    # all test methods here cleanup correctly, so we can use the same portal
    # for all those tests.
    return 'inventory_api_test'
84

85 86 87 88
  def getItemModule(self):
    """ the apparel fabric module """
    return getattr(self.getPortal(),'apparel_fabric_item_module')

89 90 91 92
  def getProductModule(self):
    return getattr(self.getPortal(), 'product',
        getattr(self.getPortal(), 'product_module'))

93 94 95 96
  def afterSetUp(self):
    """set up """
    self.createCategories()
    self.login()
97 98
    if not hasattr(self.portal, 'testing_folder'):
      self.portal.newContent(portal_type='Folder',
99
                            id='testing_folder')
100
    self.folder = self.portal.testing_folder
101 102
    
    self.section = self._makeOrganisation(title='Section')
103
    self.other_section = self._makeOrganisation(title='Other Section')
104
    self.node = self._makeOrganisation(title='Node')
105
    self.other_node = self._makeOrganisation(title='Other Node')
106 107 108
    self.payment_node = self.section.newContent(
                                  title='Payment Node',
                                  portal_type='Bank Account')
109 110 111
    self.other_payment_node = self.section.newContent(
                                  title='Other Payment Node',
                                  portal_type='Bank Account')
112 113
    self.mirror_section = self._makeOrganisation(title='Mirror Section')
    self.mirror_node = self._makeOrganisation(title='Mirror Node')
114 115
    self.project = self._makeProject(title='Project')
    self.other_project = self._makeProject(title='Other Project')
116
    self.resource = self.getProductModule().newContent(
117
                                  title='Resource',
118 119
                                  portal_type='Product')
    self.other_resource = self.getProductModule().newContent(
120
                                  title='Other Resource',
121
                                  portal_type='Product')
122 123
    self.item = self.getItemModule().newContent(title='Item')
    self.other_item = self.getItemModule().newContent(title='Other Item')
124 125
    self.getInventory = self.getSimulationTool().getInventory

126 127 128 129
  def beforeTearDown(self):
    """Clear everything for next test."""
    for module in [ 'organisation_module',
                    'person_module',
130
                    'product_module',
131
                    'portal_simulation',
132
                    'inventory_module',
133
                    self.folder.getId() ]:
Julien Muchembled's avatar
Julien Muchembled committed
134 135
      folder = self.portal[module]
      folder.manage_delObjects(list(folder.objectIds()))
136 137
    self.portal.portal_skins.custom.manage_delObjects(list(self.portal.portal_skins.custom.objectIds()))

Julien Muchembled's avatar
Julien Muchembled committed
138
    self.tic()
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156

  def login(self, quiet=0, run=1):
    uf = self.getPortal().acl_users
    uf._doAddUser('alex', '', ['Manager', 'Assignee', 'Assignor',
                               'Associate', 'Auditor', 'Author'], [])
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
  
  def createCategories(self):
    """Create the categories for our test. """
    # create categories
    for cat_string in self.getNeededCategoryList() :
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
      for cat in cat_string.split("/")[1:] :
        if not cat in path.objectIds() :
          path = path.newContent(
                    portal_type='Category',
157
                    id=cat,)
158 159 160 161 162 163 164
        else:
          path = path[cat]
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
165
    self.tic()
166 167 168 169 170 171 172
                
  def getNeededCategoryList(self):
    """return a list of categories that should be created."""
    return (  'region/level1/level2',
              'group/level1/level2',
              'group/anotherlevel',
              'product_line/level1/level2',
173
              'product_line/anotherlevel',
Sebastien Robin's avatar
Sebastien Robin committed
174 175
              'use/use1',
              'use/use2',
176 177
              'function/function1',
              'function/function1/function2',
178
           # we create a huge group category for consolidation tests
179
           ) + self.GROUP_CATEGORIES + self.VARIATION_CATEGORIES
180 181
  
  def getBusinessTemplateList(self):
182 183 184
    """ erp5_trade is required for transit_simulation_state
        erp5_apparel is required for item
    """
185 186
    return ('erp5_base', 'erp5_pdm', 'erp5_dummy_movement', 'erp5_simulation',
            'erp5_trade', 'erp5_apparel', 'erp5_project',
187
            'erp5_configurator_standard_trade_template',
Aurel's avatar
Aurel committed
188
            'erp5_simulation_test')
189 190

  # TODO: move this to a base class {{{
191
  @reindex
192 193 194 195 196 197 198
  def _makeOrganisation(self, **kw):
    """Creates an organisation."""
    org = self.getPortal().organisation_module.newContent(
          portal_type='Organisation',
          **kw)
    return org

199 200 201
  @reindex
  def _makeProject(self, **kw):
    """Creates an project."""
Julien Muchembled's avatar
Julien Muchembled committed
202
    return self.portal.project_module.newContent(
203 204 205
          portal_type='Project',
          **kw)

206
  @reindex
207 208
  def _makeSalePackingList(self, **kw):
    """Creates a sale packing list."""
Julien Muchembled's avatar
Julien Muchembled committed
209 210 211 212
    return self.portal.sale_packing_list_module.newContent(
          portal_type='Sale Packing List',
          specialise=self.business_process,
          **kw)
213
  
214
  @reindex
215 216
  def _makeSaleInvoice(self, created_by_builder=0, **kw):
    """Creates a sale invoice."""
Julien Muchembled's avatar
Julien Muchembled committed
217
    return self.portal.accounting_module.newContent(
218
          portal_type='Sale Invoice Transaction',
Julien Muchembled's avatar
Julien Muchembled committed
219 220 221
          created_by_builder=created_by_builder,
          specialise=self.business_process,
          **kw)
222

223
  @reindex
224 225 226 227
  def _makeProduct(self, **kw):
    """Creates a product."""
    product = self.getProductModule().newContent(
            portal_type = 'Product', **kw)
228
    self.tic()
229 230
    return product
  _makeResource = _makeProduct
231 232
  # }}}

233
  @reindex
234
  def _makeMovement(self, is_internal=0, **kw):
235 236 237 238 239 240 241
    """Creates a movement.
    """
    mvt = self.folder.newContent(portal_type='Dummy Movement')
    kw.setdefault('destination_section_value', self.section)
    kw.setdefault('source_section_value', self.mirror_section)
    kw.setdefault('destination_value', self.node)
    kw.setdefault('source_value', self.mirror_node)
242 243 244
    if is_internal:
      kw['source_section_value'] = None
      kw['source_value'] = None
245 246 247
    kw.setdefault('resource_value', self.resource)
    mvt.edit(**kw)
    return mvt
248 249
  
  @reindex
250 251 252
  def _makeSimulationMovement(self, **kw):
    """Creates a simulation movement.
    """
Julien Muchembled's avatar
Julien Muchembled committed
253 254
    ar = self.getSimulationTool().newContent(portal_type='Applied Rule',
      specialise_value=self.getRule(reference='default_delivery_rule'))
255 256 257 258 259 260 261 262 263
    mvt = ar.newContent(portal_type='Simulation Movement')
    kw.setdefault('destination_section_value', self.section)
    kw.setdefault('source_section_value', self.mirror_section)
    kw.setdefault('destination_value', self.node)
    kw.setdefault('source_value', self.mirror_node)
    kw.setdefault('resource_value', self.resource)
    mvt.edit(**kw)
    return mvt

264 265 266 267 268
# }}}

class TestInventory(InventoryAPITestCase):
  """Tests getInventory methods.
  """
269
  def assertInventoryEquals(self, value, **inventory_kw):
270 271
    self.assertEquals(value, self.getInventory(**inventory_kw))

272
  def testReturnedTypeIsFloat(self):
273
    """getInventory returns a float"""
274 275
    inventory = self.getInventory()
    self.assertEquals(type(inventory), type(0.1))
276
    # default is 0
277
    self.assertEquals(0, inventory)
278

279
  def test_SimulationMovement(self):
280 281 282
    """Test Simulation Movements works in this testing environnement.
    """
    self._makeSimulationMovement(quantity=100)
283
    self.assertInventoryEquals(100, section_uid=self.section.getUid())
284 285
    # mixed with a real movement
    self._makeMovement(quantity=100)
286
    self.assertInventoryEquals(200, section_uid=self.section.getUid())
287

288
  def test_SimulationMovementisAccountable(self):
289 290
    """Test Simulation Movements are not accountable if related to a delivery.
    """
291 292
    sim_mvt = self._makeSimulationMovement(quantity=2)
    mvt = self._makeMovement(quantity=3)
293 294 295 296 297 298
    # simulation movement are accountable,
    self.failUnless(sim_mvt.isAccountable())
    # unless connected to a delivery movement
    sim_mvt.setDeliveryValue(mvt)
    self.failIf(sim_mvt.isAccountable())
    # not accountable movement are not counted by getInventory
299
    self.tic() # (after reindexing of course)
300 301 302 303
    self.assertInventoryEquals(3, section_uid=self.section.getUid())
    # unless you pass only_accountable=False
    self.assertInventoryEquals(5, section_uid=self.section.getUid(), only_accountable=False)

304
  def test_OmitSimulation(self):
305 306 307 308
    """Test omit_simulation argument to getInventory.
    """
    self._makeSimulationMovement(quantity=100)
    self._makeMovement(quantity=100)
309
    self.assertInventoryEquals(100, section_uid=self.section.getUid(),
310
                                        omit_simulation=1)
311

312
  def test_SectionCategory(self):
313 314 315
    """Tests inventory on section category. """
    self.section.setGroup('level1/level2')
    self._makeMovement(quantity=100)
316 317 318
    self.assertInventoryEquals(100, section_category='group/level1')
    self.assertInventoryEquals(100, section_category='group/level1/level2')
    self.assertInventoryEquals(0, section_category='group/anotherlevel')
319 320
    
    # section category can be a list
321
    self.assertInventoryEquals(100,
322
            section_category=['group/anotherlevel', 'group/level1'])
323 324 325

    # strict_section_category only takes movement where section is strict
    # member of the category.
326
    self.assertInventoryEquals(0,
327
                section_category_strict_membership=['group/level1'])
328 329
    self.section.setGroup('level1')
    self.tic()
330
    self.assertInventoryEquals(100,
331
                section_category_strict_membership=['group/level1'])
332 333 334 335
    
    # non existing values to section_category are not silently ignored, but
    # raises an exception
    self.assertRaises(ValueError,
336
                      self.getInventory,
337 338
                      section_category='group/notexists')

339
  def test_MirrorSectionCategory(self):
340 341 342
    """Tests inventory on mirror section category. """
    self.mirror_section.setGroup('level1/level2')
    self._makeMovement(quantity=100)
343 344 345
    self.assertInventoryEquals(100, mirror_section_category='group/level1')
    self.assertInventoryEquals(100, mirror_section_category='group/level1/level2')
    self.assertInventoryEquals(0, mirror_section_category='group/anotherlevel')
346

347
    # section category can be a list
348
    self.assertInventoryEquals(100,
349
              mirror_section_category=['group/anotherlevel', 'group/level1'])
350 351 352

    # strict_section_category only takes movement where section is strict
    # member of the category.
353
    self.assertInventoryEquals(0,
354
              mirror_section_category_strict_membership=['group/level1'])
355 356
    self.mirror_section.setGroup('level1')
    self.tic()
357
    self.assertInventoryEquals(100,
358
              mirror_section_category_strict_membership=['group/level1'])
359 360 361 362
    
    # non existing values to section_category are not silently ignored, but
    # raises an exception
    self.assertRaises(ValueError,
363
                      self.getInventory,
364 365
                      mirror_section_category='group/notexists')

366
  def test_NodeCategory(self):
367 368
    """Tests inventory on node_category """
    self.node.setGroup('level1/level2')
369 370
    self._makeMovement(quantity=100, source_value=None)

371 372 373
    self.assertInventoryEquals(100, node_category='group/level1')
    self.assertInventoryEquals(100, node_category='group/level1/level2')
    self.assertInventoryEquals(0, node_category_strict_membership=['group/level1'])
374 375
    self.node.setGroup('level1')
    self.tic()
376
    self.assertInventoryEquals(100,
377
                            node_category_strict_membership=['group/level1'])
378
  
379 380
  def test_Function(self):
    """Tests inventory on function"""
381 382
    self._makeMovement(quantity=100, destination_function='function/function1')

383 384
    self.assertInventoryEquals(100, function='function/function1')
    self.assertInventoryEquals(0, function='function/function1/function2')
385 386 387 388

  def test_FunctionUid(self):
    """Tests inventory on function uid"""
    function = self.portal.portal_categories.function
389 390
    self._makeMovement(quantity=100, destination_function='function/function1')

391 392
    self.assertInventoryEquals(100, function_uid=function.function1.getUid())
    self.assertInventoryEquals(0,
393
                            function_uid=function.function1.function2.getUid())
394 395 396 397 398

  def test_FunctionCategory(self):
    """Tests inventory on function category"""
    self._makeMovement(quantity=100,
                       destination_function='function/function1/function2')
399 400
    self.assertInventoryEquals(100, function_category='function/function1')
    self.assertInventoryEquals(100, function='function/function1/function2')
401 402 403 404 405

  def test_FunctionCategoryStrictMembership(self):
    """Tests inventory on function category strict membership"""
    self._makeMovement(quantity=100,
                       destination_function='function/function1/function2')
406
    self.assertInventoryEquals(0,
407
            function_category_strict_membership='function/function1')
408
    self.assertInventoryEquals(100,
409
            function_category_strict_membership='function/function1/function2')
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

  def test_Funding(self):
    """Tests inventory on funding"""
    self._makeMovement(quantity=30, destination_funding='function/function1')
    self._makeMovement(quantity=-70, source_funding='function/function1')

    self.assertInventoryEquals(100, funding='function/function1')
    self.assertInventoryEquals(0, funding='function/function1/function2')

  def test_FundingUid(self):
    """Tests inventory on funding uid"""
    function = self.portal.portal_categories.function
    self._makeMovement(quantity=100, destination_funding='function/function1')

    self.assertInventoryEquals(100, funding_uid=function.function1.getUid())
    self.assertInventoryEquals(0,
                            funding_uid=function.function1.function2.getUid())

  def test_FundingCategory(self):
    """Tests inventory on funding category"""
    self._makeMovement(quantity=100,
                       destination_funding='function/function1/function2')
    self.assertInventoryEquals(100, funding_category='function/function1')
    self.assertInventoryEquals(100, funding='function/function1/function2')

  def test_FundingCategoryStrictMembership(self):
    """Tests inventory on funding category strict membership"""
    self._makeMovement(quantity=100,
                       destination_funding='function/function1/function2')
    self.assertInventoryEquals(0,
            funding_category_strict_membership='function/function1')
    self.assertInventoryEquals(100,
            funding_category_strict_membership='function/function1/function2')

444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  def test_PaymentRequest(self):
    """Tests inventory on payment_request"""
    self._makeMovement(quantity=30, destination_payment_request='function/function1')
    self._makeMovement(quantity=-70, source_payment_request='function/function1')

    self.assertInventoryEquals(100, payment_request='function/function1')
    self.assertInventoryEquals(0, payment_request='function/function1/function2')

  def test_PaymentRequestUid(self):
    """Tests inventory on payment_request uid"""
    function = self.portal.portal_categories.function
    self._makeMovement(quantity=100, destination_payment_request='function/function1')

    self.assertInventoryEquals(100, payment_request_uid=function.function1.getUid())
    self.assertInventoryEquals(0,
                            payment_request_uid=function.function1.function2.getUid())

  def test_PaymentRequestCategory(self):
    """Tests inventory on payment_request category"""
    self._makeMovement(quantity=100,
                       destination_payment_request='function/function1/function2')
    self.assertInventoryEquals(100, payment_request_category='function/function1')
    self.assertInventoryEquals(100, payment_request='function/function1/function2')

  def test_PaymentRequestCategoryStrictMembership(self):
    """Tests inventory on payment_request category strict membership"""
    self._makeMovement(quantity=100,
                       destination_payment_request='function/function1/function2')
    self.assertInventoryEquals(0,
            payment_request_category_strict_membership='function/function1')
    self.assertInventoryEquals(100,
            payment_request_category_strict_membership='function/function1/function2')

477 478
  def test_Project(self):
    """Tests inventory on project"""
479 480 481
    self._makeMovement(quantity=100, destination_project_value=self.project)
    self._makeMovement(quantity=100, source_project_value=self.other_project)

482 483
    self.assertInventoryEquals(100, project=self.project.getRelativeUrl())
    self.assertInventoryEquals(-100, project=self.other_project.getRelativeUrl())
484 485 486

  def test_ProjectUid(self):
    """Tests inventory on project uid"""
487 488 489
    self._makeMovement(quantity=100, destination_project_value=self.project)
    self._makeMovement(quantity=100, source_project_value=self.other_project)

490 491
    self.assertInventoryEquals(100, project_uid=self.project.getUid())
    self.assertInventoryEquals(-100, project_uid=self.other_project.getUid())
492 493 494 495

  def test_ProjectCategory(self):
    """Tests inventory on project category"""
    # this test uses unrealistic data
496
    self.project.setSource('group/level1/level2')
497 498
    self._makeMovement(quantity=100, destination_project_value=self.project)

499 500
    self.assertInventoryEquals(100, project_category='group/level1')
    self.assertInventoryEquals(100, project_category='group/level1/level2')
501 502 503 504

  def test_ProjectCategoryStrictMembership(self):
    """Tests inventory on project category strict membership"""
    # this test uses unrealistic data
505
    self.project.setSource('group/level1/level2')
506 507
    self._makeMovement(quantity=100, destination_project_value=self.project)

508
    self.assertInventoryEquals(0,
509
                    project_category_strict_membership='group/level1')
510
    self.assertInventoryEquals(100,
511
                    project_category_strict_membership='group/level1/level2')
512 513


514
  def test_ResourceCategory(self):
515 516
    """Tests inventory on resource_category """
    self.resource.setProductLine('level1/level2')
517 518
    self._makeMovement(quantity=100, source_value=None)

519 520 521
    self.assertInventoryEquals(100, resource_category='product_line/level1')
    self.assertInventoryEquals(100, resource_category='product_line/level1/level2')
    self.assertInventoryEquals(0,
522
                resource_category_strict_membership=['product_line/level1'])
523 524
    self.resource.setProductLine('level1')
    self.tic()
525
    self.assertInventoryEquals(100,
526
                resource_category_strict_membership=['product_line/level1'])
527

528
  def test_PaymentCategory(self):
529 530 531 532 533 534 535
    """Tests inventory on payment_category """
    # for now, BankAccount have a product_line category, so we can use this for
    # our category membership tests.
    self.payment_node.setProductLine('level1/level2')
    self._makeMovement(quantity=100,
                       destination_payment_value=self.payment_node,
                       source_value=None)
536

537 538 539
    self.assertInventoryEquals(100, payment_category='product_line/level1')
    self.assertInventoryEquals(100, payment_category='product_line/level1/level2')
    self.assertInventoryEquals(0,
540
                payment_category_strict_membership=['product_line/level1'])
541 542
    self.payment_node.setProductLine('level1')
    self.tic()
543
    self.assertInventoryEquals(100,
544
              payment_category_strict_membership=['product_line/level1'])
545

546 547
  def test_OwnershipInventoryByNode(self):
    """Tests ownership inventory by node. """
548 549
    self.assertInventoryEquals(0, node_uid=self.node.getUid())
    self.assertInventoryEquals(0, node_uid=self.other_node.getUid())
550 551 552 553 554
    # transfer quantity=100 from node to other_node.
    self._makeMovement(quantity=100,
                       source_value=self.node,
                       destination_value=self.other_node)
    self.tic()
555

556 557 558 559
    self.assertInventoryEquals(-100, node_uid=self.node.getUid())
    self.assertInventoryEquals(100, node_uid=self.other_node.getUid())
    self.assertInventoryEquals(100, mirror_node_uid=self.node.getUid())
    self.assertInventoryEquals(-100, mirror_node_uid=self.other_node.getUid())
560 561 562

  def test_OwnershipInventoryBySection(self):
    """Tests ownership inventory by section. """
563 564
    self.assertInventoryEquals(0, section_uid=self.section.getUid())
    self.assertInventoryEquals(0, section_uid=self.other_section.getUid())
565 566 567 568 569
    # transfer quantity=100 from section to other_section.
    self._makeMovement(quantity=100,
                       source_section_value=self.section,
                       destination_section_value=self.other_section)
    self.tic()
570

571 572 573 574
    self.assertInventoryEquals(-100, section_uid=self.section.getUid())
    self.assertInventoryEquals(100, section_uid=self.other_section.getUid())
    self.assertInventoryEquals(100, mirror_section_uid=self.section.getUid())
    self.assertInventoryEquals(-100,
575
                            mirror_section_uid=self.other_section.getUid())
576

577
  def test_SimulationState(self):
578 579 580 581 582 583
    """Tests inventory on simulation state. """
    self.payment_node.setProductLine('level1/level2')
    self._makeMovement(quantity=100,
                       simulation_state='confirmed',
                       source_value=None)

584 585 586 587
    self.assertInventoryEquals(100)
    self.assertInventoryEquals(100, simulation_state='confirmed')
    self.assertInventoryEquals(0, simulation_state='planned')
    self.assertInventoryEquals(100, simulation_state=['planned', 'confirmed'])
588

589
  def test_MultipleNodes(self):
590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
    """Test section category with many nodes. """
    test_group = self.getCategoryTool().resolveCategory('group/test_group')
    self.assertNotEquals(len(test_group.objectValues()), 0)
    # we first create a section for each group category
    quantity_for_node = {}
    for category in test_group.getCategoryChildValueList():
      # we create a member node for each category
      node = self._makeOrganisation(group_value=category)
      # we create a movement to each node
      quantity = random.randint(100, 1000)
      self._makeMovement(quantity=quantity,
                         destination_section_value=node,
                         destination_value=node)
      # and record for later
      quantity_for_node[node] = quantity

    for category in test_group.getCategoryChildValueList():
      node_list = category.getGroupRelatedValueList(portal_type='Organisation')
      self.assertNotEquals(len(node_list), 0)

      # getInventory on node uid for all member of a category ...
      total_quantity = sum([quantity_for_node[node] for node in node_list])
612
      self.assertInventoryEquals(total_quantity,
613
                              node_uid=[node.getUid() for node in node_list])
614
      # ... is equivalent to node_category
615
      self.assertInventoryEquals(total_quantity,
616
                              node_category=category.getRelativeUrl())
617
  
Sebastien Robin's avatar
Sebastien Robin committed
618 619
  @expectedFailure
  def test_DoubleCategoryMembershipSectionCategory(self):
620 621 622 623 624 625 626
    """Tests inventory on section category, when the section is twice member\
    of the same category like it happens for group and mapping"""
    self.section.setGroup('level1/level2')
    self.section.setMapping('group/level1/level2')
    self._makeMovement(quantity=100)
    # We are twice member of the section_category, but the quantity should not
    # change.
627 628 629
    self.assertInventoryEquals(100, section_category='group/level1')
    self.assertInventoryEquals(100, section_category='group/level1/level2')
    self.assertInventoryEquals(100,
630
            section_category_strict_membership=['group/level1/level2'])
631

632
  def test_NoSection(self):
633 634 635 636
    """Tests inventory on section category / section uid, when the section is\
    empty."""
    self.section.setGroup('level1/level2')
    self._makeMovement(quantity=100, source_section_value=None)
637 638
    self.assertInventoryEquals(100, section_category='group/level1/level2')
    self.assertInventoryEquals(100,
639
            section_category_strict_membership=['group/level1/level2'])
640
    self.assertInventoryEquals(100, section_uid=self.section.getUid())
641
  
642 643 644 645
  def testPrecision(self):
    # getInventory supports a precision= argument to specify the precision to
    # round
    getInventoryAssetPrice = self.getSimulationTool().getInventoryAssetPrice
646 647
    self._makeMovement(quantity=0.1234, price=1)

648
    self.assertAlmostEquals(0.123,
649 650 651
                            self.getInventory(precision=3,
                                              node_uid=self.node.getUid()),
                            places=3)
652
    self.assertAlmostEquals(0.123,
653 654 655
                            getInventoryAssetPrice(precision=3,
                                                   node_uid=self.node.getUid()),
                            places=3)
656 657 658 659 660 661 662
  
  def testPrecisionAndFloatRoundingIssues(self):
    # sum([0.1] * 10) != 1.0 but this is not a problem here
    getInventoryAssetPrice = self.getSimulationTool().getInventoryAssetPrice
    self._makeMovement( quantity=1, price=1 )
    for i in range(10):
      self._makeMovement( quantity=-0.1, price=1 )
663
    self.assertInventoryEquals(0, precision=2, node_uid=self.node.getUid())
664 665 666
    self.assertEquals(0, getInventoryAssetPrice(precision=2,
                                                node_uid=self.node.getUid()))
    
667 668 669 670
  def test_OmitInputOmitOutput(self):
    self._makeMovement(quantity=1, price=1)
    self._makeMovement(quantity=-1, price=1)
    # omit input ignores movement comming to this node
671
    self.assertInventoryEquals(-1, node_uid=self.node.getUid(), omit_input=1)
672
    # omit output ignores movement going to this node
673
    self.assertInventoryEquals(1, node_uid=self.node.getUid(), omit_output=1)
674
    # omit_output & omit_input return nothing in that case
675
    self.assertInventoryEquals(0, node_uid=self.node.getUid(),
676
                            omit_input=1, omit_output=1)
677 678
    # this also work with movements without source or without destination
    self._makeMovement(quantity=-2, price=1, source_value=None)
679 680
    self.assertInventoryEquals(-3, node_uid=self.node.getUid(), omit_input=1)
    self.assertInventoryEquals(1, node_uid=self.node.getUid(), omit_output=1)
681 682
    # and with movements without source section / desination sections
    self._makeMovement(quantity=2, price=1, source_section_value=None)
683 684
    self.assertInventoryEquals(-3, node_uid=self.node.getUid(), omit_input=1)
    self.assertInventoryEquals(3, node_uid=self.node.getUid(), omit_output=1)
685 686 687 688 689
    
  def test_OmitInputOmitOutputWithDifferentSections(self):
    self._makeMovement(quantity=2, price=1)
    self._makeMovement(quantity=-3, price=1,
                       destination_section_value=self.other_section )
690
    self.assertInventoryEquals(0, node_uid=self.node.getUid(),
691 692
                            section_uid=self.section.getUid(),
                            omit_input=1)
693
    self.assertInventoryEquals(-3, node_uid=self.node.getUid(),
694 695
                            section_uid=self.other_section.getUid(),
                            omit_input=1)
696
    self.assertInventoryEquals(2, node_uid=self.node.getUid(),
697 698
                            section_uid=self.section.getUid(),
                            omit_output=1)
699
    self.assertInventoryEquals(0, node_uid=self.node.getUid(),
700 701
                            section_uid=self.other_section.getUid(),
                            omit_output=1)
702 703 704 705 706 707 708
    
  def test_OmitInputOmitOutputWithDifferentPayment(self):
    # simple case
    self._makeMovement(quantity=2, price=1,
                       destination_payment_value=self.payment_node )
    self._makeMovement(quantity=-3, price=1,
                       destination_payment_value=self.other_payment_node )
709
    self.assertInventoryEquals(0,
710 711 712 713
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid(),
                            payment_uid=self.payment_node.getUid(),
                            omit_input=1)
714
    self.assertInventoryEquals(-3,
715 716 717 718
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid(),
                            payment_uid=self.other_payment_node.getUid(),
                            omit_input=1)
719
    self.assertInventoryEquals(2,
720 721 722 723
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid(),
                            payment_uid=self.payment_node.getUid(),
                            omit_output=1)
724
    self.assertInventoryEquals(0,
725 726 727 728
                            node_uid=self.node.getUid(),
                            section_uid=self.other_section.getUid(),
                            payment_uid=self.other_payment_node.getUid(),
                            omit_output=1)
729

730 731 732
  def test_OmitInputOmitOutputCancellationAmount(self):
    self._makeMovement(quantity=-1, price=1, cancellation_amount=True)
    self._makeMovement(quantity=2, price=1, cancellation_amount=True)
733

734 735
    self.assertInventoryEquals(2, node_uid=self.node.getUid(), omit_input=1)
    self.assertInventoryEquals(-1, node_uid=self.node.getUid(), omit_output=1)
736
    # omit_output & omit_input return nothing in that case
737
    self.assertInventoryEquals(0, node_uid=self.node.getUid(),
738
                            omit_input=1, omit_output=1)
739
    
740 741 742 743 744 745 746 747
  def test_OmitInputOmitOutputWithDifferentPaymentSameNodeSameSection(self):
    self._makeMovement(quantity=2, price=1,
                       source_value=self.node,
                       destination_value=self.node,
                       source_section_value=self.section,
                       destination_section_value=self.section,
                       source_payment_value=self.other_payment_node,
                       destination_payment_value=self.payment_node )
748
    self.assertInventoryEquals(2,
749 750 751 752
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid(),
                            payment_uid=self.payment_node.getUid(),
                            omit_output=1)
753
    self.assertInventoryEquals(-2,
754 755 756 757
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid(),
                            payment_uid=self.other_payment_node.getUid(),
                            omit_input=1)
758

759 760 761 762 763 764 765 766 767
  def test_TimeZone(self):
    """
    Check that getInventory support DateTime parameter with 
    timezone
    """
    date_gmt_1 = DateTime('2005/12/01 GMT+9')
    date_gmt0 = DateTime('2005/12/01 GMT+10')
    date_gmt1 = DateTime('2005/12/01 GMT+11')
    self._makeMovement(quantity=1, start_date=date_gmt0)
768
    self.assertInventoryEquals(0,
769 770 771
                            node_uid=self.node.getUid(),
                            resource=self.resource.getRelativeUrl(),
                            at_date=date_gmt1)
772
    self.assertInventoryEquals(1,
773 774 775
                            node_uid=self.node.getUid(),
                            resource=self.resource.getRelativeUrl(),
                            at_date=date_gmt_1)
776

777 778 779
class TestInventoryList(InventoryAPITestCase):
  """Tests getInventoryList methods.
  """
780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
  def test_ReturnedTypeIsList(self):
    """Inventory List returns a sequence object""" 
    getInventoryList = self.getSimulationTool().getInventoryList
    inventory_list = getInventoryList()
    self.assertEquals(str(inventory_list.__class__),
                    'Shared.DC.ZRDB.Results.Results')
    # the brain is InventoryListBrain
    self.assert_('InventoryListBrain' in
          [c.__name__ for c in inventory_list._class.__bases__])
    # default is an empty list
    self.assertEquals(0, len(inventory_list))

  def test_GroupByNode(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=100)
    self._makeMovement(destination_value=self.other_node, quantity=100)
    self._makeMovement(destination_value=None, quantity=100)
    inventory_list = getInventoryList(group_by_node=1)
    self.assertEquals(3, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.node_relative_url ==
                  self.node.getRelativeUrl()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.node_relative_url ==
                  self.other_node.getRelativeUrl()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.node_relative_url ==
                  self.mirror_node.getRelativeUrl()][0].inventory, -300)

806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834
  def test_GroupByMirrorNode(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=100)
    self._makeMovement(source_value=self.other_node, quantity=100)
    self._makeMovement(source_value=None, quantity=100)
    inventory_list = getInventoryList(section_uid=self.section.getUid(),
                                      group_by_mirror_node=1)
    self.assertEquals(3, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.mirror_node_uid ==
                  self.mirror_node.getUid()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.mirror_node_uid ==
                  self.other_node.getUid()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list
                       if r.mirror_node_uid is None][0].inventory, 100)

  def test_GroupBySection(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=100)
    self._makeMovement(destination_section_value=self.other_node, quantity=100)
    self._makeMovement(destination_section_value=None, quantity=100)
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_section=1)
    self.assertEquals(3, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.section_relative_url ==
                  self.section.getRelativeUrl()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.section_relative_url ==
                  self.other_node.getRelativeUrl()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.section_relative_url is
                  None][0].inventory, 100)
835 836 837 838 839 840 841 842 843 844 845 846 847

  def test_GroupBySectionCategory(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self.section.setGroup('level1')
    self.other_section.setGroup('level1')
    m1 = self._makeMovement(quantity=2)
    m2 = self._makeMovement(destination_section_value=self.other_section, quantity=3)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      section_category='group/level1',
                                      group_by_section_category=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(3+2, inventory_list[0].inventory)
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869
    # section category is exported in the brain
    self.assertTrue(hasattr(inventory_list[0], 'section_category_uid'))
    self.assertEquals(self.portal.portal_categories.group.level1.getUid(),
                      inventory_list[0].section_category_uid)

  def test_GroupBySectionCategoryStrict(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self.section.setGroup('level1')
    self.other_section.setGroup('level1')
    m1 = self._makeMovement(quantity=2)
    m2 = self._makeMovement(destination_section_value=self.other_section, quantity=3)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      section_category='group/level1',
                                      group_by_section_category_strict_membership=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(3+2, inventory_list[0].inventory)
    # section category is exported in the brain
    self.assertTrue(hasattr(inventory_list[0],
      'section_category_strict_membership_uid'))
    self.assertEquals(self.portal.portal_categories.group.level1.getUid(),
                      inventory_list[0].section_category_strict_membership_uid)
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889

  def test_GroupByFunction(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    function1 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1')
    function2 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1/function2')
    self._makeMovement(quantity=2,
                       destination_function_value=function1,)
    self._makeMovement(quantity=3,
                       destination_function_value=function2,)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_function=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.function_uid ==
      function1.getUid()][0].inventory, 2)
    self.assertEquals([r for r in inventory_list if r.function_uid ==
      function2.getUid()][0].inventory, 3)

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908
  def test_GroupByFunding(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    funding1 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1')
    funding2 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1/function2')
    self._makeMovement(quantity=2,
                       destination_funding_value=funding1,)
    self._makeMovement(quantity=3,
                       destination_funding_value=funding2,)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_funding=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.funding_uid ==
      funding1.getUid()][0].inventory, 2)
    self.assertEquals([r for r in inventory_list if r.funding_uid ==
      funding2.getUid()][0].inventory, 3)

909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
  def test_GroupByPaymentRequest(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    payment_request1 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1')
    payment_request2 = self.portal.portal_categories.restrictedTraverse(
                                      'function/function1/function2')
    self._makeMovement(quantity=2,
                       destination_payment_request_value=payment_request1,)
    self._makeMovement(quantity=3,
                       destination_payment_request_value=payment_request2,)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_payment_request=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.payment_request_uid ==
      payment_request1.getUid()][0].inventory, 2)
    self.assertEquals([r for r in inventory_list if r.payment_request_uid ==
      payment_request2.getUid()][0].inventory, 3)

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942
  def test_GroupByProject(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=2,
                       destination_project_value=self.project,)
    self._makeMovement(quantity=3,
                       destination_project_value=self.other_project,)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_project=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.project_uid ==
      self.project.getUid()][0].inventory, 2)
    self.assertEquals([r for r in inventory_list if r.project_uid ==
      self.other_project.getUid()][0].inventory, 3)

943 944 945 946
  def test_GroupByResource(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=100)
    self._makeMovement(resource_value=self.other_resource, quantity=100)
947
    # group_by_resource is implicit when grouping by something ...
948
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
949
                                      group_by_node=1)
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.resource_relative_url ==
                  self.resource.getRelativeUrl()][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.resource_relative_url ==
                  self.other_resource.getRelativeUrl()][0].inventory, 100)
    # ... but can be disabled
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_node=1,
                                      group_by_resource=0)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(inventory_list[0].inventory, 200)

  def test_GroupByPayment(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=100)
    self._makeMovement(destination_payment_value=self.payment_node,
                       quantity=200)
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_node=1, group_by_payment=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list if r.payment_uid is
                      None][0].inventory, 100)
    self.assertEquals([r for r in inventory_list if r.payment_uid ==
                       self.payment_node.getUid()][0].inventory, 200)

975 976 977
  def test_GroupByDate(self):
    # group by date currently only groups by *exact* date
    getInventoryList = self.getSimulationTool().getInventoryList
978 979 980
    self._makeMovement(quantity=1, start_date=DateTime('2000/1/1 12:00 UTC'))
    self._makeMovement(quantity=1, start_date=DateTime('2000/1/1 12:00 UTC'))
    self._makeMovement(quantity=1, start_date=DateTime('2001/1/1 12:00 UTC'))
981 982 983 984 985 986 987 988
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      group_by_date=1)
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list
                        if r.date.year() == 2000][0].inventory, 2)
    self.assertEquals([r for r in inventory_list
                        if r.date.year() == 2001][0].inventory, 1)

Sebastien Robin's avatar
Sebastien Robin committed
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005
  def test_GroupByRelatedKey(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=2, use='use1')
    self._makeMovement(quantity=3, use='use1',
                       destination_value=self.other_node)
    self._makeMovement(quantity=7, use='use2')
    self._makeMovement(quantity=4, use='use2')
    # note that grouping by related key only make sense if you group by strict
    # memebership related keys
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by=('strict_use_uid', ))
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list
            if r.getObject().getUse() == 'use1'][0].inventory, 5)
    self.assertEquals([r for r in inventory_list
        if r.getObject().getUse() == 'use2'][0].inventory, 11)
1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
    
    # in such case, it's interesting to pass a select expression, to be have on
    # brain the information of which category is used
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by=('strict_use_uid', ),
                                      select_list=['strict_use_uid'])
    self.assertEquals(2, len(inventory_list))
    self.assertTrue(hasattr(inventory_list[0], 'strict_use_uid'))
    use = self.portal.portal_categories.use
    self.assertEquals([r for r in inventory_list
      if r.strict_use_uid == use.use1.getUid()][0].inventory, 5)
    self.assertEquals([r for r in inventory_list
      if r.strict_use_uid == use.use2.getUid()][0].inventory, 11)

Sebastien Robin's avatar
Sebastien Robin committed
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
    # group_by can also be passed as string
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by='strict_use_uid', )
    self.assertEquals(2, len(inventory_list))
    self.assertEquals([r for r in inventory_list
            if r.getObject().getUse() == 'use1'][0].inventory, 5)
    self.assertEquals([r for r in inventory_list
        if r.getObject().getUse() == 'use2'][0].inventory, 11)

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
    # if we group by "use_uid" instead of "strict_use_uid", then we'll have
    # summary lines.
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by=('use_uid', ),
                                      select_list=['use_uid'])
    self.assertEquals(3, len(inventory_list))
    self.assertTrue(hasattr(inventory_list[0], 'use_uid'))
    use = self.portal.portal_categories.use
    self.assertEquals([r for r in inventory_list
      if r.use_uid == use.use1.getUid()][0].inventory, 5)
    self.assertEquals([r for r in inventory_list
      if r.use_uid == use.use2.getUid()][0].inventory, 11)
    # the summary line
    self.assertEquals([r for r in inventory_list
      if r.use_uid == use.getUid()][0].inventory, 11+5)

Sebastien Robin's avatar
Sebastien Robin committed
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    # the name of a column can also be used, from stock or other tables
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by='node_uid', )
    self.assertEquals(2, len(inventory_list))
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by='title', )
    self.assertEquals(4, len(inventory_list))

    # group_by= can be mixed with group_by_* arguments
    inventory_list = getInventoryList(node_uid=(self.node.getUid(),
                                                self.other_node.getUid()),
                                      group_by_node=True,
                                      group_by=('strict_use_uid',))
    self.assertEquals(3, len(inventory_list))
    self.assertEquals([r for r in inventory_list
            if r.getObject().getUse() == 'use1'
            and r.node_uid == self.node.getUid()][0].inventory, 2)
    self.assertEquals([r for r in inventory_list
            if r.getObject().getUse() == 'use1'
            and r.node_uid == self.other_node.getUid()][0].inventory, 3)
    self.assertEquals([r for r in inventory_list
        if r.getObject().getUse() == 'use2'][0].inventory, 11)
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
  def test_OmitInputOmitOutput(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=1, price=1)
    self._makeMovement(quantity=-1, price=1)
    # omit input ignores movement comming to this node
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_input=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(-1, inventory_list[0].total_price)
    self.assertEquals(-1, inventory_list[0].total_quantity)

    # omit output ignores movement going to this node
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_output=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(1, inventory_list[0].total_price)
    self.assertEquals(1, inventory_list[0].total_quantity)

    # omit_output & omit_input return nothing in that case
    self.assertEquals(0, len(getInventoryList(node_uid=self.node.getUid(),
                                              omit_input=1,
                                              omit_output=1)))
    
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  def test_OmitAssetIncreaseDecrease(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    m1 = self._makeMovement(quantity=1, price=1)
    m2 = self._makeMovement(quantity=-1, price=1)
    # omit movements that increases the asset
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_asset_increase=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(-1, inventory_list[0].total_price)
    self.assertEquals(-1, inventory_list[0].total_quantity)

    # omit movements that decrease the asset
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_asset_decrease=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(1, inventory_list[0].total_price)
    self.assertEquals(1, inventory_list[0].total_quantity)

    # omit_asset_increase and omit_asset_decrease return nothing in that case
    self.assertEquals(0, len(getInventoryList(node_uid=self.node.getUid(),
                                              omit_asset_increase=1,
                                              omit_asset_decrease=1)))

    # so far, it works the same as omit_input & omit_output, but if we have
    # negative prices, we see the interest of such feature
    m1.setPrice(-1)
    self.assertEquals(-1, m1.getTotalPrice())
    m2.setPrice(-1)
    self.assertEquals(1, m2.getTotalPrice())

    self.tic()

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_asset_increase=1)
    self.assertEquals(1, len(inventory_list))
    # this is m1
    self.assertEquals(-1, inventory_list[0].total_price)
    self.assertEquals(1, inventory_list[0].total_quantity)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_asset_decrease=1)
    self.assertEquals(1, len(inventory_list))
    # this is m2
    self.assertEquals(1, inventory_list[0].total_price)
    self.assertEquals(-1, inventory_list[0].total_quantity)


1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  def test_OmitInputOmitOutputWithDifferentPaymentSameNodeSameSection(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=2, price=1,
                       source_value=self.node,
                       destination_value=self.node,
                       source_section_value=self.section,
                       destination_section_value=self.section,
                       source_payment_value=self.other_payment_node,
                       destination_payment_value=self.payment_node )
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      section_uid=self.section.getUid(),
                                      payment_uid=self.payment_node.getUid(),
                                      omit_output=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(2, inventory_list[0].total_price)
    self.assertEquals(2, inventory_list[0].total_quantity)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                section_uid=self.section.getUid(),
                                payment_uid=self.other_payment_node.getUid(),
                                omit_input=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(-2, inventory_list[0].total_price)
    self.assertEquals(-2, inventory_list[0].total_quantity)
1167

1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185
  def test_OmitInputOmitOutputCancellationAmount(self):
    getInventoryList = self.getSimulationTool().getInventoryList
    self._makeMovement(quantity=-1, price=1, cancellation_amount=True)
    self._makeMovement(quantity=2, price=1, cancellation_amount=True)

    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_input=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(2, inventory_list[0].total_price)
    self.assertEquals(2, inventory_list[0].total_quantity)

    # omit output ignores movement going to this node
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      omit_output=1)
    self.assertEquals(1, len(inventory_list))
    self.assertEquals(-1, inventory_list[0].total_price)
    self.assertEquals(-1, inventory_list[0].total_quantity)

1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
  def test_CurentAvailableFutureInventoryList(self):
    def makeMovement(simulation_state=None, quantity=None):
      self._makeMovement(quantity=quantity, price=1,
                         source_value=self.node,
                         destination_value=self.other_node,
                         #source_section_value=self.section,
                         #destination_section_value=self.other_section,
                         #source_payment_value=self.payment_node,
                         #destination_payment_value=self.other_payment_node,
                         simulation_state=simulation_state)
    def checkInventory(line=0, type='Current', destination=0, source=0, quantity=None):
      method = getattr(self.getSimulationTool(),'get%sInventoryList' % type)
      if source:
        node_uid = self.node.getUid()
      if destination:
        node_uid = self.other_node.getUid()
      inventory_list = method(node_uid=node_uid)
      self.assertEquals(len(inventory_list), line)
      if quantity is not None:
        self.assertEquals(sum([x.total_quantity for x in inventory_list]), 
                          quantity)
    makeMovement(quantity=1, simulation_state='ordered')
    checkInventory(line=0, type='Current', destination=1)
    checkInventory(line=0, type='Available', destination=1)
    checkInventory(line=1, type='Future', source=1, quantity=-1)
    checkInventory(line=1, type='Future', destination=1, quantity=1)
    makeMovement(quantity=3, simulation_state='confirmed')
    checkInventory(line=0, type='Current', source=1)
    checkInventory(line=0, type='Current', destination=1)
    checkInventory(line=1, type='Available', source=1, quantity=-3)
    checkInventory(line=0, type='Available', destination=1)
    checkInventory(line=2, type='Future', source=1, quantity=-4)
    checkInventory(line=2, type='Future', destination=1, quantity=4)
    makeMovement(quantity=5, simulation_state='started')
    checkInventory(line=1, type='Current', source=1, quantity=-5)
    checkInventory(line=0, type='Current', destination=1)
    checkInventory(line=2, type='Available', source=1, quantity=-8)
    checkInventory(line=0, type='Available', destination=1)
    checkInventory(line=3, type='Future', source=1, quantity=-9)
    checkInventory(line=3, type='Future', destination=1, quantity=9)
1226

Sebastien Robin's avatar
Sebastien Robin committed
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
  def test_inventory_asset_price(self):
    # examples from http://accountinginfo.com/study/inventory/inventory-120.htm
    movement_list = [
        (1,  "Beginning Inventory", -700, 10),
        (3,  "Purchase",            -100, 12),
        (8,  "Sale",                 500, None),
        (15, "Purchase",            -600, 14),
        (19, "Purchase",            -200, 15),
        (25, "Sale",                 400, None),
        (27, "Sale",                 100, None),
    ]
    resource = self.getProductModule().newContent(
                                  title='My resource',
                                  portal_type='Product')
    for m in movement_list:
      self._makeMovement(resource_value=resource,
                         source_value=self.node,
                         destination_value=self.mirror_node,
                         start_date=DateTime('2000/1/%d 12:00 UTC' % m[0]),
                         title=m[1],
                         quantity=m[2],
                         price=m[3],
                         )

    simulation_tool = self.getSimulationTool()
    def valuate(method):
      r = simulation_tool.getInventoryAssetPrice(
            valuation_method=method,
            resource_uid=resource.getUid(),
            node_uid=self.node.getUid())
      return round(r)


    self.assertEquals(7895, valuate("MovingAverage"))
    self.assertEquals(7200, valuate("Filo"))
    self.assertEquals(8600, valuate("Fifo"))

  def test_weighted_average_asset_price(self):
    def h(quantity, total_price):
      """
      A small helper. Returns a dictionary
      """
      d = dict(quantity=quantity,
               price=float(total_price)/quantity,
               total_price=total_price)
      return d
    # one item per month:
    #  - movement_list: quantity is negative, it's incoming/purchase
    #  - after: quantity, total_price, and expected unit_price
    # Data was extracted from existing ledger books
    data = {
      '2009/11':
        dict(movement_list=[h(566, 259208),], after=h(566, 259208),),
      '2009/12':
        dict(movement_list=[h(600, 291600), h(-1135, 536164), ],
          after=h(31, 14644)),
      '2010/01':
        dict(movement_list=[h(1200, 583200), ], after=h(1231, 597844)),
      '2010/02':
        dict(movement_list=[h(200, 97200), h(-1265, 614417), ],
          after=h(166, 80627)),
      '2010/03':
        dict(movement_list=[], after=h(166, 80627)),
      '2010/04':
        dict(movement_list=[h(600, 291600), h(-680, 330437), ],
          after=h(86, 41791)),
      '2010/05':
        dict(movement_list=[], after=h(86, 41791)),
      '2010/06':
        dict(movement_list=[], after=h(86, 41791)),
      '2010/07':
        dict(movement_list=[], after=h(86, 41791)),
      '2010/08':
        dict(movement_list=[h(4400, 2032800), h(-4364, 2018170), ],
          after=h(122, 56420)),
      '2010/09':
        dict(movement_list=[], after=h(122, 56420)),
      '2010/10':
        dict(movement_list=[], after=h(122, 56420)),
      '2010/11':
        dict(movement_list=[h(1400, 646800), h(-1357, 626984), h(4, 1848)],
          after=h(169, 78084)),
    }

    resource = self._makeProduct(title="Product for weighted average test")
    resource_uid = resource.getUid()

    # create all movements
    for month, value in data.iteritems():
      for mov in value['movement_list']:
        d = DateTime('%s/15 15:00 UTC' % month)
        self._makeMovement(start_date=d, resource_uid=resource_uid, **mov)

    # and check
    for cur in sorted(data)[1:]:
      # month+1
      to_date = DateTime("%s/1" % cur) + 31

      result = self.getSimulationTool().getInventoryAssetPrice(
                  valuation_method="MonthlyWeightedAverage",
                  to_date=to_date,
                  resource_uid=resource.getUid(),
                  node_uid=self.node.getUid())
      self.assertTrue(result is not None)
      self.assertEquals(data[cur]['after']['total_price'], round(result))
1332

1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
    # check internal data
    internal_data = {
      '2010/12':
        dict(movement_list=[h(103, 46350)], after=h(269, 124434)),
      '2011/01':
        dict(movement_list=[h(22, 8910)], after=h(291, 133344)),
     }
    for month, value in internal_data.iteritems():
      for mov in value['movement_list']:
        d = DateTime('%s/15 15:00 UTC' % month)
        self._makeMovement(is_internal=1, start_date=d, resource_uid=resource_uid, **mov)
    for cur in sorted(internal_data):
      to_date = DateTime("%s/1" % cur) + 31
      # check by section
      result = self.getSimulationTool().getInventoryAssetPrice(
                  valuation_method="MonthlyWeightedAverage",
                  to_date=to_date,
                  resource_uid=resource.getUid(),
                  section_uid=self.section.getUid())
      self.assertTrue(result is not None)
      self.assertEquals(internal_data[cur]['after']['total_price'], round(result))


1356 1357 1358
class TestMovementHistoryList(InventoryAPITestCase):
  """Tests Movement history list methods.
  """
1359 1360 1361 1362
  def testReturnedTypeIsList(self):
    """Movement History List returns a sequence object""" 
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt_history_list = getMovementHistoryList()
1363
    self.assertEquals(str(mvt_history_list.__class__),
1364 1365 1366 1367 1368
                    'Shared.DC.ZRDB.Results.Results')
    # default is an empty list
    self.assertEquals(0, len(mvt_history_list))
  
  def testMovementBothSides(self):
1369
    """Movement History List returns movement from both sides""" 
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100)
    # we don't filter, so we have the same movement from both sides.
    self.assertEquals(2, len(getMovementHistoryList()))

  def testBrainClass(self):
    """Movement History List uses InventoryListBrain for brains""" 
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100)
    # maybe this check is too low level (Shared/DC/ZRDB//Results.py, class r) 
    r_bases = getMovementHistoryList()._class.__bases__
    brain_class = r_bases[2].__name__
1382
    self.assertEquals('MovementHistoryListBrain', brain_class,
1383 1384
      "unexpected brain class for getMovementHistoryList InventoryListBrain"
      " != %s (bases %s)" % (brain_class, r_bases))
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

  def testBrainAttribute(self):
    """Test attributes exposed on brains."""
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100)
    brain = getMovementHistoryList()[0]
    self.assertTrue(hasattr(brain, 'node_uid'))
    self.assertTrue(hasattr(brain, 'resource_uid'))
    self.assertTrue(hasattr(brain, 'section_uid'))
    self.assertTrue(hasattr(brain, 'date'))
    self.assertTrue(hasattr(brain, 'function_uid'))
    self.assertTrue(hasattr(brain, 'payment_uid'))
    self.assertTrue(hasattr(brain, 'project_uid'))
    self.assertTrue(hasattr(brain, 'funding_uid'))
    self.assertTrue(hasattr(brain, 'mirror_node_uid'))
    self.assertTrue(hasattr(brain, 'mirror_section_uid'))

1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489
  def testSection(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement(quantity=100)
    mvt_history_list = getMovementHistoryList(
                            section_uid = self.section.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt.getUid(), mvt_history_list[0].uid)
    self.assertEquals(100, mvt_history_list[0].total_quantity)
    self.assertEquals(self.section.getRelativeUrl(),
                  mvt_history_list[0].section_relative_url)
  
  def testMirrorSection(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement(quantity=100)
    mvt_history_list = getMovementHistoryList(
                            mirror_section_uid = self.section.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt.getUid(), mvt_history_list[0].uid)
    self.assertEquals(-100, mvt_history_list[0].total_quantity)
    self.assertEquals(self.mirror_section.getRelativeUrl(),
                  mvt_history_list[0].section_relative_url)
    self.assertEquals(self.mirror_node.getRelativeUrl(),
                  mvt_history_list[0].node_relative_url)
    
    # if we look from the other side, everything is reverted
    mvt_history_list = getMovementHistoryList(
                            section_uid = self.section.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(100, mvt_history_list[0].total_quantity)
    self.assertEquals(self.section.getRelativeUrl(),
                  mvt_history_list[0].section_relative_url)
    self.assertEquals(self.node.getRelativeUrl(),
                  mvt_history_list[0].node_relative_url)
  
  def testDifferentDatesPerSection(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    start_date = DateTime(2001, 1, 1)
    stop_date = DateTime(2002, 2, 2)
    mvt = self._makeMovement(quantity=100,
                             start_date=start_date,
                             stop_date=stop_date)
    # start_date is for source
    self.assertEquals(start_date, getMovementHistoryList(
                            section_uid=self.mirror_section.getUid())[0].date)
    # stop_date is for destination
    self.assertEquals(stop_date, getMovementHistoryList(
                            section_uid=self.section.getUid())[0].date)
    
  def testNode(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement(quantity=100)
    mvt_history_list = getMovementHistoryList(
                            node_uid = self.node.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt.getUid(), mvt_history_list[0].uid)
    self.assertEquals(100, mvt_history_list[0].total_quantity)

  def testMirrorNode(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement(quantity=100)
    mvt_history_list = getMovementHistoryList(
                            mirror_node_uid = self.node.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt.getUid(), mvt_history_list[0].uid)
    self.assertEquals(-100, mvt_history_list[0].total_quantity)

  def testResource(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement(quantity=100)
    another_resource = self._makeResource()
    another_mvt = self._makeMovement(quantity=3,
                                     resource_value=another_resource)
    # we can query resource directly by uid
    mvt_history_list = getMovementHistoryList(
                            node_uid=self.node.getUid(),
                            resource_uid=self.resource.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(100, mvt_history_list[0].total_quantity)
    # getMovementHistoryList should return only movement for
    mvt_history_list = getMovementHistoryList(
                            node_uid=self.node.getUid(),
                            resource_uid=another_resource.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(3, mvt_history_list[0].total_quantity)

    # wrong value yields an empty list
    self.assertEquals(0, len(getMovementHistoryList(
                            resource_uid = self.node.getUid())))
1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501
  
  def testSectionCategory(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self.section.setGroup('level1/level2')
    mvt = self._makeMovement(quantity=100)

    # for section category, both exact category or any parent category works
    # section_category can also be a list.
    for section_category in [ 'group/level1',
                              'group/level1/level2',
                             ['group/level1', 'group/anotherlevel'],
                             ['group/level1', 'group/level1'],
Sebastien Robin's avatar
Sebastien Robin committed
1502
                             ]:
1503 1504 1505 1506
      movement_history_list = getMovementHistoryList(
                                section_category=section_category)
      self.assertEquals(len(movement_history_list), 1)
      self.assertEquals(movement_history_list[0].total_quantity, 100)
1507
    
1508 1509 1510 1511 1512 1513 1514 1515 1516
    # again, bad category raises an exception
    self.assertRaises(ValueError,
                      getMovementHistoryList,
                      section_category='group/notexists')
    # (but other arguments are ignored)
    self.assertEquals(len(getMovementHistoryList(
                        section_category='group/level1',
                        ignored='argument')), 1)
    
Sebastien Robin's avatar
Sebastien Robin committed
1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
  @expectedFailure
  def testDoubleSectionCategory(self):
    # it is currently invalid to pass the same category twice to inventory API
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self.section.setGroup('level1/level2')
    mvt = self._makeMovement(quantity=100)
    movement_history_list = getMovementHistoryList(
                              section_category=['group/level1',
                                                'group/level1/level2'])
    self.assertEquals(len(movement_history_list), 1)
    self.assertEquals(movement_history_list[0].total_quantity, 100)


1530 1531 1532 1533 1534 1535 1536 1537
  def testNodeCategoryAndSectionCategory(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self.section.setGroup('level1/level2')
    self.node.setGroup('level1')
    mvt = self._makeMovement(quantity=100)

    valid_category_list = [ 'group/level1',
                           ['group/level1', 'group/anotherlevel'],
Sebastien Robin's avatar
Sebastien Robin committed
1538
                           ['group/level1', 'group/level1'], ]
1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670
    invalid_category_list = ['group/anotherlevel', 'product_line/level1']

    # both valid
    for section_category in valid_category_list:
      for node_category in valid_category_list:
        movement_history_list = getMovementHistoryList(
                                  node_category=node_category,
                                  section_category=section_category)
        self.assertEquals(len(movement_history_list), 1)
        self.assertEquals(movement_history_list[0].total_quantity, 100)

    # if node category OR section category is not matched, no movement are
    # returned.
    for section_category in valid_category_list:
      for node_category in invalid_category_list:
        movement_history_list = getMovementHistoryList(
                                  node_category=node_category,
                                  section_category=section_category)
        self.assertEquals(len(movement_history_list), 0)

    for section_category in invalid_category_list:
      for node_category in valid_category_list:
        movement_history_list = getMovementHistoryList(
                                  node_category=node_category,
                                  section_category=section_category)
        self.assertEquals(len(movement_history_list), 0)


  # Date tests:
  # ===========
  #
  # For all date tests, we create a list of movements with dates:
  #     start_date (date for source)        stop_date(date for destination)
  #              2006/01/01                       2006/01/02
  #              2006/01/02                       2006/01/03
  #              2006/01/03                       2006/01/04
  #              2006/01/04                       2006/01/05
  # in all those tests, we usually look from the destination, so the first
  # movement is at 2006/01/02
  #

  def test_FromDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
      self._makeMovement(quantity=100,
                         start_date=date,
                         stop_date=date+1)
    # from_date takes all movements >= 
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 2)
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 02),
                        section_uid=self.mirror_section.getUid())), 2)

  def test_AtDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
      self._makeMovement(quantity=100,
                         start_date=date,
                         stop_date=date+1)
    # at_date takes all movements <=
    self.assertEquals(len(getMovementHistoryList(
                        at_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 2)
    self.assertEquals(len(getMovementHistoryList(
                        at_date=DateTime(2006, 01, 02),
                        section_uid=self.mirror_section.getUid())), 2)

  def test_ToDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
      self._makeMovement(quantity=100,
                         start_date=date,
                         stop_date=date+1)
    # to_date takes all movements <
    self.assertEquals(len(getMovementHistoryList(
                        to_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 1)
    self.assertEquals(len(getMovementHistoryList(
                        to_date=DateTime(2006, 01, 02),
                        section_uid=self.mirror_section.getUid())), 1)

  def test_FromDateAtDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
      self._makeMovement(quantity=100,
                         start_date=date,
                         stop_date=date+1)
    # both from_date and at_date
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 03),
                        at_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 1)
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 02),
                        at_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 2)
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2005, 01, 02),
                        at_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 2)
    # from other side
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 02),
                        at_date=DateTime(2006, 01, 03),
                        section_uid=self.mirror_section.getUid())), 2)

  def test_FromDateToDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    for date in [DateTime(2006, 01, day) for day in range(1, 4)]:
      self._makeMovement(quantity=100,
                         start_date=date,
                         stop_date=date+1)
    # both from_date and to_date
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 03),
                        to_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 0)
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 02),
                        to_date=DateTime(2006, 01, 03),
                        section_uid=self.section.getUid())), 1)
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2005, 01, 02),
                        to_date=DateTime(2007, 01, 02),
                        section_uid=self.section.getUid())), 3)
    # from other side
    self.assertEquals(len(getMovementHistoryList(
                        from_date=DateTime(2006, 01, 02),
                        to_date=DateTime(2006, 01, 03),
                        section_uid=self.mirror_section.getUid())), 1)
1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703
  

  def test_BrainDateTimeZone(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100,
                       start_date=DateTime('2001/02/03 04:05 GMT+3'))
    movement_history_list = getMovementHistoryList(
                                section_uid=self.section.getUid())
    self.assertEquals(len(movement_history_list), 1)
    brain = movement_history_list[0]
    self.assertEquals(DateTime('2001/02/03 04:05 GMT+3'), brain.date)
    self.assertEquals('GMT+3', brain.date.timezone())

  def test_BrainDateTimeZoneStopDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100,
                       start_date=DateTime('2001/02/03 04:05 GMT+2'),
                       stop_date=DateTime('2001/02/03 04:05 GMT+3'))
    movement_history_list = getMovementHistoryList(
                        mirror_section_uid=self.section.getUid())
    self.assertEquals(len(movement_history_list), 1)
    brain = movement_history_list[0]
    self.assertEquals(DateTime('2001/02/03 04:05 GMT+2'), brain.date)
    self.assertEquals('GMT+2', brain.date.timezone())

  def test_BrainEmptyDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=100,)
    movement_history_list = getMovementHistoryList(
                                section_uid=self.section.getUid())
    self.assertEquals(len(movement_history_list), 1)
    brain = movement_history_list[0]
    self.assertEquals(None, brain.date)
1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736

  def test_SortOnDate(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date_list = [DateTime(2006, 01, day) for day in range(1, 10)]
    reverse_date_list = date_list[:]
    reverse_date_list.reverse()

    # we create movements with a random order on dates, to have an extra change
    # that they are not sorted accidentally.
    random_date_list = date_list[:]
    random.shuffle(random_date_list)
    for date in random_date_list:
      self._makeMovement(quantity=100,
                         start_date=date - 1,
                         stop_date=date)
    
    movement_date_list = [ x.date for x in getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              sort_on=(('stock.date', 'ascending'),)) ]
    self.assertEquals(movement_date_list, date_list)
    movement_date_list = [ x.date for x in getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              sort_on=(('stock.date', 'descending'),)) ]
    self.assertEquals(movement_date_list, reverse_date_list)
    # minimum test for (('stock.date', 'ASC'), ('stock.uid', 'ASC')) which is
    # what you want to make sure that the last line on a page precedes the
    # first line on the previous page.
    movement_date_list = [x.date for x in getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              sort_on=(('stock.date', 'ascending'),
                                       ('stock.uid', 'ascending'),)) ]
    self.assertEquals(movement_date_list, date_list)

1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748
  def test_SortOnCatalogColumn(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=1, title='First')
    self._makeMovement(quantity=2, title='Second')
    
    self.assertEquals(['First', 'Second'], [ x.getObject().getTitle() for x in
          getMovementHistoryList(section_uid=self.section.getUid(),
                                 sort_on=(('title', 'ascending'),)) ])
    self.assertEquals(['Second', 'First'], [ x.getObject().getTitle() for x in
          getMovementHistoryList(section_uid=self.section.getUid(),
                                 sort_on=(('title', 'descending'),)) ])

1749
  def test_Limit(self):
1750
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
1751
    for q in range(6):
1752
      self._makeMovement(quantity=1)
1753 1754
    self.assertEquals(3, len(getMovementHistoryList(limit=3)))
    self.assertEquals(4, len(getMovementHistoryList(limit=(1, 4))))
1755
  
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771
  def test_SimulationState(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=2, simulation_state="confirmed")
    self._makeMovement(quantity=3, simulation_state="planned")
    for simulation_state in ['confirmed', ['confirmed', 'stopped']]:
      movement_history_list = getMovementHistoryList(
                                simulation_state=simulation_state,
                                section_uid=self.section.getUid())
      self.assertEquals(len(movement_history_list), 1)
      self.assertEquals(movement_history_list[0].total_quantity, 2)
    
    movement_history_list = getMovementHistoryList(
                              simulation_state=["confirmed", "planned"],
                              section_uid=self.section.getUid())
    self.assertEquals(len(movement_history_list), 2)

1772
  def test_SimulationMovement(self):
1773 1774 1775 1776 1777 1778 1779 1780 1781
    """Test simulation movement are listed in getMovementHistoryList
    """
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeSimulationMovement(quantity=100)
    self._makeMovement(quantity=100)
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid())
    self.assertEquals(2, len(movement_history_list))
  
1782
  def test_OmitSimulation(self):
1783 1784 1785 1786 1787 1788 1789 1790 1791 1792
    """Test omit_simulation argument to getMovementHistoryList.
    """
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeSimulationMovement(quantity=100)
    self._makeMovement(quantity=100)
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid(),
                                    omit_simulation=1)
    self.assertEquals(1, len(movement_history_list))
    self.assertEquals(100, movement_history_list[0].quantity)
1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811

  def test_OnlyAccountable(self):
    """Test that only_accountable works with getMovementHistoryList"""
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=2)
    self._makeMovement(quantity=3, is_accountable=False)
    # by default, only accountable movements are returned
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid(),)
    self.assertEquals(1, len(movement_history_list))
    self.assertEquals(2, movement_history_list[0].quantity)
    # unless only_accountable=False is passed
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid(),
                                    only_accountable=False)
    self.assertEquals(2, len(movement_history_list))
    self.assertEquals(sorted((2,3)), sorted(
      brain.quantity for brain in movement_history_list))

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876
  def test_RunningTotalQuantity(self):
    """Test that a running_total_quantity attribute is set on brains
    """
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
    for date, quantity in date_and_qty_list:
      self._makeMovement(stop_date=date, quantity=quantity)
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid(),
                                    sort_on=[('stock.date', 'asc'),
                                             ('stock.uid', 'asc')])
    running_total_quantity=0
    for idx, (date, quantity) in enumerate(date_and_qty_list):
      brain = movement_history_list[idx]
      running_total_quantity += quantity
      self.assertEquals(running_total_quantity, brain.running_total_quantity)
      self.assertEquals(date, brain.date)
      self.assertEquals(quantity, brain.quantity)
  
  def test_RunningTotalPrice(self):
    """Test that a running_total_price attribute is set on brains
    """
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date_and_price_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
    for date, price in date_and_price_list:
      self._makeMovement(stop_date=date, quantity=1, price=price)
    movement_history_list = getMovementHistoryList(
                                    section_uid=self.section.getUid(),
                                    sort_on=[('stock.date', 'asc'),
                                             ('stock.uid', 'asc')])
    running_total_price=0
    for idx, (date, price) in enumerate(date_and_price_list):
      brain = movement_history_list[idx]
      running_total_price += price
      self.assertEquals(running_total_price, brain.running_total_price)
      self.assertEquals(date, brain.date)
      self.assertEquals(price, brain.total_price)

  def test_RunningTotalWithInitialValue(self):
    """Test running_total_price and running_total_quantity with an initial
    value.
    """
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date_and_qty_list = [(DateTime(2006, 01, day), day) for day in range(1, 10)]
    for date, quantity in date_and_qty_list:
      self._makeMovement(stop_date=date, price=quantity, quantity=quantity)
    initial_running_total_price=100
    initial_running_total_quantity=-10
    movement_history_list = getMovementHistoryList(
                                    initial_running_total_quantity=
                                            initial_running_total_quantity,
                                    initial_running_total_price=
                                            initial_running_total_price,
                                    section_uid=self.section.getUid(),
                                    sort_on=[('stock.date', 'asc'),
                                             ('stock.uid', 'asc')])
    running_total_price=initial_running_total_price
    running_total_quantity=initial_running_total_quantity
    for idx, (date, quantity) in enumerate(date_and_qty_list):
      brain = movement_history_list[idx]
      self.assertEquals(date, brain.date)
      running_total_quantity += quantity
      self.assertEquals(running_total_quantity, brain.running_total_quantity)
      running_total_price += quantity * quantity # we've set price=quantity
      self.assertEquals(running_total_price, brain.running_total_price)
1877
  
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895
  def testRunningQuantityWithQuantity0(self):
    # a 0 quantity should not be a problem for running total price
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date = DateTime()
    quantity = -1
    for i in range(3):
      self._makeMovement( quantity=quantity+i, price=1, start_date=date+i )
    mvt_history_list = getMovementHistoryList(
                            node_uid=self.node.getUid(),
                            sort_on=[['stock.date', 'ASC']])
    self.assertEquals(3, len(mvt_history_list))
    self.assertEquals(-1, mvt_history_list[0].running_total_quantity)
    self.assertEquals(-1, mvt_history_list[0].running_total_price)
    self.assertEquals(-1, mvt_history_list[1].running_total_quantity)
    self.assertEquals(-1, mvt_history_list[1].running_total_price)
    self.assertEquals(0, mvt_history_list[2].running_total_quantity)
    self.assertEquals(0, mvt_history_list[2].running_total_price)

1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909
  # bug #352
  def testSameNodeDifferentDates(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date = DateTime()
    mvt = self._makeMovement( quantity=2,
                              start_date=date,
                              stop_date=date+1,
                              source_value=self.node,
                              destination_value=self.node )
    
    mvt_history_list = getMovementHistoryList(
                            node_uid=self.node.getUid(),)
    self.assertEquals(2, len(mvt_history_list))
    self.assertEquals(0, sum([r.total_quantity for r in mvt_history_list]))
1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920

  def testSameNodeSameDates(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement( quantity=2,
                              start_date=DateTime(),
                              source_value=self.node,
                              destination_value=self.node )
    mvt_history_list = getMovementHistoryList(
                            node_uid=self.node.getUid(),)
    self.assertEquals(2, len(mvt_history_list))
    self.assertEquals(0, sum([r.total_quantity for r in mvt_history_list]))
1921
 
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939
  def testSameNodeSameDatesSameSections(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    mvt = self._makeMovement( quantity=2,
                              start_date=DateTime(),
                              source_value=self.node,
                              destination_value=self.node,
                              source_section_value=self.section,
                              destination_section_value=self.section,)
    # For now, if you want to get movements from same node, same dates, same
    # sections, you have to pass ignore_group_by=True to ignore default
    # grouping.
    mvt_history_list = getMovementHistoryList(
                            ignore_group_by=True,
                            node_uid=self.node.getUid(),
                            section_uid=self.section.getUid())
    self.assertEquals(2, len(mvt_history_list))
    self.assertEquals(0, sum([r.total_quantity for r in mvt_history_list]))
 
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
  def testPrecision(self):
    # getMovementHistoryList supports a precision= argument to specify the
    # precision to round
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement( quantity=0.1234, price=1 )
    mvt_history_list = getMovementHistoryList(
                            precision=2,
                            node_uid=self.node.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(0.12, mvt_history_list[0].running_total_quantity)
    self.assertEquals(0.12, mvt_history_list[0].running_total_price)
    self.assertEquals(0.12, mvt_history_list[0].total_quantity)
    self.assertEquals(0.12, mvt_history_list[0].total_price)
    
    mvt_history_list = getMovementHistoryList(
                            precision=3,
                            node_uid=self.node.getUid())
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(0.123, mvt_history_list[0].running_total_quantity)
    self.assertEquals(0.123, mvt_history_list[0].running_total_price)
    self.assertEquals(0.123, mvt_history_list[0].total_quantity)
    self.assertEquals(0.123, mvt_history_list[0].total_price)

  def testPrecisionAndFloatRoundingIssues(self):
    # sum([0.1] * 10) != 1.0 but this is not a problem here
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    date = DateTime()
    self._makeMovement( quantity=1, price=1, start_date=date )
    for i in range(10):
      self._makeMovement( quantity=-0.1, price=1, start_date=date+i )
    mvt_history_list = getMovementHistoryList(
                            precision=2,
                            node_uid=self.node.getUid(),
                            sort_on=[['stock.date', 'ASC']])
    self.assertEquals(11, len(mvt_history_list))
    self.assertEquals(0, mvt_history_list[-1].running_total_quantity)
    self.assertEquals(0, mvt_history_list[-1].running_total_price)
1977

1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000
  def test_OmitInputOmitOutput(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=1, price=1)
    self._makeMovement(quantity=-1, price=1)
    # omit input ignores movement comming to this node
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_input=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(-1, mvt_history_list[0].total_price)
    self.assertEquals(-1, mvt_history_list[0].total_quantity)

    # omit output ignores movement going to this node
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_output=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(1, mvt_history_list[0].total_price)
    self.assertEquals(1, mvt_history_list[0].total_quantity)

    self.assertEquals(0, len(getMovementHistoryList(
                                              node_uid=self.node.getUid(),
                                              omit_input=1,
                                              omit_output=1)))
    
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
  def test_OmitAssetIncreaseDecrease(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    m1 = self._makeMovement(quantity=1, price=-1)
    m2 = self._makeMovement(quantity=-1, price=-1)
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_asset_increase=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(-1, mvt_history_list[0].total_price)
    self.assertEquals(1, mvt_history_list[0].total_quantity)

    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_asset_decrease=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(1, mvt_history_list[0].total_price)
    self.assertEquals(-1, mvt_history_list[0].total_quantity)

2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042
  def test_OmitInputOmitOutputWithDifferentPaymentSameNodeSameSection(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=2, price=1,
                       source_value=self.node,
                       destination_value=self.node,
                       source_section_value=self.section,
                       destination_section_value=self.section,
                       source_payment_value=self.other_payment_node,
                       destination_payment_value=self.payment_node )
    movement_history_list = getMovementHistoryList(
                                      node_uid=self.node.getUid(),
                                      section_uid=self.section.getUid(),
                                      payment_uid=self.payment_node.getUid(),
                                      omit_output=1)
    self.assertEquals(1, len(movement_history_list))
    self.assertEquals(2, movement_history_list[0].total_price)
    self.assertEquals(2, movement_history_list[0].total_quantity)

    movement_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                   section_uid=self.section.getUid(),
                                   payment_uid=self.other_payment_node.getUid(),
                                   omit_input=1)
    self.assertEquals(1, len(movement_history_list))
    self.assertEquals(-2, movement_history_list[0].total_price)
    self.assertEquals(-2, movement_history_list[0].total_quantity)

2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062
  def test_OmitInputOmitOutputCancellationAmount(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=-1, price=1, cancellation_amount=True)
    self._makeMovement(quantity=2, price=1, cancellation_amount=True)
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_input=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(2, mvt_history_list[0].total_price)
    self.assertEquals(2, mvt_history_list[0].total_quantity)

    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              omit_output=1)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(-1, mvt_history_list[0].total_price)
    self.assertEquals(-1, mvt_history_list[0].total_quantity)

    self.assertEquals(0, len(getMovementHistoryList(
                                              node_uid=self.node.getUid(),
                                              omit_input=1,
                                              omit_output=1)))
Sebastien Robin's avatar
Sebastien Robin committed
2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117

  def test_debit_credit(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=-1, price=2,
                       start_date=DateTime(2010, 1, 1))
    self._makeMovement(quantity=2, price=2,
                       start_date=DateTime(2010, 1, 2))
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              sort_on=(('stock.date', 'ASC'),))
    self.assertEquals(2, len(mvt_history_list))
    self.assertEquals(0, mvt_history_list[0].debit)
    self.assertEquals(1, mvt_history_list[0].credit)
    self.assertEquals(0, mvt_history_list[0].debit_price)
    self.assertEquals(2, mvt_history_list[0].credit_price)

    self.assertEquals(2, mvt_history_list[1].debit)
    self.assertEquals(0, mvt_history_list[1].credit)
    self.assertEquals(4, mvt_history_list[1].debit_price)
    self.assertEquals(0, mvt_history_list[1].credit_price)

  def test_debit_credit_cancellation_amount(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    self._makeMovement(quantity=-1, price=2, cancellation_amount=True,
                       start_date=DateTime(2010, 1, 1))
    self._makeMovement(quantity=2, price=2, cancellation_amount=True,
                       start_date=DateTime(2010, 1, 2))
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              sort_on=(('stock.date', 'ASC'),))
    self.assertEquals(2, len(mvt_history_list))
    self.assertEquals(-1, mvt_history_list[0].debit)
    self.assertEquals(0, mvt_history_list[0].credit)
    self.assertEquals(-2, mvt_history_list[0].debit_price)
    self.assertEquals(0, mvt_history_list[0].credit_price)

    self.assertEquals(0, mvt_history_list[1].debit)
    self.assertEquals(-2, mvt_history_list[1].credit)
    self.assertEquals(0, mvt_history_list[1].debit_price)
    self.assertEquals(-4, mvt_history_list[1].credit_price)

  def test_group_by_explanation(self):
    getMovementHistoryList = self.getSimulationTool().getMovementHistoryList
    delivery = self.folder.newContent(portal_type='Dummy Delivery',
                                      destination_section_value=self.section,
                                      source_section_value=self.mirror_section,
                                      destination_value=self.node,
                                      source_value=self.mirror_node,)
    m1 = delivery.newContent(portal_type='Dummy Movement', quantity=1,
                             price=3, resource_value=self.resource,
                             start_date=DateTime(2010, 1, 1))
    m2 = delivery.newContent(portal_type='Dummy Movement', quantity=1,
                             price=2, resource_value=self.resource,
                             start_date=DateTime(2010, 1, 1))
    m3 = delivery.newContent(portal_type='Dummy Movement', quantity=1,
                             price=7, resource_value=self.other_resource,
                             start_date=DateTime(2010, 1, 2))
2118
    self.commit();
Sebastien Robin's avatar
Sebastien Robin committed
2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153
    self.tic()
    # sanity check, our fake movements are all created in the same delivery,
    # and have a valid explanation uid
    self.assertEquals(m1.getExplanationUid(),
                      m2.getExplanationUid())
    self.assertTrue(m1.getExplanationUid())
    # also make sure they acquire from delivery
    self.assertEquals(self.node, m1.getDestinationValue())

    # group by explanation
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              group_by=('explanation_uid',), )
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(3, mvt_history_list[0].total_quantity)
    self.assertEquals(3, mvt_history_list[0].running_total_quantity)
    self.assertEquals(12, mvt_history_list[0].total_price)
    self.assertEquals(12, mvt_history_list[0].running_total_price)

    # group by explanation and resource
    mvt_history_list = getMovementHistoryList(node_uid=self.node.getUid(),
                                              group_by_resource=True,
                                              group_by=('explanation_uid',),
                                              sort_on=(('stock.date', 'ASC'),))
    self.assertEquals(2, len(mvt_history_list))

    self.assertEquals(2, mvt_history_list[0].total_quantity)
    self.assertEquals(2, mvt_history_list[0].running_total_quantity)
    self.assertEquals(5, mvt_history_list[0].total_price)
    self.assertEquals(5, mvt_history_list[0].running_total_price)

    self.assertEquals(1, mvt_history_list[1].total_quantity)
    self.assertEquals(3, mvt_history_list[1].running_total_quantity)
    self.assertEquals(7, mvt_history_list[1].total_price)
    self.assertEquals(12, mvt_history_list[1].running_total_price)

2154

2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172
class TestNextNegativeInventoryDate(InventoryAPITestCase):
  """Tests getInventory methods.
  """
  def testNode(self):
    getNextNegativeInventoryDate = self.getSimulationTool().getNextNegativeInventoryDate
    def makeMovement(start_date=None, quantity=None, change_way=0):
      if not change_way:
        source_value = self.node
        destination_value = self.other_node,
      else:
        source_value = self.other_node
        destination_value = self.node,
      self._makeMovement(quantity=quantity, price=1,
                         source_value=source_value,
                         destination_value=destination_value,
                         start_date=start_date,
                         simulation_state='planned')
    node_uid = self.node.getUid()
2173
    date = DateTime(DateTime().strftime('%Y/%m/%d'))
2174 2175 2176 2177
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), None)
    makeMovement(quantity=1, change_way=1, start_date=date)
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), None)
    makeMovement(quantity=3, change_way=0, start_date=date+2)
2178
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), date+2)
2179 2180
    makeMovement(quantity=5, change_way=1, start_date=date+1)
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), None)
2181
    makeMovement(quantity=7, change_way=0, start_date=date+5)
2182
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), date+5)
2183 2184
    makeMovement(quantity=7, change_way=1, start_date=date+4)
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), None)
2185
    makeMovement(quantity=7, change_way=0, start_date=date+3)
2186
    self.assertEquals(getNextNegativeInventoryDate(node_uid=node_uid), date+3)
2187

2188 2189 2190
class TestInventoryStat(InventoryAPITestCase):
  """Tests Inventory Stat methods.
  """
2191 2192 2193 2194 2195 2196 2197 2198
  def testStockUidQuantity(self):
    getInventoryStat = self.getSimulationTool().getInventoryStat
    def makeMovement(quantity=None):
      self._makeMovement(quantity=quantity, price=1,
                         source_value=self.other_node,
                         destination_value=self.node)
    node_uid = self.node.getUid()
    makeMovement(quantity=1)
2199
    # Test the number of movement for this particular node
2200 2201 2202 2203 2204 2205
    self.assertEquals(getInventoryStat(node_uid=node_uid)[0].stock_uid, 1)
    makeMovement(quantity=3)
    self.assertEquals(getInventoryStat(node_uid=node_uid)[0].stock_uid, 2)
    makeMovement(quantity=5)
    self.assertEquals(getInventoryStat(node_uid=node_uid)[0].stock_uid, 3)

2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253
class TestTrackingList(InventoryAPITestCase):
  """Tests Inventory Stat methods.
  """
  def testNodeUid(self):
    getTrackingList = self.getSimulationTool().getTrackingList
    start_date = DateTime()
    def makeMovement(aggregate=None):
      self._makeMovement(quantity=1, price=1,
                         aggregate_value=aggregate,
                         resource_value=self.resource,
                         start_date = start_date,
                         source_value=self.other_node,
                         destination_value=self.node)
    item_uid = self.item.getUid()
    other_item_uid = self.other_item.getUid()
    node_uid = self.node.getUid()
    self.assertEquals(len(getTrackingList(node_uid=node_uid, 
                             at_date=start_date)),0)
    makeMovement(aggregate=self.item)
    result = getTrackingList(node_uid=node_uid,at_date=start_date)
    self.assertEquals(len(result),1)
    self.failIfDifferentSet([x.uid for x in result], [item_uid])
    makeMovement(aggregate=self.other_item)
    result = getTrackingList(node_uid=node_uid,at_date=start_date)
    self.assertEquals(len(result),2)
    self.failIfDifferentSet([x.uid for x in result], [item_uid, other_item_uid])

  def testSeveralAggregateOnMovement(self):
    getTrackingList = self.getSimulationTool().getTrackingList
    start_date = DateTime()
    def makeMovement(aggregate_list=None):
      self._makeMovement(quantity=1, price=1,
                         aggregate_list=aggregate_list,
                         resource_value=self.resource,
                         start_date = start_date,
                         source_value=self.other_node,
                         destination_value=self.node)
    item_uid = self.item.getUid()
    other_item_uid = self.other_item.getUid()
    node_uid = self.node.getUid()
    self.assertEquals(len(getTrackingList(node_uid=node_uid, 
                             at_date=start_date)),0)
    makeMovement(aggregate_list=[self.item.getRelativeUrl(),
                                 self.other_item.getRelativeUrl()])
    result = getTrackingList(node_uid=node_uid,at_date=start_date)
    self.assertEquals(len(result),2)
    self.failIfDifferentSet([x.uid for x in result], [item_uid, other_item_uid])

2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270
  def testDates(self):
    """
      Test different dates parameters of getTrackingList.
    """
    getTrackingList = self.getSimulationTool().getTrackingList
    now = DateTime()
    node_1 = self._makeOrganisation(title='Node 1')
    node_2 = self._makeOrganisation(title='Node 2')
    date_0 = now - 4 # Before first movement
    date_1 = now - 3 # First movement
    date_2 = now - 2 # Between both movements
    date_3 = now - 1 # Second movement
    date_4 = now     # After last movement
    self._makeMovement(quantity=1, price=1,
                       aggregate_value=self.item,
                       resource_value=self.resource,
                       start_date=date_1,
2271
                       source_value=None,
2272 2273 2274 2275 2276
                       destination_value=node_1)
    self._makeMovement(quantity=1, price=1,
                       aggregate_value=self.item,
                       resource_value=self.resource,
                       start_date=date_3,
2277
                       source_value=node_1,
2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294
                       destination_value=node_2)
    node_1_uid = node_1.getUid()
    node_2_uid = node_2.getUid()
    date_location_dict = {
      date_0: {'at_date': None,       'to_date': None},
      date_1: {'at_date': node_1_uid, 'to_date': None},
      date_2: {'at_date': node_1_uid, 'to_date': node_1_uid},
      date_3: {'at_date': node_2_uid, 'to_date': node_1_uid},
      date_4: {'at_date': node_2_uid, 'to_date': node_2_uid}
    }
    node_uid_to_node_number = {
      node_1_uid: 1,
      node_2_uid: 2
    }
    for date, location_dict in date_location_dict.iteritems():
      for param_id, location_uid in location_dict.iteritems():
        param_dict = {param_id: date}
2295 2296
        uid_list = [x.node_uid for x in getTrackingList(
                            aggregate_uid=self.item.getUid(), **param_dict)]
2297 2298 2299 2300 2301 2302 2303 2304
        if location_uid is None:
          self.assertEqual(len(uid_list), 0)
        else:
          self.assertEqual(len(uid_list), 1)
          self.assertEqual(uid_list[0], location_uid,
                           '%s=now - %i, aggregate should be at node %i but is at node %i' % \
                           (param_id, now - date, node_uid_to_node_number[location_uid], node_uid_to_node_number[uid_list[0]]))

2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331
class TestInventoryDocument(InventoryAPITestCase):
  """ Test impact of creating full inventories of stock points on inventory
  lookup. This is an optimisation to regular inventory system to avoid
  reading all stock entries since a node/section/payment is used when
  gathering its amounts of resources.
  """
  def _createAutomaticInventoryAtDate(self, date, override_inventory=None,
                                      full_inventory=False):
    """
      getInventoryList is tested to work in another unit test.
      If full_inventory is false, only inventoriate the first resource
      found.
    """
    self.tic() # Tic so that grabbed inventory is up to date.
    getInventoryList = self.getSimulationTool().getInventoryList
    portal = self.getPortal()
    inventory_module = portal.getDefaultModule(portal_type='Inventory')
    inventory = inventory_module.newContent(portal_type='Inventory')
    inventory.edit(destination_value=self.node,
                   destination_section_value=self.section,
                   start_date=date,
                   full_inventory=full_inventory)
    inventory_list = getInventoryList(node_uid=self.node.getUid(),
                                      at_date=date,
                                      omit_output=1)
    if full_inventory:
      inventory_list = [inventory_list[0]]
Vincent Pelletier's avatar
Vincent Pelletier committed
2332
    # TODO: Define a second resource which will only be present in full
Leonardo Rochael Almeida's avatar
typos  
Leonardo Rochael Almeida committed
2333
    # inventories. This will allow testing getInventoryList.
2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344
    #else:
    #  inventory_list.append({'resource_relative_url': '','total_quantity': 50,'variation_text': ''})
    for inventory_line in inventory_list:
      line = inventory.newContent(portal_type='Inventory Line')
      if override_inventory is None:
        total_quantity = inventory_line['total_quantity']
      else:
        total_quantity = override_inventory
      line.edit(resource=inventory_line['resource_relative_url'],
                inventory=total_quantity,
                variation_text=inventory_line['variation_text'])
Leonardo Rochael Almeida's avatar
typos  
Leonardo Rochael Almeida committed
2345
      # TODO: pass more properties through from calculated inventory to
2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361
      # inventory lines if needed.
    inventory.deliver()
    return inventory
    
  def _populateInventoryModule(self):
    """
      Create 3 inventories:
         Type     Deviation  Date (see stepCreateInitialMovements)
       - partial  1000       
       - full     10000      
       - full     100000     
    """
    self.BASE_QUANTITY = BASE_QUANTITY = 1
    # TODO: It would be better to strip numbers below seconds instead of below
    # days.
    self.MAX_DATE = MAX_DATE = DateTime(DateTime().Date()) - 1
2362
    self.DUPLICATE_INVENTORY_DATE = MAX_DATE - 8 # Newest
2363 2364 2365 2366 2367 2368
    self.INVENTORY_DATE_3 = INVENTORY_DATE_3 = MAX_DATE - 10 # Newest
    self.INVENTORY_QUANTITY_3 = INVENTORY_QUANTITY_3 = 100000
    self.INVENTORY_DATE_2 = INVENTORY_DATE_2 = INVENTORY_DATE_3 - 10
    self.INVENTORY_QUANTITY_2 = INVENTORY_QUANTITY_2 = 10000
    self.INVENTORY_DATE_1 = INVENTORY_DATE_1 = INVENTORY_DATE_2 - 10 # Oldest
    self.INVENTORY_QUANTITY_1 = INVENTORY_QUANTITY_1 = 1000
2369 2370 2371 2372 2373 2374 2375 2376 2377 2378

    # "actual" quantities are the quantities which will end up in the stock
    # table.
    self.ACTUAL_INVENTORY_QUANTITY_1 = INVENTORY_QUANTITY_1 - \
      BASE_QUANTITY
    self.ACTUAL_INVENTORY_QUANTITY_2 = INVENTORY_QUANTITY_2 - \
      (self.INVENTORY_QUANTITY_1 + BASE_QUANTITY)
    self.ACTUAL_INVENTORY_QUANTITY_3 = INVENTORY_QUANTITY_3 - \
      (self.INVENTORY_QUANTITY_2 + BASE_QUANTITY)
    
2379
    self.movement_uid_list = movement_uid_list = []
2380
    # Initial movement of 1
2381
    movement = self._makeMovement(quantity=BASE_QUANTITY,
2382 2383
      start_date=INVENTORY_DATE_1 - 1,
      simulation_state='delivered')
2384
    movement_uid_list.append(movement.getUid())
2385
    # First (partial) inventory of 1 000
2386 2387
    partial_inventory = self._createAutomaticInventoryAtDate(
      date=INVENTORY_DATE_1, override_inventory=INVENTORY_QUANTITY_1)
2388
    # Second movement of 1
2389
    movement = self._makeMovement(quantity=BASE_QUANTITY,
2390 2391
      start_date=INVENTORY_DATE_2 - 1,
      simulation_state='delivered')
2392
    movement_uid_list.append(movement.getUid())
2393
    # Second (full) inventory of 10 000
2394 2395 2396
    self._createAutomaticInventoryAtDate(date=INVENTORY_DATE_2,
      override_inventory=INVENTORY_QUANTITY_2,
      full_inventory=True)
2397
    # Third movement of 1
2398
    movement = self._makeMovement(quantity=BASE_QUANTITY,
2399 2400
      start_date=INVENTORY_DATE_3 - 1,
      simulation_state='delivered')
2401
    movement_uid_list.append(movement.getUid())
2402
    # Third (full) inventory of 100 000
2403 2404 2405
    self._createAutomaticInventoryAtDate(date=INVENTORY_DATE_3,
      override_inventory=INVENTORY_QUANTITY_3,
      full_inventory=True)
2406
    # Fourth movement of 1
2407
    movement = self._makeMovement(quantity=BASE_QUANTITY,
2408 2409
      start_date=INVENTORY_DATE_3 + 1,
      simulation_state='delivered')
2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496
    movement_uid_list.append(movement.getUid())
    self.tic()
    manage_test = self.getPortal().erp5_sql_transactionless_connection.manage_test
    def executeSQL(query):
      manage_test("BEGIN\x00%s\x00COMMIT" % (query, ))
      
    # Make stock table inconsistent with inventory_stock to make sure
    # inventory_stock is actually tested.
    executeSQL("UPDATE stock SET quantity=quantity*2 WHERE uid IN (%s)" %
               (', '.join([str(x) for x in movement_uid_list]), ))
    self.BASE_QUANTITY *= 2
    # Make inventory_stock table inconsistent with stock to make sure
    # inventory_stock is actually not used when checking that partial
    # inventory is not taken into account.
    executeSQL("UPDATE inventory_stock SET quantity=quantity*2 WHERE "\
               "uid IN (%s)" % (', '.join([str(x.getUid()) for x in \
                                           partial_inventory.objectValues()]),
                               ))

  def afterSetUp(self):
    InventoryAPITestCase.afterSetUp(self)
    self._populateInventoryModule()
    simulation_tool = self.getSimulationTool()
    self.getInventory = simulation_tool.getInventory
    self.getInventoryList = simulation_tool.getInventoryList
    self.node_uid = self.node.getUid()

  def _doesInventoryLineMatch(self, criterion_dict, inventory_line):
    """
      True: all values from criterion_dict match given inventory_line.
      False otherwise.
    """
    for criterion_id, criterion_value in criterion_dict.iteritems():
      if criterion_id not in inventory_line \
         or criterion_value != inventory_line[criterion_id]:
        return False
    return True

  def _checkInventoryList(self, inventory_list, criterion_dict_list,
                          ordered_check=False):
    """
      Check that:
        - inventory_list matches length of criterion_dict_list
        - inventory_list contains criterions mentionned in
          criterion_dict_list, line per line.

      If ordered_check is true, chek that lines match in the order they are
      provided.

      Warning: If a criterion can match multiple line, the first encountered
      line is accepted and will not be available for other checks. Sort
      inventory & criterions prior to checking if there is no other way - but
      it's most probable that your test is wrong if such case happens.

      Given inventory must have usable methods:
        __contains__ : to know if a column is present in the inventory
        __getitem__  : to get the value of an inventory column
    """
    if getattr(inventory_list, 'dictionaries', None) is not None:
      inventory_list = inventory_list.dictionaries()
    else:
      inventory_list = inventory_list[:] # That list is modified in this method
    for criterion_dict in criterion_dict_list:
      success = False
      for inventory_position in xrange(len(inventory_list)):
        if self._doesInventoryLineMatch(criterion_dict,
                                        inventory_list[inventory_position]):
          del inventory_list[inventory_position]
          success = True
          break
        if ordered_check:
          # We only reach this test if first line of inventory_list didn't
          # match current criterion_dict, which means lines at same initial
          # position do not match.
          break
      # Avoid rendering assertion error messages when no error happened.
      # This is because error messages might causes errors to be thrown if
      # they are rendered in cases where no assertion error would happen...
      # Leads to rasing exception instead of calling self.assert[...] method.
      if not success:
        if ordered_check:
          raise AssertionError, 'Line %r do not match %r' % \
                                (inventory_list[inventory_position],
                                 criterion_dict)
        else:
          raise AssertionError, 'No line in %r match %r' % \
                                (inventory_list, criterion_dict)
2497 2498
    # Check all expected lines have been found.
    self.assertFalse(inventory_list)
2499

2500
  def assertInventoryEquals(self, value, inventory_kw):
2501 2502 2503 2504 2505 2506 2507 2508 2509
    """
      Check that optimised getInventory call is equal to given value
      and that unoptimised call is *not* equal to thi value.
    """
    self.assertEquals(value, self.getInventory(**inventory_kw))
    self.assertNotEquals(value,
                         self.getInventory(optimisation__=False,
                                           **inventory_kw))

2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593
  def setUpDefaultInventoryCalculationList(self):
    createZODBPythonScript(self.portal.portal_skins.custom,
                           'Inventory_getDefaultInventoryCalculationList', '',
'''return ({
'inventory_params':{
 'section_uid':context.getDestinationSectionUid(),
 'node_uid':context.getDestinationUid(),
 'group_by_variation':1,
 'group_by_resource':1},
'list_method':'getMovementList',
'first_level':({'key':'resource_relative_url',
                'getter':'getResource',
                'setter':('appendToCategoryList', 'resource')},
               {'key':'variation_text',
                'getter':'getVariationText',
                'setter':'splitAndExtendToCategoryList'},
               ),
},)
''')
    self.commit()

  def clearAllInventoryAndSetUpTwoInventory(self):
    self.portal.inventory_module.manage_delObjects(list(self.portal.inventory_module.objectIds()))
    self.folder.manage_delObjects(list(self.folder.objectIds()))
    self.resource.setProductLine('level1/level2')
    self.other_resource.setProductLine('anotherlevel')
    self.section.setGroup('level1/level2')
    self.other_section.setGroup('anotherlevel')
    self.node.setRegion('level1')
    self.other_node.setGroup('anotherlevel')
    full_inventory = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory.edit(destination_section_value=self.section,
                        destination_value=self.node,
                        full_inventory=1,
                        start_date=DateTime('2012/05/18 00:00:00 GMT+9'))
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.resource)
    line.setQuantity(1)
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.other_resource)
    line.setQuantity(10)
    full_inventory.deliver()

    full_inventory = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory.edit(destination_section_value=self.other_section,
                        destination_value=self.node,
                        full_inventory=1,
                        start_date=DateTime('2012/05/18 00:00:00 GMT+9'))
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.resource)
    line.setQuantity(100)
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.other_resource)
    line.setQuantity(1000)
    full_inventory.deliver()

    full_inventory = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory.edit(destination_section_value=self.section,
                        destination_value=self.other_node,
                        full_inventory=1,
                        start_date=DateTime('2012/05/18 00:00:00 GMT+9'))
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.resource)
    line.setQuantity(10000)
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.other_resource)
    line.setQuantity(100000)
    full_inventory.deliver()
    full_inventory = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory.edit(destination_section_value=self.other_section,
                        destination_value=self.other_node,
                        full_inventory=1,
                        start_date=DateTime('2012/05/18 00:00:00 GMT+9'))
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.resource)
    line.setQuantity(1000000)
    line = full_inventory.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.other_resource)
    line.setQuantity(10000000)
    full_inventory.deliver()

    self.commit()
    self.tic()

2594 2595
  def test_01_CurrentInventoryWithFullInventory(self):
    """
2596 2597
      Check that inventory optimisation is executed when querying current
      amount (there is a usable full inventory which is the latest).
2598
    """
2599
    self.assertInventoryEquals(value=self.INVENTORY_QUANTITY_3 + \
2600 2601 2602 2603 2604
                                  self.BASE_QUANTITY,
                            inventory_kw={'node_uid': self.node_uid})

  def test_02_InventoryAtLatestFullInventoryDate(self):
    """
2605 2606
      Check that inventory optimisation is executed when querying an amount
      at the exact time of latest usable full inventory.
2607
    """
2608
    self.assertInventoryEquals(value=self.INVENTORY_QUANTITY_3,
2609 2610 2611 2612 2613
                            inventory_kw={'node_uid': self.node_uid,
                                          'at_date': self.INVENTORY_DATE_3})

  def test_03_InventoryAtEarlierFullInventoryDate(self):
    """
2614 2615
      Check that inventory optimisation is executed when querying past
      amount (there is a usable full inventory which is not the latest).
2616
    """
2617
    self.assertInventoryEquals(value=self.INVENTORY_QUANTITY_2 + \
2618 2619 2620 2621 2622 2623 2624
                                  self.BASE_QUANTITY,
                            inventory_kw={'node_uid': self.node_uid,
                                          'at_date': self.INVENTORY_DATE_3 - \
                                                     1})

  def test_04_InventoryBeforeFullInventoryAfterPartialInventory(self):
    """
2625 2626
      Check that optimisation is not executed when querying past amount
      with no usable full inventory.
2627

2628 2629 2630
      If optimisation was executed,
        self.INVENTORY_QUANTITY_1 * 2 + self.BASE_QUANTITY * 2
      would be found.
2631
    """
2632 2633
    self.assertEquals(self.ACTUAL_INVENTORY_QUANTITY_1 + \
                      self.BASE_QUANTITY * 2,
2634 2635 2636 2637 2638
                      self.getInventory(node_uid=self.node_uid,
                                   at_date=self.INVENTORY_DATE_2 - 1))

  def test_05_InventoryListWithFullInventory(self):
    """
2639 2640
      Check that inventory optimisation is executed when querying current
      amount list (there is a usable full inventory which is the latest).
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695
    """
    inventory = self.getInventoryList(node_uid=self.node_uid)
    reference_inventory = [
      {'date': self.INVENTORY_DATE_3,
       'inventory': self.INVENTORY_QUANTITY_3,
       'node_uid': self.node_uid},
      {'date': self.INVENTORY_DATE_3 + 1,
       'inventory': self.BASE_QUANTITY,
       'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_06_InventoryListAtLatestFullInventoryDate(self):
    """
      Check that inventory optimisation is executed when querying past
      amount list (there is a usable full inventory which is not the latest).
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      at_date=self.INVENTORY_DATE_3)
    reference_inventory = [
      {'date': self.INVENTORY_DATE_3,
       'inventory': self.INVENTORY_QUANTITY_3,
       'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_07_InventoryListAtEarlierFullInventoryDate(self):
    """
      Check that inventory optimisation is executed when querying past
      amount list (there is a usable full inventory which is not the latest).
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      at_date=self.INVENTORY_DATE_3 - 1)
    reference_inventory = [
      {'date': self.INVENTORY_DATE_2,
       'inventory': self.INVENTORY_QUANTITY_2,
       'node_uid': self.node_uid},
      {'date': self.INVENTORY_DATE_3 - 1,
       'inventory': self.BASE_QUANTITY,
       'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_08_InventoryListBeforeFullInventoryAfterPartialInventory(self):
    """
      Check that optimisation is not executed when querying past amount list
      with no usable full inventory.
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      at_date=self.INVENTORY_DATE_2 - 1)
    reference_inventory = [
      {'date': self.INVENTORY_DATE_1 - 1,
       'inventory': self.BASE_QUANTITY,
       'node_uid': self.node_uid},
      {'date': self.INVENTORY_DATE_1,
2696
       'inventory': self.ACTUAL_INVENTORY_QUANTITY_1,
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734
       'node_uid': self.node_uid},
      {'date': self.INVENTORY_DATE_2 - 1,
       'inventory': self.BASE_QUANTITY,
       'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_09_InventoryListGroupedByResource(self):
    """
      Group inventory list by resource explicitely, used inventory is the
      latest.
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      group_by_resource=1)
    reference_inventory = [
    {'inventory': self.INVENTORY_QUANTITY_3 + self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_10_InventoryListGroupedByResourceBeforeLatestFullInventoryDate(self):
    """
      Group inventory list by resource explicitely, used inventory is not the
      latest.
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      group_by_resource=1,
                                      at_date=self.INVENTORY_DATE_3 - 1)
    reference_inventory = [
    {'inventory': self.INVENTORY_QUANTITY_2 + self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_11_InventoryListAroundLatestInventoryDate(self):
    """
Vincent Pelletier's avatar
Vincent Pelletier committed
2735
      Test getInventoryList with a min and a max date around latest full
2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
      inventory. A full inventory is used and is not the latest.
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      from_date=self.INVENTORY_DATE_3 - 1,
                                      at_date=self.INVENTORY_DATE_3 + 1)
    reference_inventory = [
    {'inventory': self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3 - 1},
2746
    {'inventory': self.ACTUAL_INVENTORY_QUANTITY_3,
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3},
    {'inventory': self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3 + 1}
    ]
    self._checkInventoryList(inventory, reference_inventory)

  def test_12_InventoryListWithOrderByDate(self):
    """
      Test order_by is preserved by optimisation on date column.
      Also sort on total_quantity column because there are inventory lines
      which are on the same date but with distinct quantities.
    """
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      from_date=self.INVENTORY_DATE_3 - 1,
                                      at_date=self.INVENTORY_DATE_3 + 1,
                                      sort_on=(('date', 'ASC'),
                                               ('total_quantity', 'DESC')))
    reference_inventory = [
    {'inventory': self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3 - 1},
2773
    {'inventory': self.ACTUAL_INVENTORY_QUANTITY_3,
2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3},
    {'inventory': self.BASE_QUANTITY,
     'resource_uid': self.resource.getUid(),
     'node_uid': self.node_uid,
     'date': self.INVENTORY_DATE_3 + 1}
    ]
    self._checkInventoryList(inventory, reference_inventory,
                             ordered_check=True)
    inventory = self.getInventoryList(node_uid=self.node_uid,
                                      from_date=self.INVENTORY_DATE_3 - 1,
                                      at_date=self.INVENTORY_DATE_3 + 1,
                                      sort_on=(('date', 'DESC'),
                                               ('total_quantity', 'ASC')))
    reference_inventory.reverse()
    self._checkInventoryList(inventory, reference_inventory,
                             ordered_check=True)
2792

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814
  def test_13_InventoryAfterModificationInPast(self):
    """
    Test inventory after adding a new movement in past and reindex all inventory
    """
    movement = self._makeMovement(quantity=self.BASE_QUANTITY*2,
      start_date=self.INVENTORY_DATE_3 - 2,
      simulation_state='delivered')
    # reindex inventory module, although we modified table by hand
    # everything must be consistent after reindexation
    inventory_module = self.getPortal().getDefaultModule(portal_type='Inventory')
    inventory_module.recursiveReindexObject()
    self.tic()
    inventory_kw={'node_uid': self.node_uid,
                  'at_date': self.INVENTORY_DATE_3}
    value=self.INVENTORY_QUANTITY_3
    # use optimisation
    self.assertEquals(value, self.getInventory(**inventory_kw))
    # without optimisation
    self.assertEquals(value,
                      self.getInventory(optimisation__=False,
                                        **inventory_kw))

2815 2816 2817 2818 2819 2820 2821 2822
  def test_14_TwoInventoryWithSameDateAndResourceAndNode(self):
    """
    It makes no sense to validate two inventories with same date,
    same resource, and same node. The calculation of inventories
    will not work in such case. So here we test that a constraint
    does not allow such things
    """
    portal = self.getPortal()
2823
    self._addPropertySheet('Inventory', 'InventoryConstraint')
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
    try:
      inventory_module = portal.getDefaultModule(portal_type='Inventory')
      inventory = inventory_module.newContent(portal_type='Inventory')
      date = self.DUPLICATE_INVENTORY_DATE
      inventory.edit(destination_value=self.node,
                     destination_section_value=self.section,
                     start_date=date)
      inventory_line = inventory.newContent(
          resource_value = self.resource,
          quantity = 1)
      self.workflow_tool = portal.portal_workflow
      workflow_id = 'inventory_workflow'
      transition_id = 'deliver_action'
      workflow_id= 'inventory_workflow'
      self.workflow_tool.doActionFor(inventory, transition_id,
              wf_id=workflow_id)
      self.assertEquals('delivered', inventory.getSimulationState())
      self.tic()
      
      # We should detect the previous inventory and fails
      new_inventory = inventory.Base_createCloneDocument(batch_mode=1)
      self.assertRaises(ValidationFailed, self.workflow_tool.doActionFor, 
          new_inventory, transition_id, wf_id=workflow_id)
      workflow_history = self.workflow_tool.getInfoFor(ob=new_inventory, 
          name='history', wf_id=workflow_id)
      workflow_error_message = str(workflow_history[-1]['error_message'])
2850 2851 2852
      self.assertTrue(len(workflow_error_message))
      self.assertTrue(len([x for x in workflow_error_message \
          if x.find('There is already an inventory')]))
2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868

      # Add a case in order to check a bug when the other inventory at the
      # same date does not change stock values
      new_inventory = inventory.Base_createCloneDocument(batch_mode=1)
      new_inventory.setStartDate(self.DUPLICATE_INVENTORY_DATE + 1)
      self.workflow_tool.doActionFor(new_inventory, transition_id,
              wf_id=workflow_id)
      self.assertEquals('delivered', new_inventory.getSimulationState())
      self.tic()

      new_inventory = new_inventory.Base_createCloneDocument(batch_mode=1)
      self.assertRaises(ValidationFailed, self.workflow_tool.doActionFor, 
          new_inventory, transition_id, wf_id=workflow_id)
      workflow_history = self.workflow_tool.getInfoFor(ob=new_inventory, 
          name='history', wf_id=workflow_id)
      workflow_error_message = str(workflow_history[-1]['error_message'])
2869 2870 2871
      self.assertTrue(len(workflow_error_message))
      self.assertTrue(len([x for x in workflow_error_message \
          if x.find('There is already an inventory')]))
2872
    finally:
2873
      # remove all property sheets we added to type informations
2874
      ttool = self.getTypesTool()
2875 2876 2877 2878 2879
      for ti_name, psheet_list in self._added_property_sheets.iteritems():
        ti = ttool.getTypeInfo(ti_name)
        property_sheet_set = set(ti.getTypePropertySheetList())
        property_sheet_set.difference_update(psheet_list)
        ti._setTypePropertySheetList(list(property_sheet_set))
2880
      self.commit()
2881
      _aq_reset()
2882

2883 2884 2885 2886 2887 2888 2889 2890
  def test_15_InventoryAfterModificationInFuture(self):
    """
    Test inventory after adding a new movement in future 
    """
    movement = self._makeMovement(quantity=self.BASE_QUANTITY*2,
      start_date=self.INVENTORY_DATE_3 + 2,
      simulation_state='delivered')
    self.tic()
2891 2892 2893 2894 2895

    def getCurrentInventoryPathList(resource, **kw):
      # the brain is not a zsqlbrain instance here, so it does not
      # have getPath().
      return [x.path for x in resource.getCurrentInventoryList(**kw)]
2896
    
2897
    # use optimisation
2898 2899 2900
    self.assertEquals(True,movement.getPath() in 
                  [x.path for x in self.resource.getInventoryList(
                                         mirror_uid=self.mirror_node.getUid())])
2901

2902
    # without optimisation
2903 2904 2905 2906
    self.assertEquals(True,movement.getPath() in 
                  [x.path for x in self.resource.getInventoryList(
                                         optimisation__=False,
                                         mirror_uid=self.mirror_node.getUid())])
2907

2908
  @expectedFailure
2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
  def test_MultipleSectionAndFullInventory(self):
    """Make sure that getInventoryList works in the situation which
    two sections use the same node and one section has full inventory for
    the node.
    """
    # In this test we do not need doucments made by afterSetUp.
    self.portal.inventory_module.manage_delObjects(list(self.portal.inventory_module.objectIds()))
    self.folder.manage_delObjects(list(self.folder.objectIds()))

    self.commit()
    self.tic()

    createZODBPythonScript(self.portal.portal_skins.custom,
                           'Inventory_getDefaultInventoryCalculationList', '',
'''return ({
'inventory_params':{
 'section_uid':context.getDestinationSectionUid(),
 'node_uid':context.getDestinationUid(),
 'group_by_variation':1,
 'group_by_resource':1},
'list_method':'getMovementList',
'first_level':({'key':'resource_relative_url',
                'getter':'getResource',
                'setter':('appendToCategoryList', 'resource')},
               {'key':'variation_text',
                'getter':'getVariationText',
                'setter':'splitAndExtendToCategoryList'},
               ),
},)
''')

    self.commit()

    getCurrentInventoryList = self.getSimulationTool().getCurrentInventoryList

    # Add movements for section
    self._makeMovement(source_section_value=None,
                       source_value=None,
                       destination_section_value=self.section,
                       destination_value=self.node,
                       start_date=DateTime('2012/07/18 00:00:00 GMT+9'),
                       simulation_state='delivered',
                       resource_value=self.resource,
                       quantity=1)
    self._makeMovement(source_section_value=None,
                       source_value=None,
                       destination_section_value=self.section,
                       destination_value=self.node,
                       start_date=DateTime('2012/07/21 00:00:00 GMT+9'),
                       simulation_state='delivered',
                       resource_value=self.resource,
                       quantity=2)

    # Add movemnets for other section
    self._makeMovement(source_section_value=None,
                       source_value=None,
                       destination_section_value=self.other_section,
                       destination_value=self.node,
                       start_date=DateTime('2012/07/19 00:00:00 GMT+9'),
                       simulation_state='delivered',
                       resource_value=self.resource,
                       quantity=3)
    self._makeMovement(source_section_value=None,
                       source_value=None,
                       destination_section_value=self.other_section,
                       destination_value=self.node,
                       start_date=DateTime('2012/07/20 00:00:00 GMT+9'),
                       simulation_state='delivered',
                       resource_value=self.resource,
                       quantity=4)

    self.commit()
    self.tic()

    # Check inventory
    result = {}
    for brain in getCurrentInventoryList(node_uid=self.node.getUid(),
                                         group_by_resource=1,
                                         group_by_node=1,
                                         group_by_section=1):
      key = (brain.section_uid, brain.node_uid, brain.resource_uid)
      if not key in result:
        result[key] = 0
      result[key] = result[key] + brain.inventory

    self.assertEqual(result,
                     {(self.section.getUid(), self.node.getUid(), self.resource.getUid()):3,
                      (self.other_section.getUid(), self.node.getUid(), self.resource.getUid()):7})

    # Add full inventory for section, not for other section
    full_inventory1 = self.portal.inventory_module.newContent(portal_type='Inventory')
    full_inventory1.edit(destination_section_value=self.section,
                         destination_value=self.node,
                         full_inventory=1,
                         start_date=DateTime('2012/07/20 00:00:00 GMT+9'))
    line = full_inventory1.newContent(portal_type='Inventory Line')
    line.setResourceValue(self.resource)
    line.setQuantity(100)
    full_inventory1.deliver()

    self.commit()
    self.tic()

    # Check inventory again. This time, full inventory should change
    # section's inventory. It should not change other section's inventory.
    result = {}
    for brain in getCurrentInventoryList(node_uid=self.node.getUid(),
                                         group_by_resource=1,
                                         group_by_node=1,
                                         group_by_section=1):
      key = (brain.section_uid, brain.node_uid, brain.resource_uid)
      if not key in result:
        result[key] = 0
      result[key] = result[key] + brain.inventory

    self.assertEqual(result,
                     {(self.section.getUid(), self.node.getUid(), self.resource.getUid()):102,
                      (self.other_section.getUid(), self.node.getUid(), self.resource.getUid()):7})

  @expectedFailure
3029 3030
  def test_ResourceCategory(self):
    """Make sure that resource category works when full inventory exists."""
3031
    # In this test we do not need doucments made by afterSetUp.
3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
    self.setUpDefaultInventoryCalculationList()
    self.clearAllInventoryAndSetUpTwoInventory()
    self.assertEquals(1,
                      self.getInventory(section_uid=self.section.getUid(),
                                        node_uid=self.node.getUid(),
                                        resource_category='product_line/level1',
                                        optimisation__=False))
    self.assertEquals(1,
                      self.getInventory(section_uid=self.section.getUid(),
                                        node_uid=self.node.getUid(),
                                        resource_category='product_line/level1',
                                        optimisation__=True))
3044

3045
  @expectedFailure
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
  def test_SectionCategory(self):
    """Make sure that section category works when full inventory exists."""
    # In this test we do not need doucments made by afterSetUp.
    self.clearAllInventoryAndSetUpTwoInventory()
    self.assertEquals(11,
                      self.getInventory(node_uid=self.node.getUid(),
                                        section_category='group/level1/level2',
                                        optimisation__=False))
    self.assertEquals(11,
                      self.getInventory(node_uid=self.node.getUid(),
                                        section_category='group/level1/level2',
                                        optimisation__=True))
3058

3059
  @expectedFailure
3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070
  def test_NodeCategory(self):
    # In this test we do not need doucments made by afterSetUp.
    self.clearAllInventoryAndSetUpTwoInventory()
    self.assertEquals(11,
                      self.getInventory(section_uid=self.section.getUid(),
                                        node_category='region/level1',
                                        optimisation__=False))
    self.assertEquals(11,
                      self.getInventory(section_uid=self.section.getUid(),
                                        node_category='region/level1',
                                        optimisation__=True))
Sebastien Robin's avatar
Sebastien Robin committed
3071

3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086
class BaseTestUnitConversion(InventoryAPITestCase):
  QUANTITY_UNIT_DICT = {}
  METRIC_TYPE_CATEGORY_LIST = ()

  def setUpUnitDefinition(self):

    unit_module = self.portal.quantity_unit_conversion_module
    for base, t in self.QUANTITY_UNIT_DICT.iteritems():
      standard, definition_dict = t

      group = unit_module._getOb(base, None)
      if group is None:
        group = unit_module.newContent(
                 id=base,
                 portal_type='Quantity Unit Conversion Group',
3087
                 quantity_unit="%s/%s" % (base, standard),)
3088 3089
      if group.getValidationState() in ('draft', 'invalidated'):
        group.validate()
3090 3091

      for unit, amount in definition_dict.iteritems():
3092 3093 3094 3095 3096 3097
        definition = group._getOb(unit, None)
        if definition is None:
          definition = group.newContent(
                        id=unit,
                        portal_type="Quantity Unit Conversion Definition",
                        quantity_unit="%s/%s" % (base, unit),
3098
                        quantity=amount,)
3099 3100
        if definition.getValidationState() in ('draft', 'invalidated'):
          definition.validate()
3101 3102 3103 3104 3105

  def afterSetUp(self):
    InventoryAPITestCase.afterSetUp(self)

    self.setUpUnitDefinition()
Julien Muchembled's avatar
Julien Muchembled committed
3106
    self.tic()
3107

3108
  @reindex
3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130
  def makeMovement(self, quantity, resource, *variation, **kw):
    m = self._makeMovement(quantity=quantity, resource_value=resource,
      source_value=self.node, destination_value=self.mirror_node, **kw)
    if variation:
      m.setVariationCategoryList(variation)

  def convertedSimulation(self, metric_type, **kw):
    return self.getSimulationTool().getInventory(
      metric_type=metric_type, node_uid=self.node.getUid(),
      **kw)

  def getNeededCategoryList(self):
    category_list = ['metric_type/' + c for c in self.METRIC_TYPE_CATEGORY_LIST]
    for base, t in self.QUANTITY_UNIT_DICT.iteritems():
      standard, definition_dict = t

      quantity = 'quantity_unit/%s/' % base
      category_list.append(quantity + standard)
      category_list.extend(quantity + unit for unit in definition_dict)
    category_list += InventoryAPITestCase.getNeededCategoryList(self)
    return category_list

3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
  def beforeTearDown(self):
    # invalidating definitions is enough
    unit_module = self.portal.quantity_unit_conversion_module
    for obj in unit_module.objectValues():
      if obj.getValidationState() == "validated":
        obj.invalidate()

    super(BaseTestUnitConversion, self).beforeTearDown()


3141 3142 3143 3144 3145 3146
class TestUnitConversion(BaseTestUnitConversion):
  QUANTITY_UNIT_DICT = {
    # base: (reference, dict_of_others)
    'unit':   ('unit', dict(a_few=None)),
    'length': ('m',    {'in': .0254}),
    'mass':   ('kg',   dict(t=1000, g=.001)),
3147
  }
3148
  METRIC_TYPE_CATEGORY_LIST = (
3149 3150 3151 3152
    'unit',
    'unit/0',
    'unit/1',
    'unit/2',
3153
    'unit/lot',
3154 3155 3156 3157 3158
    'mass/net',
    'mass/nutr/lipid',
  )

  def afterSetUp(self):
3159
    BaseTestUnitConversion.afterSetUp(self)
3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195

    self.resource.setQuantityUnitList(('unit/unit', 'length/in'))
    self.other_resource.setQuantityUnit('mass/g')

    keys = ('metric_type', 'quantity_unit', 'quantity', 'default_metric_type')
    for resource, measure_list in {
        self.resource: (
          ('mass/net',        'mass/kg', .123, None),
          ('mass/nutr/lipid', 'mass/g',  45,   True),
        ),
        self.other_resource: (
          # default measure (only useful to set the metric type)
          ('mass/net', None,        1,    True),
          # Bad measures
          ('unit',    'unit/unit',  123,  None), ## duplicate
          ('unit',    'unit/unit',  123,  None), #
          ('unit/0',  'unit/a_few', 123,  None), ## incomplete
          ('unit/1',  'unit/unit',  None, None), #
          ('unit/2',  None,         123,  None), #
          (None,      'mass/kg',    123,  None), #
          (None,      None,         None, None), ## empty
        )}.iteritems():
      for measure in measure_list:
        kw = dict((keys[i], v) for i, v in enumerate(measure) if v is not None)
        resource.newContent(portal_type='Measure', **kw)

    self.resource.setOptionalVariationBaseCategory('industrial_phase')
    self.resource.setVariationBaseCategoryList(('colour', 'size'))
    self.resource.setVariationCategoryList(self.VARIATION_CATEGORIES)
    m = self.resource.getDefaultMeasure('mass/t')

    m.setMeasureVariationBaseCategory('colour')
    for colour, quantity in ('green', 43), ('red', 56):
      m.newContent(portal_type='Measure Cell', quantity=quantity) \
       ._setMembershipCriterionCategory('colour/' + colour)

Julien Muchembled's avatar
Julien Muchembled committed
3196
    self.tic()
3197 3198

  def testConvertedInventoryList(self):
3199 3200 3201
    self.makeMovement(2, self.resource, 'colour/green', 'size/big')
    self.makeMovement(789, self.other_resource)
    self.makeMovement(-13, self.resource, 'colour/red', 'size/small',
3202 3203 3204 3205
                 'industrial_phase/phase1', 'industrial_phase/phase2')


    for i in range(3):
3206
      self.assertEquals(None, self.convertedSimulation('unit/%i' % i))
3207

3208 3209 3210 3211
    self.assertEquals(None,
                      self.convertedSimulation('unit',
                                               simulation_period='Current'))
    self.assertEquals(11, self.convertedSimulation('unit'))
3212

3213
    self.assertEquals(11 * .123 - .789, self.convertedSimulation('mass/net'))
3214
    self.assertEquals((11 * 123 - 789) / 1e6,
3215 3216 3217 3218 3219
                      self.convertedSimulation('mass/net',
                                               quantity_unit='mass/t'))

    self.assertEquals(13 * .056 - 2 * .043,
                      self.convertedSimulation('mass/nutr/lipid'))
3220

3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
    def testInventoryNoMetricType(self):
      """
      providing only the quantity_unit argument should also work,
      and the standard metric type is used
      """
      self.assertEquals((11 * 123 - 789) / 1e6,
                        self.getSimulationTool().getInventory(
                           node_uid=self.node.getUid(),
                           quantity_unit="mass/t"))

3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263
class TestUnitConversionDefinition(BaseTestUnitConversion):
  QUANTITY_UNIT_DICT = {
    # base: (reference, dict_of_others)
    'unit':   ('unit', dict(lot=1000, pack=6)),
  }
  METRIC_TYPE_CATEGORY_LIST = (
    'unit',
  )

  def afterSetUp(self):
    BaseTestUnitConversion.afterSetUp(self)

    # Aliases for readability
    self.resource_bylot = self.resource
    self.resource_bylot_overriding = self.other_resource

    # And a third resource
    self.resource_byunit = self.getProductModule().newContent(
                                  title='Resource counted By Unit',
                                  portal_type='Product')

    self.resource_bypack = self.getProductModule().newContent(
                                  title='Resource counted By Pack',
                                  portal_type='Product')

    self.resource_bylot.setQuantityUnit('unit/lot')
    self.resource_bypack.setQuantityUnit('unit/pack')
    self.resource_bylot_overriding.setQuantityUnit('unit/lot')
    self.resource_byunit.setQuantityUnit('unit/unit')


    base_unit = self.resource_bylot_overriding.newContent(
                  portal_type='Quantity Unit Conversion Group',
3264
                  quantity_unit='unit/unit',)
3265
    base_unit.validate()
3266 3267 3268 3269 3270


    unit = base_unit.newContent(
            portal_type='Quantity Unit Conversion Definition',
            quantity_unit='unit/lot',
3271 3272
            inverse=True,
            quantity=1.0/50,)
3273
    unit.validate()
3274

Julien Muchembled's avatar
Julien Muchembled committed
3275
    self.tic()
3276

3277 3278 3279 3280 3281 3282 3283 3284
  def beforeTearDown(self):
    # invalidating definitions is enough
    for obj in self.resource_bylot_overriding.objectValues("Quantity Unit " \
        "Conversion Group"):
      obj.invalidate()

    super(TestUnitConversionDefinition, self).beforeTearDown()

3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343
  def testAggregatedReports(self):
    self.makeMovement(-10, self.resource_bylot)
    self.makeMovement(-1, self.resource_bypack)
    self.makeMovement(2, self.resource_bylot_overriding)
    self.makeMovement(500, self.resource_byunit)

    # Always displayed as quantity*unit_ratio
    self.assertEquals(10*1000 + 1*6 - 2*50 - 500*1,
                      self.convertedSimulation('unit'))
    self.assertEquals(10*1000 + 1*6 - 2*50 - 500*1,
                      self.convertedSimulation('unit',
                                               quantity_unit='unit/unit'))
    self.assertEquals(10*1 + 1*(6*0.001) - 2*1 - 500*(1./1000),
                      self.convertedSimulation('unit',
                                               quantity_unit='unit/lot'))
    # amounts are rounded on the 12th digit.
    self.assertEquals(round(10*(1000./6) + 1*1 - 2*(50./6) - 500*(1./6), 12),
                      self.convertedSimulation('unit',
                                               quantity_unit='unit/pack'))

  def testResourceConvertQuantity(self):
    # First, test without local Unit Definitions
    for resource in (self.resource_bylot,
                     self.resource_bypack,
                     self.resource_byunit):
      # not_reference -> reference quantity
      self.assertEquals(1000,
                        resource.convertQuantity(1,
                                                 "unit/lot",
                                                 "unit/unit"))
      # reference -> not_reference
      self.assertEquals(1,
                        resource.convertQuantity(1000,
                                                 "unit/unit",
                                                 "unit/lot"))
      # not_reference -> not_reference
      self.assertEquals(1*1000./6,
                        resource.convertQuantity(1,
                                                 "unit/lot",
                                                 "unit/pack"))
      self.assertEquals(1*6./1000,
                        resource.convertQuantity(1,
                                                 "unit/pack",
                                                 "unit/lot"))

    # then with local Unit definition
    self.assertEquals(1*50,
                      self.resource_bylot_overriding\
                          .convertQuantity(1, "unit/lot", "unit/unit"))
    self.assertEquals(1./50,
                      self.resource_bylot_overriding\
                          .convertQuantity(1, "unit/unit", "unit/lot"))
    self.assertEquals(1*50./6,
                      self.resource_bylot_overriding\
                          .convertQuantity(1, "unit/lot", "unit/pack"))
    self.assertEquals(1*6./50,
                      self.resource_bylot_overriding\
                          .convertQuantity(1, "unit/pack", "unit/lot"))

3344
  def checkInitialStateAndGetLotDefinition(self):
3345
    """
3346 3347 3348
    Helper function: check correctness of initial definitions
    and return the (sole) Definition object of unit/lot for further
    changes.
3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366
    """
    # Before the global change, global definition reads 1000
    self.assertEquals(1000,
                      self.resource_bylot.convertQuantity(1,
                                                           "unit/lot",
                                                           "unit/unit"))
    # which does not affect resources overriding the definition
    self.assertEquals(1*50,
                      self.resource_bylot_overriding\
                          .convertQuantity(1, "unit/lot", "unit/unit"))

    portal = self.getPortalObject()

    lot_uid = portal.portal_categories.quantity_unit.unit.lot.getUid()
    query = portal.portal_catalog(quantity_unit_uid=lot_uid,
                                                  grand_parent_portal_type= \
                                                    "Quantity Unit Conversion" \
                                                    " Module",
3367
                                                  validation_state="validated",
3368 3369 3370 3371
                                                  portal_type= \
                                                    "Quantity Unit Conversion" \
                                                    " Definition")
    self.assertEquals(1, len(query))
3372
    return query[0].getObject()
3373

3374 3375 3376 3377 3378 3379
  def testResourceConvertQuantityAfterGlobalChange(self):
    """
    after a change in a Global unit definition, definitions should get
    reindexed.
    """
    lot_definition = self.checkInitialStateAndGetLotDefinition()
3380

3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428
    # We use a try...finally to avoid hitting unrelated tests
    # in case of a failure
    try:
      lot_definition.setQuantity(500)

      # this change triggers Resource reindexations. Wait for 'em!
      self.tic()

      # SQL tables should have been updated:
      self.assertEquals(500,
                        self.resource_bylot.convertQuantity(1,
                                                            "unit/lot",
                                                            "unit/unit"))
      # without affecting resources that override the definition
      self.assertEquals(1*50,
                        self.resource_bylot_overriding\
                           .convertQuantity(1, "unit/lot", "unit/unit"))
    finally:
      # restore initial value
      lot_definition.setQuantity(1000)

  def testResourceConvertQuantityAfterInvalidation(self):
    """
    after invalidating a Global unit definition, definitions should get
    reindexed, and cache should be reloaded.
    """
    lot_definition = self.checkInitialStateAndGetLotDefinition()

    # Be careful to restore the object state whatever is the outcome
    # of the test
    try:
      lot_definition.invalidate()

      # this change triggers Resource reindexations. Wait for 'em!
      self.tic()

      # SQL tables should have been updated:
      self.assertEquals(None,
                        self.resource_bylot.convertQuantity(1,
                                                            "unit/lot",
                                                            "unit/unit"))
      # without affecting resources that override the definition
      self.assertEquals(1*50,
                        self.resource_bylot_overriding\
                            .convertQuantity(1, "unit/lot", "unit/unit"))
    finally:
      # restore initial state
      lot_definition.validate()
3429

3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443
class TestUnitConversionBackwardCompatibility(BaseTestUnitConversion):
  QUANTITY_UNIT_DICT = {
    # base: (reference, dict_of_others)
    'mass':   ('kilogram', dict(gram=0.001)),
  }
  METRIC_TYPE_CATEGORY_LIST = (
    'mass/net',
  )
  def setUpUnitDefinition(self):
    # bypass Unit Definition setup
    mass_category = self.portal.portal_categories.quantity_unit.mass
    mass_category.gram.setProperty('quantity', 0.001)
    mass_category.kilogram.setProperty('quantity', 1)

3444 3445
    # clear cache to force recalculation of quantity units
    self.portal.portal_caches.clearCache(('erp5_content_long',))
3446 3447

  def testBackwardCompatibility(self):
Julien Muchembled's avatar
Julien Muchembled committed
3448
    self.getRule(reference='default_delivery_rule').validate()
3449 3450 3451 3452 3453 3454 3455 3456 3457

    resource = self.portal.product_module.newContent(
                      portal_type='Product',
                      quantity_unit_list=('mass/gram',
                                          'mass/kilogram'),)
    node = self.portal.organisation_module.newContent(
                      portal_type='Organisation')
    delivery = self.portal.purchase_packing_list_module.newContent(
                      portal_type='Purchase Packing List',
Julien Muchembled's avatar
Julien Muchembled committed
3458
                      specialise=self.business_process,
3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488
                      start_date='2010-01-26',
                      price_currency='currency_module/EUR',
                      destination_value=node,
                      destination_section_value=node)
    delivery.newContent(portal_type='Purchase Packing List Line',
                        resource_value=resource,
                        quantity=10,
                        quantity_unit='mass/gram')
    delivery.newContent(portal_type='Purchase Packing List Line',
                        resource_value=resource,
                        quantity=3,
                        quantity_unit='mass/kilogram')
    delivery.confirm()
    delivery.start()
    delivery.stop()
    self.tic()

    # inventories of that resource are indexed in grams
    self.assertEquals(3010,
        self.portal.portal_simulation.getCurrentInventory(
          resource_uid=resource.getUid(),
          node_uid=node.getUid()))

    # converted inventory also works
    self.assertEquals(3.01,
        self.portal.portal_simulation.getCurrentInventory(
          quantity_unit='mass/kilogram',
          resource_uid=resource.getUid(),
          node_uid=node.getUid()))

3489 3490 3491 3492 3493 3494 3495 3496 3497
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestInventory))
  suite.addTest(unittest.makeSuite(TestInventoryList))
  suite.addTest(unittest.makeSuite(TestMovementHistoryList))
  suite.addTest(unittest.makeSuite(TestInventoryStat))
  suite.addTest(unittest.makeSuite(TestNextNegativeInventoryDate))
  suite.addTest(unittest.makeSuite(TestTrackingList))
  suite.addTest(unittest.makeSuite(TestInventoryDocument))
3498
  suite.addTest(unittest.makeSuite(TestUnitConversion))
3499
  suite.addTest(unittest.makeSuite(TestUnitConversionDefinition))
3500
  suite.addTest(unittest.makeSuite(TestUnitConversionBackwardCompatibility))
3501
  return suite
3502 3503

# vim: foldmethod=marker