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

35
# TODO : 
Jérome Perrin's avatar
Jérome Perrin committed
36
#   * test with a Person as destination_section
37 38 39
#   * test payment rule & payment builder
#   * test invoicing rule by connecting to order test.
# 
40

Jérome Perrin's avatar
Jérome Perrin committed
41
import os, sys, random
42
if __name__ == '__main__':
43
  execfile(os.path.join(sys.path[0], 'framework.py'))
44 45 46 47 48 49

# Needed in order to have a log file inside the current folder
os.environ['EVENT_LOG_FILE'] = os.path.join(os.getcwd(), 'zLOG.log')
os.environ['EVENT_LOG_SEVERITY'] = '-300'

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
50
from Products.ERP5Type.tests.Sequence import Sequence, SequenceList
51

52 53 54 55 56
from Testing import ZopeTestCase
from AccessControl.SecurityManagement import newSecurityManager
from zLOG import LOG, INFO
from DateTime import DateTime
  
57 58
class TestAccountingRules(ERP5TypeTestCase):
  """
Jérome Perrin's avatar
Jérome Perrin committed
59 60
  This should test the simulation tree and builds starting from the
  invoice.
61

62
  """
63

64
  RUN_ALL_TESTS = 1
Jérome Perrin's avatar
Jérome Perrin committed
65
  RUN_BROKEN_TESTS = os.getenv('RUN_BROKEN_TESTS', 0)
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

  # define portal_types 
  account_module_portal_type           = "Account Module"
  accounting_module_portal_type        = "Accounting Module"
  product_module_portal_type           = "Product Module"
  currency_module_portal_type          = "Currency Module"
  organisation_portal_type             = "Organisation"
  account_portal_type                  = "Account"
  product_portal_type                  = "Product"
  currency_portal_type                 = "Currency"
  predicate_portal_type                = "Predicate"
  applied_rule_portal_type             = "Applied Rule"
  simulation_movement_portal_type      = "Simulation Movement"
  accounting_rule_cell_portal_type     = "Accounting Rule Cell"
  sale_invoice_transaction_portal_type = "Sale Invoice Transaction"
  sale_invoice_transaction_line_portal_type \
                     = "Sale Invoice Transaction Line"
Jérome Perrin's avatar
Jérome Perrin committed
83 84
  sale_invoice_line_portal_type        = "Invoice Line"
  sale_invoice_cell_portal_type        = "Invoice Cell"
85 86 87 88 89
  
  purchase_invoice_transaction_portal_type \
                      = "Purchase Invoice Transaction"
  payment_transaction_portal_type      = "Payment Transaction"
  
90
  def getTitle(self):
91 92
    return "Test Accounting Rules"
 
93
  def getBusinessTemplateList(self):
94 95
    """  Return the list of business templates. """
    return ('erp5_pdm', 'erp5_trade', 'erp5_accounting')
96

97
  def getAccountModule(self):
98 99 100
    return getattr(self.getPortal(), 'account',
        getattr(self.getPortal(), 'account_module'))
  
101
  def getAccountingModule(self):
102 103
    return getattr(self.getPortal(), 'accounting',
        getattr(self.getPortal(), 'accounting_module'))
104 105

  def getProductModule(self):
106 107 108 109 110 111 112 113 114 115 116 117 118 119
    return getattr(self.getPortal(), 'product',
        getattr(self.getPortal(), 'product_module'))
  
  ## XXX move this to "Sequence class"
  def playSequence(self, sequence_string) :
    sequence_list = SequenceList()
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self)

  def afterSetUp(self) :
    self.login()
    self.createCategories()
   
  def login(self):
120
    uf = self.getPortal().acl_users
121
    uf._doAddUser('alex', '', ['Manager', 'Owner', 'Assignor'], [])
122 123
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
  
  def createCategories(self) :
    """ create all categories that are needed for this test.
    It uses getCategoriesToCreate, so you should overload this method.
    """
    # create base categories
    for base_cat in self.getBaseCategoriesToCreate() :
      if not base_cat in self.getCategoryTool().objectIds() :
        self.getCategoryTool().newContent(
          portal_type = 'Base Category',
          id = base_cat)
    # create categories
    for cat_string in self.getCategoriesToCreate() :
      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',
            id = cat,
            immediate_reindex = 1 )
    # check categories have been created
    for cat_string in self.getCategoriesToCreate() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
    
  def getBaseCategoriesToCreate(self) :
    return ("hd_size", "cpu_freq")

  def getCategoriesToCreate(self):
    return (
      # regions for our organisations
      "region/europe/west/france",
      "region/africa",
      
      # those are mandatory for account, and accounting rules depends on
      # the account_type category. (ie payable, will create a Payment 
      # Transaction accordingly)
      "account_type/asset/cash",
      "account_type/asset/receivable/refundable_vat",
      "account_type/equity",
      "account_type/expense",
      "account_type/income",
      "account_type/liability/payable/collected_vat",
     
      # some products lines for our products
      "product_line/storever/notebook",
      "product_line/storever/barebone",
      "product_line/storever/openbrick",
      "product_line/not_used/not_matched",
      
      # some categories for variating our products
      "cpu_freq/1Ghz",
      "cpu_freq/2Ghz",
      "hd_size/60Go",
      "hd_size/120Go",
    )

  def rollbackTest(self) :
    """ delete everything created by the test (for 'live debugin')""" 
    portal = self.getPortal()
    from Products.ERP5.Document.AccountingTransaction \
        import AccountingTransaction
188
    self.tic()
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
    old_manage_beforeDelete = AccountingTransaction.manage_beforeDelete 
    AccountingTransaction.manage_beforeDelete = lambda x, y, z: 1
    self.getAccountModule().deleteContent(
          list(self.getAccountModule().objectIds()))
    self.getAccountingModule().deleteContent(
          list(self.getAccountingModule().objectIds()))
    self.getOrganisationModule().deleteContent(
          list(self.getOrganisationModule().objectIds()))
    self.getCurrencyModule().deleteContent(
          list(self.getCurrencyModule().objectIds()))
    self.getProductModule().deleteContent(
          list(self.getProductModule().objectIds()))
    self.getSimulationTool().deleteContent(
          list(self.getSimulationTool().objectIds()))
    AccountingTransaction.manage_beforeDelete = old_manage_beforeDelete
    self.tic()
  
  def stepTic(self, **kw):
207
    self.tic()
208

Jérome Perrin's avatar
Jérome Perrin committed
209 210 211
  def stepCommitTransaction(self, **kw):
    get_transaction().commit()
    
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  def stepCreateSaleInvoiceTransactionRule(self, sequence, **kw) :
    """ 
      Create some predicates in the Invoice Transaction Rule
    """
    invoice_transaction_rule = getattr(self.getRuleTool(),
            'default_invoice_transaction_rule')
    # delete anything inside the rule first
    # clear the message queue, so that it does not contains unexistant paths
    self.tic()
    invoice_transaction_rule.deleteContent(
                [x for x in invoice_transaction_rule.objectIds()])
    self.assertEquals(len(invoice_transaction_rule.objectValues()), 0)
    
    # and add new content, predicate product_line
    predicate_product_notebook = invoice_transaction_rule.newContent(
      id = 'product_notebook',
      title = 'Product Notebook',
      portal_type = self.predicate_portal_type,
      string_index = 'product',
      int_index = '1',
      membership_criterion_base_category_list = ['product_line',],
      membership_criterion_category_list = ['product_line/storever/notebook'],
      immediate_reindex = 1,
    )
    predicate_product_barebone = invoice_transaction_rule.newContent(
      id = 'product_barebone',
      title = 'Product Barebone',
      portal_type = self.predicate_portal_type,
      string_index = 'product',
      int_index = '2',
      membership_criterion_base_category_list = ['product_line',],
      membership_criterion_category_list = ['product_line/storever/barebone'],
      immediate_reindex = 1,
    )
    # ... and destination_region
    predicate_region_france = invoice_transaction_rule.newContent(
      id = 'region_france',
      title = 'Region France',
      portal_type = self.predicate_portal_type,
      string_index = 'region',
      int_index ='1',
      membership_criterion_base_category_list = ['destination_region',],
      membership_criterion_category_list =
                    ['destination_region/region/europe/west/france'],
      immediate_reindex = 1,
    )
    predicate_region_africa = invoice_transaction_rule.newContent(
      id = 'region_africa',
      title = 'region_africa',
      portal_type = self.predicate_portal_type,
      string_index = 'region',
      int_index = '2',
      membership_criterion_base_category_list = ['destination_region',],
      membership_criterion_category_list = ['destination_region/region/africa'],
      immediate_reindex = 1,
    )
    # sanity checks
    self.failUnless(predicate_product_notebook != None)
    self.failUnless(predicate_product_barebone != None)
    self.failUnless(predicate_region_france  != None)
    self.failUnless(predicate_region_africa  != None)
    predicate_list = invoice_transaction_rule.contentValues(
          filter = {'portal_type': self.predicate_portal_type})
    self.assertEqual(len(predicate_list), 4)
    sequence.edit(
      invoice_transaction_rule = invoice_transaction_rule,
      predicate_product_notebook = predicate_product_notebook,
      predicate_product_barebone = predicate_product_barebone,
      predicate_region_france  = predicate_region_france,
      predicate_region_africa  = predicate_region_africa,
    )
  
  def stepUpdateSaleInvoiceTransactionRuleMatrix(self, sequence, **kw) :
    """ creates/updates the matrix of the sale invoice transacction rule """
    invoice_transaction_rule = sequence.get('invoice_transaction_rule')
    base_id = 'movement'
288
    kwd = {'base_id': base_id}
289
    
290
    # update the matrix, generates the accounting rule cells
291 292 293 294
    invoice_transaction_rule.edit()
    invoice_transaction_rule.updateMatrix()
    self.tic()
    
295
    # check the accounting rule cells inside the matrix
296 297
    cell_list = invoice_transaction_rule.contentValues(
                filter = {'portal_type':self.accounting_rule_cell_portal_type})
298 299
    self.assertEqual(len(cell_list), 4)

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 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 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 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    # In the matrix, cells are named on the scheme :
    # ${base_id} + '_'.join(predicate_dimension ordered by int_index)
    product_notebook_region_france_cell = getattr(invoice_transaction_rule,
                                          '%s_0_0'%base_id, None)
    product_notebook_region_africa_cell = getattr(invoice_transaction_rule,
                                          '%s_0_1'%base_id, None)
    product_barebone_region_france_cell = getattr(invoice_transaction_rule,
                                          '%s_1_0'%base_id, None)
    product_barebone_region_africa_cell = getattr(invoice_transaction_rule,
                                          '%s_1_1'%base_id, None)
    
    self.failUnless(product_notebook_region_france_cell != None)
    self.failUnless(product_notebook_region_africa_cell != None)
    self.failUnless(product_barebone_region_france_cell != None)
    self.failUnless(product_barebone_region_africa_cell != None)

    sequence.edit(
      product_notebook_region_france_cell = product_notebook_region_france_cell,
      product_notebook_region_africa_cell = product_notebook_region_africa_cell,
      product_barebone_region_france_cell = product_barebone_region_france_cell,
      product_barebone_region_africa_cell = product_barebone_region_africa_cell,
    )
    
  def stepCreateNotebookFranceCell(self, sequence, **kw):
    """ creates the content of product_notebook_region_france_cell """
    # create content in the notebook / france cell
    product_notebook_region_france_cell = sequence.get(
        'product_notebook_region_france_cell')
    product_notebook_region_france_cell_income = \
        product_notebook_region_france_cell.newContent(
            id = 'income',
            source = sequence.get('income').getRelativeUrl(),
            quantity = 1)
    product_notebook_region_france_cell_receivable = \
        product_notebook_region_france_cell.newContent(
            id = 'receivable',
            source = sequence.get('receivable').getRelativeUrl(),
            quantity = -1.196)
    product_notebook_region_france_cell_vat = \
        product_notebook_region_france_cell.newContent(
            id = 'collected_vat',
            source = sequence.get('collected_vat').getRelativeUrl(),
            quantity = 0.196)
    sequence.edit(
      invoice_transaction_rule_cell = product_notebook_region_france_cell,
      product_notebook_region_france_cell_income =
            product_notebook_region_france_cell_income,
      product_notebook_region_france_cell_receivable =
            product_notebook_region_france_cell_receivable,
      product_notebook_region_france_cell_vat =
            product_notebook_region_france_cell_vat,
    )
  
  def stepCreateBareboneFranceCell(self, sequence, **kw):
    """ creates the content of product_barebone_region_france_cell, 
      the same as product_notebook_region_france_cell, but the income
      account is differrent """
    # create content in the notebook / france cell
    product_barebone_region_france_cell = sequence.get(
        'product_barebone_region_france_cell')
    product_barebone_region_france_cell_income = \
        product_barebone_region_france_cell.newContent(
            id = 'income',
            source = sequence.get('income_barebone').getRelativeUrl(),
            quantity = 1)
    product_barebone_region_france_cell_receivable = \
        product_barebone_region_france_cell.newContent(
            id = 'receivable',
            source = sequence.get('receivable').getRelativeUrl(),
            quantity = -1.196)
    product_barebone_region_france_cell_vat = \
        product_barebone_region_france_cell.newContent(
            id = 'collected_vat',
            source = sequence.get('collected_vat').getRelativeUrl(),
            quantity = 0.196)
    sequence.edit(
      product_barebone_region_france_cell = product_barebone_region_france_cell,
      product_barebone_region_france_cell_income =\
                product_barebone_region_france_cell_income,
      product_barebone_region_france_cell_vat =\
                product_barebone_region_france_cell_vat,
      product_barebone_region_france_cell_receivable =\
                product_barebone_region_france_cell_receivable
    )
      
  
  def stepCreateAccounts(self, sequence, **kw):
    """
      Create an income, an payable and a collected_vat account
    """
    portal = self.getPortal()
    account_module = self.getAccountModule()
    if not hasattr(account_module, 'income') :
      income = account_module.newContent(
        id = "income",
        portal_type = self.account_portal_type,
        title = "Income Notebook",
        account_type = "income",
        immediate_reindex = 1,
      )
      income = account_module.newContent(
        id = "income_barebone",
        portal_type = self.account_portal_type,
        title = "Income Barebone",
        account_type = "income",
        immediate_reindex = 1,
      )
      receivable = account_module.newContent(
        id = "receivable",
        portal_type=self.account_portal_type,
        title = "Receivable",
        account_type = "asset/receivable",
        immediate_reindex = 1,
      )
      collected_vat = account_module.newContent(
        id = "collected_vat",
        portal_type=self.account_portal_type,
        title = "Collected VAT",
        account_type = "liability/payable/collected_vat",
        immediate_reindex = 1,
      )
    # store accounts in sequence object
    sequence.edit(
      income          = account_module.income,
      income_barebone = account_module.income_barebone,
      receivable      = account_module.receivable,
      collected_vat   = account_module.collected_vat,
    )
    
  def stepCreateEntities(self, sequence, **kw) :
    """ Create a vendor and a client organisation.
      The region of the client is the same as the region
      defined in the rule.
    """
    organisation_module = self.getOrganisationModule()
    if not hasattr(organisation_module, 'vendor') :
      vendor = organisation_module.newContent(
        portal_type = self.organisation_portal_type,
        id = "vendor",
        title = "Vendor",
        region = "europe/west/france",
        immediate_reindex = 1,
      )
      self.assertNotEquals(vendor.getDefaultRegionValue(), None)
      client_fr = organisation_module.newContent(
        portal_type = self.organisation_portal_type,
        id = "client_fr",
        title = "French Client",
        region = "europe/west/france",
        immediate_reindex = 1,
      )
      self.assertNotEquals(client_fr.getDefaultRegionValue(), None)
    sequence.edit(
      vendor      = organisation_module.vendor,
      client_fr   = organisation_module.client_fr,
      client      = organisation_module.client_fr,
    )
  
  def stepCreateProducts(self, sequence, **kw) :
    """
      Create 2 kind of products, a notebook (Varianted) 
      and a barebone not varianted.
    """
    product_module = self.getProductModule()
    if not hasattr(product_module, 'notebook') :
      # Create some products
      notebook = product_module.newContent(
        id = 'notebook',
        title = 'Notebook',
        portal_type = self.product_portal_type,
        product_line = 'storever/notebook',
        base_price = 3.0,
        immediate_reindex = 1,
      )
      # sets some variation categories on the notebook product
      notebook.setVariationBaseCategoryList(["hd_size", "cpu_freq"])
      notebook.setVariationCategoryList([
        "cpu_freq/1Ghz",
        "cpu_freq/2Ghz",
        "hd_size/60Go",
        "hd_size/120Go",])
      
      barebone = product_module.newContent(
        id = 'barebone',
        title = 'Barebone',
        portal_type = self.product_portal_type,
        product_line = 'storever/barebone',
        base_price = 5.0,
        immediate_reindex = 1,
      )
    sequence.edit(
      notebook = product_module.notebook,
      barebone = product_module.barebone,
      product_notebook = product_module.notebook,
      product_barebone = product_module.barebone,
    )
    
  def stepCreateCurrencies(self, sequence, **kw) :
    """
      Create EUR currency
    """
    currency_module = self.getCurrencyModule()
    if not hasattr(currency_module, 'EUR') :
      currency_module.newContent(
        id = 'EUR',
        title = 'Euro',
        portal_type = self.currency_portal_type,
      )
    sequence.edit(euro=currency_module.EUR, currency=currency_module.EUR)
    
  def stepCreatePaymentRule(self, **kw) :
    """ create a rule payment transaction generation """
    # XXX: for now there are no cells in payment rule, so nothing to do here
    # TODO
    
Jérome Perrin's avatar
Jérome Perrin committed
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
  def stepCreateEmptyInvoice(self, sequence, **kw) :
    """ Create an empty invoice that will be modified later """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    currency = sequence.get('currency')
    
    empty_invoice = self.getAccountingModule().newContent(
                id = 'empty_invoice',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    sequence.edit(
      simple_invoice = empty_invoice,
      invoice = empty_invoice,
    )
    
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  def stepCreateSimpleSaleInvoice(self, sequence, **kw) :
    """ creates a simple sale invoice for non varianted notebook product.
      The invoice is from `vendor` to `client_fr`, so the cell defined in
      stepUpdateSaleInvoiceTransactionRuleMatrix should match. 
      This invoice containts one line, 10 notebook * 10 EUR, so total price
      is 100
    """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    product_notebook = sequence.get('product_notebook')
    currency = sequence.get('currency')
    
    simple_invoice = self.getAccountingModule().newContent(
                id = 'simple_invoice',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    invoice_line = simple_invoice.newContent(
      id = 'invoice_line',
      resource = product_notebook.getRelativeUrl(),
      quantity = 10,
Jérome Perrin's avatar
Jérome Perrin committed
562 563
      price = 10,
      portal_type = self.sale_invoice_line_portal_type)
564 565 566 567 568 569 570 571 572 573

    self.assertEqual(invoice_line.getTotalPrice(), 100)
    
    sequence.edit(
      simple_invoice = simple_invoice,
      invoice = simple_invoice,
      invoice_line = invoice_line,
      invoice_lines = [invoice_line]
    )
  
Jérome Perrin's avatar
Jérome Perrin committed
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654
  def stepCreateOtherSimpleSaleInvoice(self, sequence, **kw) :
    """ creates a simple sale invoice for non varianted notebook product.
      It will contain one line that will later be changed.
    """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    product_notebook = sequence.get('product_notebook')
    currency = sequence.get('currency')
    
    simple_invoice = self.getAccountingModule().newContent(
                id = 'other_simple_invoice',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    invoice_line = simple_invoice.newContent(
      id = 'invoice_line',
      resource = product_notebook.getRelativeUrl(),
      quantity = 123,
      price = 456,
      portal_type = self.sale_invoice_line_portal_type)

    sequence.edit(
      simple_invoice = simple_invoice,
      invoice = simple_invoice,
      invoice_line = invoice_line,
      invoice_lines = [invoice_line]
    )

  def stepAddInvoiceLine(self, sequence, **kw) :
    """ add an invoice line in the current invoice : 
      10 notebook * 10 EUR, so total price is 100
    """
    product_notebook = sequence.get('product_notebook')
    invoice = sequence.get('invoice')
    
    invoice_line = invoice.newContent(
      id = 'invoice_line_%s'%(int(random.random()*1000)),
      resource = product_notebook.getRelativeUrl(),
      quantity = 10,
      price = 10,
      portal_type = self.sale_invoice_line_portal_type)

    self.assertEqual(invoice_line.getTotalPrice(), 100)
    
    sequence.edit(
      invoice_line = invoice_line,
      invoice_lines = [invoice_line]
    )

  def stepEditInvoiceLine(self, sequence, **kw) :
    """ edit the invoice line : 
      10 notebook * 10 EUR, so total price is 100
    """
    invoice = sequence.get('invoice')
    invoice_line = sequence.get('invoice_line')
    invoice_line.edit(
      quantity = 10,
      price = 10)
    
    self.assertEqual(invoice_line.getTotalPrice(), 100)

   
  def stepDeleteInvoiceLine(self, sequence, **kw) :
    """ remove an invoice line from the invoice
    """
    invoice = sequence.get('invoice')
    invoice_line = sequence.get('invoice_line')
    invoice.deleteContent([invoice_line.getId()])
 
  def stepUpdateAppliedRule(self, sequence, **kw) :
    """ update the applied rule for the invoice. In the UI, the call to
    updateAppliedRule is made in an interraction workflow when you edit
    an invoice or its content."""
    sequence.get('invoice').updateAppliedRule(
            rule_id='default_invoice_transaction_rule')
    
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679
  def stepCreateSimpleSaleInvoiceTwoLines(self, sequence, **kw) :
    """ 
      similar to stepCreateSimpleSaleInvoice, but replace 
      "10 notebook * 10 EUR, so total price is 100" by :
      "5 notebook * 10 EUR + 5 notebook * 10 EUR , so total price is 100"
    """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    product_notebook = sequence.get('product_notebook')
    currency = sequence.get('currency')
    
    simple_invoice = self.getAccountingModule().newContent(
                id = 'simple_invoice_two_lines',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    invoice_line1 = simple_invoice.newContent(
      id = 'invoice_line1',
      resource = product_notebook.getRelativeUrl(),
      quantity = 5,
Jérome Perrin's avatar
Jérome Perrin committed
680 681
      price = 10,
      portal_type = self.sale_invoice_line_portal_type)
682 683
    invoice_line2 = simple_invoice.newContent(
      id = 'invoice_line2',
Jérome Perrin's avatar
Jérome Perrin committed
684
      REsource = product_notebook.getRelativeUrl(),
685
      quantity = 5,
Jérome Perrin's avatar
Jérome Perrin committed
686 687
      price = 10,
      portal_type = self.sale_invoice_line_portal_type)
688 689 690 691 692 693 694 695 696 697

    self.assertEqual(invoice_line1.getTotalPrice()
            + invoice_line2.getTotalPrice(), 100)
    
    sequence.edit(
      simple_invoice = simple_invoice,
      invoice = simple_invoice,
      invoice_lines = [invoice_line1, invoice_line2]
    )

Jérome Perrin's avatar
Jérome Perrin committed
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727
  def stepCreateSimpleSaleInvoiceTwoCells(self, sequence, **kw) :
    """ 
      similar to stepCreateSimpleSaleInvoiceTwoLines, but use two
      differents cells on the same line instead of two differents lines. 
    """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    product_notebook = sequence.get('product_notebook')
    currency = sequence.get('currency')
    
    simple_invoice = self.getAccountingModule().newContent(
                id = 'simple_invoice_two_cells',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    invoice_line = simple_invoice.newContent(
      id = 'invoice_line',
      resource = product_notebook.getRelativeUrl(),
      portal_type = self.sale_invoice_line_portal_type)
      
    sequence.edit(
      simple_invoice = simple_invoice,
      invoice = simple_invoice,
      invoice_line = invoice_line,
      invoice_lines = [invoice_line]
728
    )
Jérome Perrin's avatar
Jérome Perrin committed
729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
    self.stepAddCellsInInvoiceLine(sequence)

  def stepAddCellsInInvoiceLine(self, sequence, **kw):
    """ add 2 cells in the invoice line, same quantity as simple invoice
    """
    invoice_line = sequence.get('invoice_line')
    
    # initialy, the line must not contain cells
    self.assertEqual(len(invoice_line.objectIds()), 0)
    invoice_line._setVariationBaseCategoryList(['hd_size', 'cpu_freq'])
    invoice_line._setVariationCategoryList(
                    ['hd_size/60Go', 'hd_size/120Go', 'cpu_freq/1Ghz' ])
    base_id = 'movement'
    invoice_line.updateCellRange(base_id)
    cell_key_list = list(invoice_line.getCellKeyList(base_id = base_id))
    
    # this is probably not the easiest way to create cells ...
    price = 10
    quantity = 5
    for cell_key in cell_key_list:
      cell = invoice_line.newCell(base_id = base_id,
             portal_type = self.sale_invoice_cell_portal_type, *cell_key)
      cell.edit(mapped_value_property_list = ['price','quantity'],
                price = price, quantity = quantity,
                predicate_category_list = cell_key,
                variation_category_list = cell_key)
    
    # getTotalPrice uses mysql, so we must make sure the invoice is cataloged
    # to have correct results
    invoice_line.getParent().recursiveImmediateReindexObject()
    self.assertEqual(invoice_line.getTotalPrice(), 100)
    self.assertEqual(invoice_line.getTotalQuantity(), 10)
761
    
Jérome Perrin's avatar
Jérome Perrin committed
762 763 764
    # then we must have 2 cells inside our line
    self.assertEqual(len(invoice_line.objectIds()), 2)

765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 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 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
  def stepCreateMultiLineSaleInvoice(self, sequence, **kw) :
    """ create an invoice with varianted products 
      The invoice is from `vendor` to `client_fr`, so the cell defined in
      This invoice containts two lines :
      10 notebook * 10 EUR, so total price is 100 
            (matched by product_notebook_region_france_cell)
      10 barebone * 100 EUR, so total price is 1000 
            (matched by product_notebook_region_france_cell)
      total price for the invoice is 100 + 1000
    """
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    product_notebook = sequence.get('product_notebook')
    product_barebone = sequence.get('product_barebone')
    currency = sequence.get('currency')
    
    multi_line_invoice = self.getAccountingModule().newContent(
                id = 'multi_line_invoice',
                portal_type = self.sale_invoice_transaction_portal_type,
                resource = currency.getRelativeUrl(),
                price_currency = currency.getRelativeUrl(),
                stop_date = DateTime(2004, 01, 01),
                start_date = DateTime(2004, 01, 01),
                source_section = vendor.getRelativeUrl(),
                destination_section = client.getRelativeUrl(),
              )
    
    notebook_line = multi_line_invoice.newContent(
      id = 'notebook_line',
      resource = product_notebook.getRelativeUrl(),
      quantity = 10,
      price = 10)

    barebone_line = multi_line_invoice.newContent(
      id = 'barebone_line',
      resource = product_barebone.getRelativeUrl(),
      quantity = 10,
      price = 100)

    self.assertEqual( 10*10 + 10*100,
        notebook_line.getTotalPrice() + barebone_line.getTotalPrice())
    
    sequence.edit(
      multi_line_invoice = multi_line_invoice,
      invoice = multi_line_invoice,
      invoice_lines = [notebook_line, barebone_line],
    )
    
  def stepCheckAddPredicate(self, sequence, **kw) :
    invoice_transaction_rule = sequence.get('invoice_transaction_rule')
    # next, we add a predicate to see if it is still okay (3x2 cells)
    predicate_product3 = invoice_transaction_rule.newContent(
      id = 'product_3',
      title = 'product_3',
      portal_type = self.predicate_portal_type,
      string_index = 'product',
      int_index = '3',
      membership_criterion_base_category_list = ['product_line',],
      membership_criterion_category_list = ['product_line/storever/openbrick'],
      immediate_reindex = 1,
    )
    invoice_transaction_rule.updateMatrix()
827
    self.tic()
828 829 830 831 832 833 834 835 836 837 838 839 840
    cell_list = invoice_transaction_rule.contentValues(
        filter = {'portal_type': self.accounting_rule_cell_portal_type})
    self.assertEqual(len(cell_list), 6)

  def stepCheckRemovePredicate(self, sequence, **kw) :
    invoice_transaction_rule = sequence.get('invoice_transaction_rule')
    self.tic() # make sure message queue is empty
    # then, we remove a predicate and check again (3x3 cells)
    invoice_transaction_rule.deleteContent(id = 'region_africa')
    invoice_transaction_rule.updateMatrix()
    cell_list = invoice_transaction_rule.contentValues(
                 filter = {'portal_type':self.accounting_rule_cell_portal_type})
    self.assertEqual(len(cell_list), 3)
841

842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 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 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101
  def stepCheckRestoreOriginalPredicates(self, sequence, **kw) :
    """ we put back the matrix in the original format (2x2 cells) """
    invoice_transaction_rule = sequence.get("invoice_transaction_rule")
    self.tic() # make sure message queue is empty
    invoice_transaction_rule.deleteContent(id='product_3')
    predicate_region_africa = invoice_transaction_rule.newContent(
      id = 'region_africa', title = 'Region Africa',
      portal_type = self.predicate_portal_type,
      string_index = 'region', int_index = '2',
      membership_criterion_base_category_list = ['destination_region',],
      membership_criterion_category_list = ['destination_region/region/africa'],
      immediate_reindex = 1,
    )
    invoice_transaction_rule.updateMatrix()
    cell_list = invoice_transaction_rule.contentValues(
        filter = {'portal_type':self.accounting_rule_cell_portal_type})
    self.assertEqual(len(cell_list), 4)
   
  def stepCreateDummyInvoice(self, sequence, **kw) :
    """ Create a dummy invoice for temp movements """
    invoice = self.getAccountingModule().newContent(
                      id = "dummy_invoice",
                   )
    sequence.edit(invoice = invoice)
    
  def stepCreateMatchableSaleInvoiceMovements(self, sequence, **kw) :
    """ Create a temp movement that will be matched by the
      default_invoice_transaction_rule """
    from Products.ERP5Type.Document import newTempMovement
    product_notebook_region_france_movement = newTempMovement(
      sequence.get('invoice'),
      'test1',
      resource = sequence.get('notebook').getRelativeUrl(),
      destination = sequence.get('client_fr').getRelativeUrl(),
    )
    product_barebone_region_france_movement = newTempMovement(
      sequence.get('invoice'),
      'test2',
      resource = sequence.get('barebone').getRelativeUrl(),
      destination = sequence.get('client_fr').getRelativeUrl(),
    )
    sequence.edit(
      product_notebook_region_france_movement =
                  product_notebook_region_france_movement ,
      product_barebone_region_france_movement =
                  product_barebone_region_france_movement ,
    )
  
  def stepCheckMatchableSaleInvoiceMovements(self, sequence, **kw) :
    """ Check that we have a matching cell for the movement """
    invoice_transaction_rule = sequence.get("invoice_transaction_rule")
    product_barebone_region_france_movement  = sequence.get(
                          'product_barebone_region_france_movement')
    product_notebook_region_france_movement  = sequence.get(
                          'product_notebook_region_france_movement')
    
    # Make sure acquisition is working for destination_region
    self.assertEqual(
          product_barebone_region_france_movement.getDestinationRegion(),
          'region/europe/west/france')
    self.assertEqual(
          product_notebook_region_france_movement.getDestinationRegion(),
          'region/europe/west/france')
          
    # Make sure category is working for resource
    self.assertEqual(product_barebone_region_france_movement.getProductLine(),
            'storever/barebone')
    self.assertEqual(product_notebook_region_france_movement.getProductLine(),
            'storever/notebook')
    
    # check the predicates 
    predicate_product_notebook = sequence.get("predicate_product_notebook")
    predicate_product_barebone = sequence.get("predicate_product_barebone")
    predicate_region_france  = sequence.get("predicate_region_france")
    predicate_region_africa  = sequence.get("predicate_region_africa")
    
    self.assert_(not predicate_region_africa.test(
                      product_barebone_region_france_movement ))
    self.assert_( predicate_region_france.test(
                      product_barebone_region_france_movement ))
    self.assert_(not predicate_product_notebook.test(
                      product_barebone_region_france_movement ))
    self.assert_( predicate_product_barebone.test(
                      product_barebone_region_france_movement ))
    
    self.assert_(not predicate_region_africa.test(
                      product_notebook_region_france_movement ))
    self.assert_( predicate_region_france.test(
                      product_notebook_region_france_movement ))
    self.assert_(not predicate_product_barebone.test(
                      product_notebook_region_france_movement ))
    self.assert_( predicate_product_notebook.test(
                      product_notebook_region_france_movement ))
    
    # check the cells
    product_notebook_region_france_cell = sequence.get(
                     'product_notebook_region_france_cell')
    product_barebone_region_france_cell = sequence.get(
                     'product_barebone_region_france_cell')
    product_notebook_region_africa_cell = sequence.get(
                     'product_notebook_region_africa_cell')
    product_barebone_region_africa_cell = sequence.get(
                     'product_barebone_region_africa_cell')
    self.assert_(not product_notebook_region_france_cell.test(
                        product_barebone_region_france_movement ))
    self.assert_(    product_barebone_region_france_cell.test(
                        product_barebone_region_france_movement ))
    self.assert_(not product_notebook_region_africa_cell.test(
                        product_barebone_region_france_movement ))
    self.assert_(not product_barebone_region_africa_cell.test(
                        product_barebone_region_france_movement ))
    
    self.assert_(    product_notebook_region_france_cell.test(
                        product_notebook_region_france_movement ))
    self.assert_(not product_barebone_region_france_cell.test(
                        product_notebook_region_france_movement ))
    self.assert_(not product_notebook_region_africa_cell.test(
                        product_notebook_region_france_movement ))
    self.assert_(not product_barebone_region_africa_cell.test(
                        product_notebook_region_france_movement ))
    
    # finally check the matching cell is the good one
    self.assertEquals(product_notebook_region_france_cell,
              invoice_transaction_rule._getMatchingCell(
                product_notebook_region_france_movement ))
    self.assertEqual(product_barebone_region_france_cell,
              invoice_transaction_rule._getMatchingCell(
                product_barebone_region_france_movement ))
  
  def stepCreateNotMatchableSaleInvoiceMovements(self, sequence, **kw) :
    """ create a temp movement that not any cell could match. """
    from Products.ERP5Type.Document import newTempMovement
    bad_movement1 = newTempMovement(
      sequence.get("invoice"),
      'test3',
      product = None,
      destination = sequence.get('client').getRelativeUrl(),
    )
    bad_movement2 = newTempMovement(
      sequence.get("invoice"),
      'test4',
      gap = 'gap/1',
      destination = sequence.get('client').getRelativeUrl(),
    )
    sequence.edit(
      bad_movement1 = bad_movement1,
      bad_movement2 = bad_movement2,
    )

  def stepCheckNotMatchableSaleInvoiceMovements(self, sequence, **kw) :
    """ check that temp movement that cannot be matched is not matched. """
    invoice_transaction_rule = sequence.get('invoice_transaction_rule')
    self.assertEqual(None,
      invoice_transaction_rule._getMatchingCell(
        sequence.get('bad_movement1')))
    self.assertEqual(None,
      invoice_transaction_rule._getMatchingCell(
        sequence.get('bad_movement2')))

  def stepClearSimulation(self, sequence, **kw) :
    """ clear the content of portal_simulation """
    self.tic() # make sure message queue is empty
    self.getSimulationTool().deleteContent(
        list(self.getSimulationTool().objectIds()))
    
  def stepClearAccountingModule(self, sequence, **kw) :
    """ clear the content of accounting module """
    self.tic() # make sure message queue is empty
    # cancel accounting transaction to be able to delete them
    for transaction in self.getAccountingModule().objectValues() :
      self.getPortal().portal_workflow.doActionFor(
        transaction, 'cancel_action', wf_id='accounting_workflow')
    # delete
    self.getAccountingModule().deleteContent(
        list(self.getAccountingModule().objectIds()))
    
  def stepCheckFirstRuleIsApplied(self, sequence, **kw) :
    """ check every level of the simulation """
    invoice = sequence.get('invoice')
    invoice_line = sequence.get('invoice_line')
    invoice_transaction_rule = sequence.get('invoice_transaction_rule')
    vendor = sequence.get('vendor')
    client = sequence.get('client')
    currency = sequence.get('currency')
    invoice_transaction_rule_cell = sequence.get(
                                  'invoice_transaction_rule_cell')
    
    # content of the simulation tool is a list of invoice rules
    applied_rule_list = self.getSimulationTool().contentValues()
    
    self.assertEqual(len(applied_rule_list), 1)
    applied_rule = applied_rule_list[0]
    self.assertEqual( applied_rule.getPortalType(),
                      self.applied_rule_portal_type)
    self.assertEqual( applied_rule.getSpecialise(),
                      'portal_rules/default_invoice_rule')
    self.assertEqual( applied_rule.getCausality(),
                      invoice.getRelativeUrl())
    
    # inside the rule there are simulation movements
    simulation_movement_list = applied_rule.contentValues()
    # the first one is a mirror of the movement in the invoice line
    self.assertEqual( len(simulation_movement_list), 1)
    simulation_movement = simulation_movement_list[0]
     
    self.assertEqual( simulation_movement.getPortalType(),
                      self.simulation_movement_portal_type)
    self.assertEqual( invoice_line.getResource(),
                      simulation_movement.getResource())
    self.assertEqual( invoice_line.getQuantity(),
                      simulation_movement.getQuantity())
    self.assertEqual( invoice_line.getStopDate(),
                      simulation_movement.getStopDate())
    self.assertEqual( invoice_line.getStartDate(),
                      simulation_movement.getStartDate())
    self.assertEqual( invoice_line.getSourceSection(),
                      simulation_movement.getSourceSection())
    self.assertEqual( invoice_line.getDestinationSection(),
                      simulation_movement.getDestinationSection())
    self.assertEqual( invoice_line.getSource(),
                      simulation_movement.getSource())
    self.assertEqual( invoice_line.getDestination(),
                      simulation_movement.getDestination())
    
    # inside this movement there is an applied rule which
    # specialize invoice_transaction_rule
    applied_rule_list = simulation_movement.contentValues()
    self.assertEquals( len(applied_rule_list), 1)
    applied_rule = applied_rule_list[0]
    self.assertEquals( applied_rule.getPortalType(),
                      self.applied_rule_portal_type)
    self.assertEquals( applied_rule.getSpecialise(),
                      invoice_transaction_rule.getRelativeUrl())
    
    # and in this applied rule, we got simulation movements, 
    # based on those inside product_notebook_region_france_cell
    simulation_movement_list = applied_rule.contentValues()
    self.assertEqual( len(simulation_movement_list), 3)
    rule_movement_found = {}
    for simulation_movement in simulation_movement_list :
      self.assertEquals( simulation_movement.getSourceSection(),
                        vendor.getRelativeUrl())
      self.assertEquals( simulation_movement.getDestinationSection(),
                        client.getRelativeUrl())
      self.assertEquals( simulation_movement.getResource(),
                        currency.getRelativeUrl())
      self.assertEquals( simulation_movement.getCausalityState(),
                         'expanded')
      for rule_movement in invoice_transaction_rule_cell.contentValues() :
        if simulation_movement.getSource() == rule_movement.getSource() :
          rule_movement_found[rule_movement.getSource()] = 1
          self.assertEquals(simulation_movement.getQuantity(),
                rule_movement.getQuantity() * invoice_line.getTotalPrice())
          self.assertEquals(simulation_movement.getSourceCredit(),
                rule_movement.getSourceCredit() * invoice_line.getTotalPrice())
          self.assertEquals(simulation_movement.getSourceDebit(),
                rule_movement.getSourceDebit() * invoice_line.getTotalPrice())
      self.assert_(len(rule_movement_found.keys()), 3)
    sequence.edit( simulation_movement_list = simulation_movement_list )

Jérome Perrin's avatar
Jérome Perrin committed
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 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      
  def stepCollectSimulationMovements(self, sequence, **kw) :
    """ put some simulation movements in sequence for later checkings """
    invoice = sequence.get('invoice')
    invoice_line = sequence.get('invoice_line')
    
    applied_rule_list = self.getSimulationTool().contentValues()
    self.assertEquals(len(applied_rule_list), 1)
    simulation_movement_list = []
    simulation_movement_quantities = {}
    simulation_movement_resources = {}
    simulation_movement_paths = {}
    simulation_movement_section_paths = {}
    
    applied_rule = applied_rule_list[0]
    for invoice_simulation_movement in applied_rule.objectValues() :
      for invoice_transaction_applied_rule in \
                        invoice_simulation_movement.objectValues() :
        for simulation_movement in \
                   invoice_transaction_applied_rule.objectValues() :
          path= simulation_movement.getPath()
          simulation_movement_list.append(simulation_movement)
          simulation_movement_quantities[path] = \
                                    simulation_movement.getQuantity()
          simulation_movement_resources[path] = \
                                    simulation_movement.getResource()
          simulation_movement_paths[path] = (
                      simulation_movement.getSource(),
                      simulation_movement.getDestination())
          simulation_movement_section_paths[path] = (
                      simulation_movement.getSourceSection(),
                      simulation_movement.getDestinationSection())
    sequence.edit(
         simulation_movement_list = simulation_movement_list
      ,  simulation_movement_quantities = simulation_movement_quantities
      ,  simulation_movement_resources = simulation_movement_resources
      ,  simulation_movement_paths = simulation_movement_paths
      ,  simulation_movement_section_paths = simulation_movement_section_paths
    )

  def stepCheckSimulationMovements(self, sequence, **kw) :
    """ checks simulation movements from the sequence object """
    simulation_movement_list = sequence.get(
                                        'simulation_movement_list')
    simulation_movement_quantities = sequence.get(
                                  'simulation_movement_quantities')
    simulation_movement_resources = sequence.get(
                                   'simulation_movement_resources')
    simulation_movement_paths = sequence.get(
                                       'simulation_movement_paths')
    simulation_movement_section_paths = sequence.get(
                               'simulation_movement_section_paths')
    
    for simulation_movement in simulation_movement_list :
      path=simulation_movement.getPath()
      self.assertEquals(
        simulation_movement.getQuantity(),
        simulation_movement_quantities[path]
      )
      self.assertEquals(
        simulation_movement.getResource(),
        simulation_movement_resources[path]
      )
      self.assertEquals(
        (simulation_movement.getSource(), simulation_movement.getDestination()),
        simulation_movement_paths[path]
      )
      self.assertEquals(
           ( simulation_movement.getSourceSection(),
             simulation_movement.getDestinationSection()),
        simulation_movement_section_paths[path]
      )
  
1175 1176 1177 1178
  def stepCheckPaymentRuleIsApplied(self, sequence, **kw) :
    """ checks that a payment rule is applied for the total amount
      of receivable """
    # TODO
Jérome Perrin's avatar
Jérome Perrin committed
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188
  
  def stepPlanInvoice(self, sequence, **kw) :
    """ put the invoice in the `planned` state, which will 
      start the simulation process. """
    invoice = sequence.get('invoice')
    self.getPortal().portal_workflow.doActionFor(
      invoice, 'plan_action',
      wf_id = 'accounting_workflow'
    )
    self.assertEquals(invoice.getSimulationState(), 'planned')
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 1226 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

  def stepConfirmInvoice(self, sequence, **kw) :
    """ put the invoice in the `confirmed` state, which will 
      start the delivery builder """
    invoice = sequence.get('invoice')
    self.getPortal().portal_workflow.doActionFor(
      invoice, 'confirm_action',
      wf_id = 'accounting_workflow'
    )
    self.assertEquals(invoice.getSimulationState(), 'confirmed')
  
  def stepCheckAccountingLinesCoherantWithSimulation(self, sequence, **kw) :
    """ checks that accounting lines are created on the sale invoice 
    transaction """
    invoice  = sequence.get('invoice')
    vendor   = sequence.get('vendor')
    client   = sequence.get('client')
    currency = sequence.get('currency')
    invoice_line = sequence.get('invoice_line')
    simulation_movement_list = sequence.get('simulation_movement_list')
    invoice_transaction_rule_cell = sequence.get(
                          'invoice_transaction_rule_cell')
    invoice_transaction_line_list = invoice.contentValues(
        filter = {'portal_type':
                  self.sale_invoice_transaction_line_portal_type})
    self.assertEquals( len(invoice_transaction_line_list),
                       len(simulation_movement_list))
    
    simulation_movement_found = {}
    for invoice_transaction_line in invoice_transaction_line_list :
      self.assertEquals( invoice_transaction_line.getSourceSection(),
                         vendor.getRelativeUrl())
      self.assertEquals( invoice_transaction_line.getDestinationSection(),
                         client.getRelativeUrl())
      self.assertEquals( invoice_transaction_line.getResource(),
                         currency.getRelativeUrl())
      for simulation_movement in simulation_movement_list :
        if simulation_movement.getSource() == \
                            invoice_transaction_line.getSource() :
          simulation_movement_found[simulation_movement.getSource()] = 1
          self.assertEquals(simulation_movement.getQuantity(),
                            invoice_transaction_line.getQuantity())
          self.assertEquals(simulation_movement.getSourceCredit(),
                            invoice_transaction_line.getSourceCredit())
          self.assertEquals(simulation_movement.getSourceDebit(),
                            invoice_transaction_line.getSourceDebit())
          self.assertEquals(simulation_movement.getDelivery(),
                            invoice_transaction_line.getRelativeUrl())
      self.assert_(len(simulation_movement_found.keys()), 3)
  
  
  def stepCheckAccountingLinesCreatedForSimpleInvoice(
            self, sequence, **kw) :
    """ Checks that accounting lines are created on the sale invoice 
    transaction and that all movement are correctly aggregated.
    The price of the invoice was 100, it should result in the following
    accounting layout :
    
      ===============   =======   =======
      account           Debit     Credit
      ===============   =======   =======
      income                       100
      collected_vat                 19.60
      receivable         119.60 
      ===============   =======   =======
    """
    invoice  = sequence.get('invoice')
    vendor   = sequence.get('vendor')
    client   = sequence.get('client')
    currency = sequence.get('currency')
    invoice_lines = sequence.get('invoice_lines')
    
    invoice_transaction_line_list = invoice.contentValues(
        filter = {'portal_type': self.sale_invoice_transaction_line_portal_type})
    self.assertEquals(len(invoice_transaction_line_list), 3)
    
    accounting_lines_layout = {
      'income'            : (0, 100),
      'collected_vat'     : (0, 19.60),
      'receivable'        : (119.60, 0),
    }
  
    for invoice_transaction_line in invoice_transaction_line_list :
Jérome Perrin's avatar
Jérome Perrin committed
1272 1273
      debit, credit = accounting_lines_layout[
                            invoice_transaction_line.getSourceId()]
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
      self.assertEquals(debit, invoice_transaction_line.getSourceDebit())
      self.assertEquals(credit, invoice_transaction_line.getSourceCredit())
  
  def stepCheckAccountingLinesCreatedForMultiLineInvoice(
            self, sequence, **kw) :
    """ Checks that accounting lines are created on the sale invoice 
    transaction and that all movement are correctly aggregated.
    The price of the invoice was 1100, it should result in the following
    accounting layout :
    
      ===============   =======   =======
      account           Debit     Credit
      ===============   =======   =======
      income                       100
      income_barebone              1000
      collected_vat                215.60
      receivable        1315.60 
      ===============   =======   =======
    """
    invoice  = sequence.get('invoice')
    vendor   = sequence.get('vendor')
    client   = sequence.get('client')
    currency = sequence.get('currency')
    invoice_lines = sequence.get('invoice_lines')
    
    invoice_transaction_line_list = invoice.contentValues(
        filter = {'portal_type': self.sale_invoice_transaction_line_portal_type})
    self.assertEquals(len(invoice_transaction_line_list), 4)
    
    accounting_lines_layout = {
      'income'            : (0, 100),
      'income_barebone'   : (0, 1000),
      'collected_vat'     : (0, 215.60),
      'receivable'        : (1315.60, 0),
    }
  
    for invoice_transaction_line in invoice_transaction_line_list :
Jérome Perrin's avatar
Jérome Perrin committed
1311 1312
      debit, credit = accounting_lines_layout[
                                    invoice_transaction_line.getSourceId()]
1313 1314 1315
      self.assertEquals(debit, invoice_transaction_line.getSourceDebit())
      self.assertEquals(credit, invoice_transaction_line.getSourceCredit())
      
Jérome Perrin's avatar
Jérome Perrin committed
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356

  def stepRebuildAndCheckNothingIsCreated(self, sequence, **kw) :
    """ Calls the DeliveryBuilder again and checks that the accounting module
    remains unchanged.
    """
    accounting_transaction_count = len(self.getAccountingModule().objectIds())
    accounting_lines_dict = {}
    for transaction in self.getAccountingModule().objectValues():
      transaction_dict = {}
      for accounting_line in transaction.objectValues() :
        if accounting_line.getPortalType() != \
                          self.sale_invoice_line_portal_type :
          transaction_dict[accounting_line.getId()] = \
                accounting_line.getTotalQuantity()
      accounting_lines_dict[transaction.getId()] = transaction_dict
  
    # reindex the simulation for testing purposes
    self.getSimulationTool().recursiveReindexObject()
    self.tic()
    delivery_tool = self.getPortal().portal_deliveries
    # and build again ...
    delivery_tool.sale_invoice_transaction_builder.build()
    if hasattr(delivery_tool, 'pay_sheet_transaction_builder') :
      # TODO: conflict with pay_sheet_transaction_builder must be tested too
      delivery_tool.pay_sheet_transaction_builder.build()
    self.tic()
    
    # nothing should have changed
    self.assertEquals(accounting_transaction_count,
            len(self.getAccountingModule().objectIds()))
      
    for transaction in self.getAccountingModule().objectValues() :
      transaction_dict = accounting_lines_dict[transaction.getId()]
      for accounting_line in transaction.objectValues() :
        if accounting_line.getPortalType() != \
                          self.sale_invoice_line_portal_type :
          self.assertEquals(
              transaction_dict[accounting_line.getId()],
              accounting_line.getTotalQuantity())
    
    
1357 1358 1359 1360
  def test_01_HasEverything(self, quiet=0, run=RUN_ALL_TESTS):
    """ check necessary tools and modules are present. """
    if not run:
      return
1361 1362
    if not quiet:
      ZopeTestCase._print('\nTest Has Everything ')
1363
      LOG('Testing... ', INFO, 'testHasEverything')
1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375
    self.failUnless(self.getCategoryTool() != None)
    self.failUnless(self.getSimulationTool() != None)
    self.failUnless(self.getTypeTool() != None)
    self.failUnless(self.getSqlConnection() != None)
    self.failUnless(self.getCatalogTool() != None)
    self.failUnless(self.getRuleTool() != None)
    self.failUnless(self.getAccountModule() != None)
    self.failUnless(self.getAccountingModule() != None)
    self.failUnless(self.getOrganisationModule() != None)
    self.failUnless(self.getProductModule() != None)
    self.failUnless(self.getCurrencyModule() != None)

1376 1377
  def test_02_UpdateInvoiceTransactionRuleMatrix(self, quiet=0,
                                              run=RUN_ALL_TESTS):
Jérome Perrin's avatar
Jérome Perrin committed
1378
    """ test edition of matrix and rule.
1379 1380
    Try to update the matrix after adding some predicates, 
    and check if all objects were created
1381
    """
1382 1383
    if not run:
      return
1384 1385 1386
    if not quiet:
      message = 'Test Update Invoice Transaction Rule Matrix'
      ZopeTestCase._print('\n%s ' % message)
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
      LOG('Testing... ', INFO, message)
    
    self.playSequence("""
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepTic
      stepCheckAddPredicate
      stepTic
      stepCheckRemovePredicate
      stepTic
      stepCheckRestoreOriginalPredicates
    """)

  def test_03_invoiceTransactionRule_getMatchingCell(self,
                                    quiet=0, run=RUN_ALL_TESTS):
Jérome Perrin's avatar
Jérome Perrin committed
1402
    """ test predicates for the cells of invoice transaction rule
1403
    """
1404 1405
    if not run:
      return
1406
    if not quiet:
1407
      message = 'Test Invoice Transaction Rule getMatchingCell '
1408
      ZopeTestCase._print('\n%s ' % message)
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
      LOG('Testing... ', INFO, message)
    
    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepTic
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateProducts
      stepTic
      stepCreateDummyInvoice
      stepCreateMatchableSaleInvoiceMovements
      stepCheckMatchableSaleInvoiceMovements
      stepCreateNotMatchableSaleInvoiceMovements
      stepCheckNotMatchableSaleInvoiceMovements
    """)
    
  def test_04_SimpleInvoice(self, quiet=0, run=RUN_ALL_TESTS):
Jérome Perrin's avatar
Jérome Perrin committed
1428
    """ Simple Invoice.
1429 1430
    Try to expand an invoice containing only one simple Invoice Line.
    Check that the build is correct.
1431
    """
1432 1433
    if not run:
      return
1434
    if not quiet:
1435
      message = 'Test Simple Invoice Rule'
1436
      ZopeTestCase._print('\n%s ' % message)
1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoice
      stepPlanInvoice
      stepTic
      stepCheckFirstRuleIsApplied 
      stepCheckPaymentRuleIsApplied
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCoherantWithSimulation
      """ )

  def test_04b_SimpleInvoiceConfirm(self, quiet=0, run=RUN_ALL_TESTS):
Jérome Perrin's avatar
Jérome Perrin committed
1461 1462
    """  Same test as SimpleInvoice but directly confirm the invoice
    without planning it """
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (without plan)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoice
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
Jérome Perrin's avatar
Jérome Perrin committed
1485
      stepRebuildAndCheckNothingIsCreated
1486 1487
      """ )
  
Jérome Perrin's avatar
Jérome Perrin committed
1488 1489
  def test_04c_SimpleInvoiceTwoLines(self, quiet=0, run=RUN_ALL_TESTS):
    """ Simple Invoice, 2 lines.
1490 1491 1492 1493 1494 1495
    Same test as SimpleInvoice but use 2 lines of quantity 5 instead of
    1 line of quantity 10.
    """
    if not run:
      return
    if not quiet:
Jérome Perrin's avatar
Jérome Perrin committed
1496
      message = 'Test Simple Invoice Rule (with 2 lines)'
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoiceTwoLines
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
Jérome Perrin's avatar
Jérome Perrin committed
1515
      stepRebuildAndCheckNothingIsCreated
1516 1517
      """ )
      
Jérome Perrin's avatar
Jérome Perrin committed
1518 1519 1520 1521
  def test_04d_SimpleInvoiceTwoCells(self, quiet=0, run=RUN_ALL_TESTS):
    """ Simple Invoice, 2 cells.
    Same test as SimpleInvoice but use 2 cells of quantity 5 instead of
    1 line of quantity 10.
1522
    """
Jérome Perrin's avatar
Jérome Perrin committed
1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 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 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 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (with 2 cells)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoiceTwoCells
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )
   
  # next 5 tests will check update of applied rules. 
  def test_05a_SimpleInvoiceReExpandAddLine(self, quiet=0,
        run=RUN_BROKEN_TESTS):
    """ Add a new line then updateAppliedRule.
    Create an empty invoice, plan, add a line so that this
    invoice is the same as `SimpleInvoice`, confirm it then check
    accounting lines
    """
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (add invoice line and reexpand)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateEmptyInvoice
      stepPlanInvoice
      stepTic
      stepAddInvoiceLine
      stepUpdateAppliedRule
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )
      
  def test_05b_SimpleInvoiceReExpandEditLine(self, quiet=0,
              run = RUN_BROKEN_TESTS):
    """ Tests that editing a line updates simulation correctly """
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (edit line and reexpand)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateOtherSimpleSaleInvoice
      stepPlanInvoice
      stepTic
      stepCollectSimulationMovements
      stepEditInvoiceLine
      stepUpdateAppliedRule
      stepConfirmInvoice
      stepTic
      stepCheckSimulationMovements
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )

  def test_05c_SimpleInvoiceReExpandDeleteLine(
                        self, quiet=0, run=RUN_ALL_TESTS):
    """ Tests that removing a line updates simulation correctly """
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (delete line and reexpand)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoice
      stepAddInvoiceLine
      stepPlanInvoice
      stepTic
      stepDeleteInvoiceLine
      stepUpdateAppliedRule
      stepTic
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )

  def test_05d_SimpleInvoiceReExpandCreateCell(self, quiet=0,
                    run=RUN_BROKEN_TESTS):
    """ Tests that replacing a line by cells updates simulation correctly """
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (add cells in a line and reexpand)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateOtherSimpleSaleInvoice
      stepPlanInvoice
      stepTic
      stepAddCellsInInvoiceLine
      stepUpdateAppliedRule
      stepTic
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )

  def test_05e_SimpleInvoiceExpandManyTimes(
                                self, quiet=0, run=RUN_ALL_TESTS):
    """ Tests that updating an applied rule many times doesn't break the
    build """
    if not run:
      return
    if not quiet:
      message = 'Test Simple Invoice Rule (many updateAppliedRule)'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepCreateNotebookFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateSimpleSaleInvoice 
      stepPlanInvoice
      stepTic """ +
      ("""
      stepEditInvoiceLine
      stepUpdateAppliedRule
      stepTic""" * 4) +
      """
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForSimpleInvoice
      stepRebuildAndCheckNothingIsCreated
      """ )

  def test_06_MultiLineInvoice(self, quiet=0, run=RUN_ALL_TESTS):
    """ Multiple lines invoice.
1724
    Try to expand an invoice containing multiples Invoice Line.
Jérome Perrin's avatar
Jérome Perrin committed
1725
    Check that the build is correct, ie similar movements are aggregated.
1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752
    """
    if not run:
      return
    if not quiet:
      message = 'Test Multi Line Invoice Rule'
      ZopeTestCase._print('\n%s ' % message)
      LOG('Testing... ', INFO, message)

    self.playSequence("""
      stepCreateAccounts
      stepCreateEntities
      stepCreateCurrencies
      stepCreateProducts
      stepCreateSaleInvoiceTransactionRule
      stepTic
      stepUpdateSaleInvoiceTransactionRuleMatrix
      stepTic
      stepCreateNotebookFranceCell
      stepCreateBareboneFranceCell
      stepTic
      stepClearSimulation
      stepClearAccountingModule
      stepCreateMultiLineSaleInvoice
      stepPlanInvoice
      stepConfirmInvoice
      stepTic
      stepCheckAccountingLinesCreatedForMultiLineInvoice
Jérome Perrin's avatar
Jérome Perrin committed
1753
      stepRebuildAndCheckNothingIsCreated
1754 1755
      """ )
    
Jérome Perrin's avatar
Jérome Perrin committed
1756 1757 1758
  def test_07_PaymentRuleForSaleInvoice(self, quiet=0, run=RUN_ALL_TESTS):
    """ Payment Rule.
      checks the payment rule is applied on sale invoice simulation
1759 1760 1761 1762 1763 1764
      movement. """
    # checks :
    #   date from trade condition
    #   quantity from sum of receivable movement
    #   link to sale invoice
     
1765
if __name__ == '__main__':
1766
  framework()
1767
else:
1768 1769 1770 1771 1772
  import unittest
  def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestAccountingRules))
    return suite
Jérome Perrin's avatar
Jérome Perrin committed
1773