testAccounting.py 71.7 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
#############################################################################
#
# 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.
#
##############################################################################

29
"""Tests some accounting functionality.
30 31 32

"""

33
import unittest
34
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
35
from Products.ERP5Type.tests.utils import reindex
36
from Products.DCWorkflow.DCWorkflow import ValidationFailed
37 38
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.Sequence import Sequence, SequenceList
39
from Products.ERP5.Document.Delivery import Delivery
40
from DateTime import DateTime
41

42 43 44
SOURCE = 'source'
DESTINATION = 'destination'
RUN_ALL_TESTS = 1
Jérome Perrin's avatar
Jérome Perrin committed
45
QUIET = 1
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
# Associate transaction portal type to the corresponding line portal type.
transaction_to_line_mapping = {
    'Accounting Transaction': 'Accounting Transaction Line',
    'Balance Transaction': 'Balance Transaction Line',
    'Purchase Invoice Transaction': 'Purchase Invoice Transaction Line',
    'Sale Invoice Transaction': 'Sale Invoice Transaction Line',
    'Payment Transaction': 'Accounting Transaction Line',
    'Closing Transaction': 'Closing Transaction Line',
  }


class AccountingTestCase(ERP5TypeTestCase):
  """A test case for all accounting tests.

  Like in erp5_accounting_ui_test, the testing environment is made of:

  Currencies:
    * EUR with precision 2
    * USD with precision 2
    * JPY with precision 0

  Regions:
    * region/europe/west/france
    
  Group:
    * group/demo_group
    * group/demo_group/sub1
    * group/demo_group/sub2
    * group/client
    * group/vendor'
    
  Payment Mode:
    * payment_mode/cash
    * payment_mode/check
  
  Organisations:
    * `self.section` an organisation in region europe/west/france
    using EUR as default currency, without any openned accounting period by
    default. This organisation is member of group/demo_group/sub1
    * self.client_1, self.client_2 & self.vendor, some other organisations
  
  Accounts:
      All accounts are associated to a virtual GAP category named "My Accounting
    Standards":
    * bank
    * collected_vat
    * equity
    * fixed_assets
    * goods_purchase
    * goods_sales
    * payable
    * receivable
    * refundable_vat
    * stocks
  
  Tests starts with a preference activated for self.my_organisation, logged in
  as a user with Assignee, Assignor and Author role.

  All documents created appart from this configuration will be deleted in
  teardown. So users of this test case are encouraged to create new documents
  rather than modifying default documents. 
  """
  
  username = 'username'

  @reindex
113 114
  def _makeOne(self, portal_type='Accounting Transaction', lines=None,
               simulation_state='draft', **kw):
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
    """Creates an accounting transaction, and edit it with kw.
    
    The default settings is for self.section.
    You can pass a list of mapping as lines, then lines will be created
    using this information.
    """
    created_by_builder = kw.pop('created_by_builder', lines is not None)
    kw.setdefault('start_date', DateTime())
    kw.setdefault('resource', 'currency_module/euro')
    if portal_type in ('Purchase Invoice Transaction', ):
      if 'destination_section' not in kw:
        kw.setdefault('destination_section_value', self.section)
    else:
      if 'source_section' not in kw:
        kw.setdefault('source_section_value', self.section)
    tr = self.accounting_module.newContent(portal_type=portal_type,
                         created_by_builder=created_by_builder, **kw)
    if lines:
      for line in lines:
        line.setdefault('portal_type', transaction_to_line_mapping[portal_type])
        tr.newContent(**line)
136 137 138 139 140 141 142 143
    if simulation_state == 'planned':
      tr.plan()
    elif simulation_state == 'confirmed':
      tr.confirm()
    elif simulation_state in ('stopped', 'delivered'):
      tr.stop()
      if simulation_state == 'delivered':
        tr.deliver()
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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
    return tr


  def login(self):
    """login with Assignee, Assignor & Author roles."""
    uf = self.getPortal().acl_users
    uf._doAddUser(self.username, '', ['Assignee', 'Assignor', 'Author'], [])
    user = uf.getUserById(self.username).__of__(uf)
    newSecurityManager(None, user)


  def setUp(self):
    """Setup the fixture.
    """
    ERP5TypeTestCase.setUp(self)
    self.portal = self.getPortal()
    self.account_module = self.portal.account_module
    self.accounting_module = self.portal.accounting_module
    self.organisation_module = self.portal.organisation_module
    self.person_module = self.portal.person_module
    self.currency_module = self.portal.currency_module
    self.section = self.organisation_module.my_organisation
    
    # make sure documents are validated
    for module in (self.account_module, self.organisation_module,
                   self.person_module):
      for doc in module.objectValues():
        doc.validate()
    
    # and the preference enabled
    self.portal.portal_preferences.accounting_zuite_preference\
                      .manage_addLocalRoles(self.username, ('Auditor', ))
    self.portal.portal_preferences.accounting_zuite_preference.enable()
    
    # and all this available to catalog
    get_transaction().commit()
    self.tic()


  def tearDown(self):
    """Remove all documents, except the default ones.
    """
    get_transaction().abort()
    self.accounting_module.manage_delObjects(
                      list(self.accounting_module.objectIds()))
    self.organisation_module.manage_delObjects([x for x in 
          self.accounting_module.objectIds() if x not in ('my_organisation',
            'client_1', 'client_2', 'client_3')])
    self.organisation_module.my_organisation.manage_delObjects([x.getId()
        for x in self.organisation_module.my_organisation.objectValues(
                                   portal_type='Accounting Period')])
    self.person_module.manage_delObjects([x for x in 
          self.person_module.objectIds() if x not in ('john_smith',)])
    self.account_module.manage_delObjects([x for x in 
          self.account_module.objectIds() if x not in ('bank', 'collected_vat',
            'equity', 'fixed_assets', 'goods_purchase', 'goods_sales',
            'payable', 'receivable', 'refundable_vat', 'stocks',)])
    self.portal.portal_preferences.manage_delObjects([x for x in
          self.portal.portal_preferences.objectIds() if x not in
          ('accounting_zuite_preference', 'default_site_preference')])
    self.portal.portal_simulation.manage_delObjects(list(
          self.portal.portal_simulation.objectIds()))
    get_transaction().commit()
    self.tic()
    ERP5TypeTestCase.tearDown(self)


  def getBusinessTemplateList(self):
    """Returns list of BT to be installed."""
    return ('erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_accounting',
            'erp5_accounting_ui_test')

216

217
class TestAccounting(ERP5TypeTestCase):
218 219
  """The first test for Accounting
  """
220 221 222 223 224 225 226 227 228
  def getAccountingModule(self):
    return getattr(self.getPortal(), 'accounting_module',
           getattr(self.getPortal(), 'accounting', None))
  
  def getAccountModule(self) :
    return getattr(self.getPortal(), 'account_module',
           getattr(self.getPortal(), 'account', None))
  
  # XXX
Jérome Perrin's avatar
Jérome Perrin committed
229
  def playSequence(self, sequence_string, quiet=1) :
230 231
    sequence_list = SequenceList()
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
232
    sequence_list.play(self, quiet=quiet)
233
  
234
  account_portal_type           = 'Account'
235
  accounting_period_portal_type = 'Accounting Period'
236 237
  accounting_transaction_portal_type = 'Accounting Transaction'
  accounting_transaction_line_portal_type = 'Accounting Transaction Line'
238 239 240 241 242 243 244 245 246 247 248 249
  currency_portal_type          = 'Currency'
  organisation_portal_type      = 'Organisation'
  sale_invoice_portal_type      = 'Sale Invoice Transaction'
  sale_invoice_line_portal_type = 'Sale Invoice Line' 
  sale_invoice_transaction_line_portal_type = 'Sale Invoice Transaction Line'
  sale_invoice_cell_portal_type = 'Invoice Cell'
  purchase_invoice_portal_type      = 'Purchase Invoice Transaction'
  purchase_invoice_line_portal_type = 'Purchase Invoice Line' 
  purchase_invoice_transaction_line_portal_type = \
                'Purchase Invoice Transaction Line'
  purchase_invoice_cell_portal_type = 'Invoice Cell'

250 251 252
  start_date = DateTime(2004, 01, 01)
  stop_date  = DateTime(2004, 12, 31)

253 254
  default_region = 'europe/west/france'

255 256 257
  def getTitle(self):
    return "Accounting"
  
258 259
  def afterSetUp(self):
    """Prepare the test."""
260 261 262 263 264
    self.portal = self.getPortal()
    self.workflow_tool = self.portal.portal_workflow
    self.organisation_module = self.portal.organisation_module
    self.account_module = self.portal.account_module
    self.accounting_module = self.portal.accounting_module
265
    self.createCategories()
266 267 268
    self.createCurrencies()
    self.createEntities()
    self.createAccounts()
269 270 271 272 273 274 275 276

    # setup preference for the vendor group
    self.pref = self.portal.portal_preferences.newContent(
         portal_type='Preference', preferred_section_category='group/vendor',
         preferred_accounting_transaction_section_category='group/vendor',
         priority=3 )
    self.workflow_tool.doActionFor(self.pref, 'enable_action')

277 278
    self.login()

279 280 281 282 283 284 285 286 287 288
  def beforeTearDown(self):
    """Cleanup for next test.
    All tests uses the same accounts and same entities, so we just cleanup
    accounting module and simulation. """
    get_transaction().abort()
    for folder in (self.accounting_module, self.portal.portal_simulation):
      folder.manage_delObjects([i for i in folder.objectIds()])
    get_transaction().commit()
    self.tic()

289 290 291 292 293 294 295 296 297 298 299
  def login(self) :
    """sets the security manager"""
    uf = self.getPortal().acl_users
    uf._doAddUser('alex', '', ['Member', 'Assignee', 'Assignor',
                               'Auditor', 'Author', 'Manager'], [])
    user = uf.getUserById('alex').__of__(uf)
    newSecurityManager(None, user)
  
  def createCategories(self):
    """Create the categories for our test. """
    # create categories
300
    for cat_string in self.getNeededCategoryList():
301 302
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
303 304
      for cat in cat_string.split("/")[1:]:
        if not cat in path.objectIds():
305
          path = path.newContent(
306 307 308 309 310 311
            portal_type='Category',
            id=cat,
            immediate_reindex=1)
        else:
          path = path[cat]
          
312 313 314 315 316 317 318
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
                
  def getNeededCategoryList(self):
319
    """Returns a list of categories that should be created."""
320
    return ('group/client', 'group/vendor/sub1', 'group/vendor/sub2',
321
            'payment_mode/check', 'region/%s' % self.default_region, )
322 323
  
  def getBusinessTemplateList(self):
324
    """Returns list of BT to be installed."""
325
    return ('erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_accounting', )
326 327

  def stepTic(self, **kw):
328
    """Flush activity queue. """
329
    self.tic()
330 331 332 333
  
  def createEntities(self):
    """Create entities. """
    self.client = self.getOrganisationModule().newContent(
334
        title = 'Client',
335
        portal_type = self.organisation_portal_type,
336
        group = "client",
337
        price_currency = "currency_module/USD")
338
    self.vendor = self.getOrganisationModule().newContent(
339
        title = 'Vendor',
340
        portal_type = self.organisation_portal_type,
341
        group = "vendor/sub1",
342 343
        price_currency = "currency_module/EUR")
    self.other_vendor = self.getOrganisationModule().newContent(
344
        title = 'Other Vendor',
345
        portal_type = self.organisation_portal_type,
346
        group = "vendor/sub2",
347
        price_currency = "currency_module/EUR")
348
    # validate entities
349
    for entity in (self.client, self.vendor, self.other_vendor):
350 351
      entity.setRegion(self.default_region)
      self.getWorkflowTool().doActionFor(entity, 'validate_action')
352 353
    get_transaction().commit()
    self.tic()
354
    
355 356 357 358 359 360 361
  def stepCreateEntities(self, sequence, **kw) :
    """Create entities. """
    # TODO: remove this method
    sequence.edit( client=self.client,
                   vendor=self.vendor,
                   other_vendor=self.other_vendor,
                   organisation=self.vendor )
362 363 364 365 366 367 368 369 370 371 372 373
  
  def stepCreateAccountingPeriod(self, sequence, **kw):
    """Creates an Accounting Period for the Organisation."""
    organisation = sequence.get('organisation')
    start_date = self.start_date
    stop_date = self.stop_date
    accounting_period = organisation.newContent(
      portal_type = self.accounting_period_portal_type,
      start_date = start_date, stop_date = stop_date )
    sequence.edit( accounting_period = accounting_period,
                   valid_date_list = [ start_date, start_date+1, stop_date],
                   invalid_date_list = [start_date-1, stop_date+1] )
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
  def stepUseValidDates(self, sequence, **kw):
    """Puts some valid dates in sequence."""
    sequence.edit(date_list = sequence.get('valid_date_list'))
    
  def stepUseInvalidDates(self, sequence, **kw):
    """Puts some invalid dates in sequence."""
    sequence.edit(date_list = sequence.get('invalid_date_list'))
  
  def stepOpenAccountingPeriod(self, sequence, **kw):
    """Opens the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
    self.getPortal().portal_workflow.doActionFor(
                        accounting_period,
                        'plan_action' )
    self.assertEquals(accounting_period.getSimulationState(),
                      'planned')
                      
  def stepConfirmAccountingPeriod(self, sequence, **kw):
    """Confirm the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
    self.getPortal().portal_workflow.doActionFor(
                        accounting_period,
                        'confirm_action' )
    self.assertEquals(accounting_period.getSimulationState(),
                      'confirmed')

401 402 403 404 405 406 407
  def stepCheckAccountingPeriodRefusesClosing(self, sequence, **kw):
    """Checks the Accounting Period refuses closing."""
    accounting_period = sequence.get('accounting_period')
    self.assertRaises(ValidationFailed,
          self.getPortal().portal_workflow.doActionFor,
          accounting_period, 'confirm_action' )

408 409 410 411 412
  def stepDeliverAccountingPeriod(self, sequence, **kw):
    """Deliver the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
    self.getPortal().portal_workflow.doActionFor(
                        accounting_period,
413 414 415 416 417 418 419
                        'close_action' )
    self.assertEquals(accounting_period.getSimulationState(),
                      'closing')
    
  def stepCheckAccountingPeriodDelivered(self, sequence, **kw):
    """Check the Accounting Period is delivered."""
    accounting_period = sequence.get('accounting_period')
420 421
    self.assertEquals(accounting_period.getSimulationState(),
                      'delivered')
422
    
423 424 425 426 427 428 429 430
  def createCurrencies(self):
    """Create some currencies.
    This script will reuse existing currencies, because we want currency ids to
    be stable, as we use them as categories.
    """
    currency_module = self.getCurrencyModule()
    if not hasattr(currency_module, 'EUR'):
      self.EUR = currency_module.newContent(
431
          portal_type = self.currency_portal_type,
432 433
          reference = "EUR", id = "EUR" )
      self.USD = currency_module.newContent(
434
          portal_type = self.currency_portal_type,
435 436
          reference = "USD", id = "USD" )
      self.YEN = currency_module.newContent(
437
          portal_type = self.currency_portal_type,
438 439 440 441 442 443 444 445 446 447 448 449
          reference = "YEN", id = "YEN" )
      get_transaction().commit()
      self.tic()
    else:
      self.EUR = currency_module.EUR
      self.USD = currency_module.USD
      self.YEN = currency_module.YEN

  def stepCreateCurrencies(self, sequence, **kw) :
    """Create some currencies. """
    # TODO: remove
    sequence.edit(EUR=self.EUR, USD=self.USD, YEN=self.YEN)
450
  
451 452 453 454
  def createAccounts(self):
    """Create some accounts.
    """
    receivable = self.receivable_account = self.getAccountModule().newContent(
455 456 457
          title = 'receivable',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable' )
458
    payable = self.payable_account = self.getAccountModule().newContent(
459 460 461
          title = 'payable',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable' )
462
    expense = self.expense_account = self.getAccountModule().newContent(
463 464 465
          title = 'expense',
          portal_type = self.account_portal_type,
          account_type = 'expense' )
466
    income = self.income_account = self.getAccountModule().newContent(
467 468 469
          title = 'income',
          portal_type = self.account_portal_type,
          account_type = 'income' )
470 471
    collected_vat = self.collected_vat_account = self\
                                        .getAccountModule().newContent(
472 473 474
          title = 'collected_vat',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable/collected_vat' )
475 476
    refundable_vat = self.refundable_vat_account = self\
                                        .getAccountModule().newContent(
477 478 479
          title = 'refundable_vat',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable/refundable_vat' )
480
    bank = self.bank_account = self.getAccountModule().newContent(
481 482 483 484 485 486 487 488 489 490 491 492 493
          title = 'bank',
          portal_type = self.account_portal_type,
          account_type = 'asset/cash/bank')
    
    # set mirror accounts.
    receivable.setDestinationValue(payable)
    payable.setDestinationValue(receivable)
    expense.setDestinationValue(income)
    income.setDestinationValue(expense)
    collected_vat.setDestinationValue(refundable_vat)
    refundable_vat.setDestinationValue(collected_vat)
    bank.setDestinationValue(bank)
    
494 495 496 497 498 499 500
    self.account_list = [ receivable,
                          payable,
                          expense,
                          income,
                          collected_vat,
                          refundable_vat,
                          bank ]
501

502
    for account in self.account_list :
503
      account.validate()
504
      self.failUnless('Site Error' not in account.view())
505
      self.assertEquals(account.getValidationState(), 'validated')
506 507
    get_transaction().commit()
    self.tic()
508

509 510 511 512 513 514 515 516 517 518 519
  def stepCreateAccounts(self, sequence, **kw) :
    """Create necessary accounts. """
    # XXX remove me !  
    sequence.edit( receivable_account=self.receivable_account,
                   payable_account=self.payable_account,
                   expense_account=self.expense_account,
                   income_account=self.income_account,
                   collected_vat_account=self.collected_vat_account,
                   refundable_vat_account=self.refundable_vat_account,
                   bank_account=self.bank_account,
                   account_list=self.account_list )
520 521 522 523 524 525 526 527 528 529 530 531 532
  
  def stepCreateAccountingTransactionAndCheckMirrorAccount(self,
                                          sequence, **kw):
    """Check that mirror account are set automatically. """
    account_list = sequence.get('account_list')
    
    for account in account_list :
      self.assertNotEquals(account.getDestinationValue(), None)
    
    transaction = self.getAccountingModule().newContent(
      portal_type = self.accounting_transaction_portal_type,
      source_section_value = sequence.get('client'),
      resource_value = sequence.get('EUR'),
533
      created_by_builder = 1,
534 535 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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
    )
    
    # setting both source and destination shouldn't use mirror accounts
    destination = sequence.get('receivable_account')
    for account in account_list :
      transaction_line = transaction.newContent(
        portal_type = self.accounting_transaction_line_portal_type,
        source = account.getRelativeUrl(),
        destination = destination.getRelativeUrl(),
      )
      self.assertEquals( destination.getRelativeUrl(),
                         transaction_line.getDestination() )
    
    # setting only a source must use mirror account as destination
    for account in account_list :
      transaction_line = transaction.newContent(
        portal_type = self.accounting_transaction_line_portal_type,
        source = account.getRelativeUrl(),
      )
      self.assertEquals( account.getDestination(),
                         transaction_line.getDestination() )
    
    # editing the destination later should not change the source once
    # the mirror account has been set.
    account = sequence.get('receivable_account')
    destination = sequence.get('bank_account')
    another_destination = sequence.get('expense_account')
    account.setDestinationValueList(account_list)
    
    transaction_line = transaction.newContent(
      portal_type = self.accounting_transaction_line_portal_type,
      source = account.getRelativeUrl(), )
    automatically_set_destination = transaction_line.getDestinationValue()
    # get another account.
    if automatically_set_destination == destination :
      forced_destination = destination
    else :
      forced_destination = another_destination
    # set all other accounts as mirror account to this one.
    forced_destination.setDestinationValueList(account_list)
    
    # change the destination and check the source didn't change.
    transaction_line.edit(destination = forced_destination.getRelativeUrl())
    self.assertEquals( transaction_line.getSourceValue(), account )
    
579 580 581 582 583 584 585 586 587 588 589 590 591 592
  def getInvoicePropertyList(self):
    """Returns the list of properties for invoices, stored as 
      a list of dictionnaries. """
    # source currency is EUR
    # destination currency is USD
    return [
      # in currency of destination, converted for source
      { 'income' : -200,             'source_converted_income' : -180,
        'collected_vat' : -40,       'source_converted_collected_vat' : -36,
        'receivable' : 240,          'source_converted_receivable' : 216,
        'currency' : 'currency_module/USD' },
      
      # in currency of source, converted for destination
      { 'income' : -100,        'destination_converted_expense' : -200,
593
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
594 595 596 597
        'receivable' : 90,      'destination_converted_payable' : 100,
        'currency' : 'currency_module/EUR' },
      
      { 'income' : -100,        'destination_converted_expense' : -200,
598
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
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
        'receivable' : 90,      'destination_converted_payable' : 100,
        'currency' : 'currency_module/EUR' },
      
      # in an external currency, converted for both source and dest.
      { 'income' : -300,
                    'source_converted_income' : -200,
                    'destination_converted_expense' : -400,
        'collected_vat' : 40,
                    'source_converted_collected_vat' : 36,
                    'destination_converted_refundable_vat' : 50,
        'receivable' : 260,
                    'source_converted_receivable' : 164,
                    'destination_converted_payable': 350,
        'currency' : 'currency_module/YEN' },
      
      # currency of source, not converted for destination -> 0
      { 'income' : -100,
        'collected_vat' : -20,
        'receivable' : 120,
        'currency' : 'currency_module/EUR' },
      
    ]
  
  def stepCreateInvoices(self, sequence, **kw) :
    """Create invoices with properties from getInvoicePropertyList. """
    invoice_prop_list = self.getInvoicePropertyList()
    invoice_list = []
626 627 628
    date_list = sequence.get('date_list')
    if not date_list : date_list = [ DateTime(2004, 12, 31) ]
    i = 0
629
    for invoice_prop in invoice_prop_list :
630 631
      i += 1
      date = date_list[i % len(date_list)]
632 633 634 635 636 637 638
      invoice = self.getAccountingModule().newContent(
          portal_type = self.sale_invoice_portal_type,
          source_section_value = sequence.get('vendor'),
          source_value = sequence.get('vendor'),
          destination_section_value = sequence.get('client'),
          destination_value = sequence.get('client'),
          resource = invoice_prop['currency'],
639
          start_date = date, stop_date = date,
640
          created_by_builder = 0,
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
      )
      
      for line_type in ['income', 'receivable', 'collected_vat'] :
        source_account = sequence.get('%s_account' % line_type)
        line = invoice.newContent(
          portal_type = self.sale_invoice_transaction_line_portal_type,
          quantity = invoice_prop[line_type],
          source_value = source_account
        )
        source_converted = invoice_prop.get(
                          'source_converted_%s' % line_type, None)
        if source_converted is not None :
          line.setSourceTotalAssetPrice(source_converted)
        
        destination_account = source_account.getDestinationValue(
                                                portal_type = 'Account' )
        destination_converted = invoice_prop.get(
                          'destination_converted_%s' %
                          destination_account.getAccountTypeId(), None)
        if destination_converted is not None :
          line.setDestinationTotalAssetPrice(destination_converted)
 
      invoice_list.append(invoice)
    sequence.edit( invoice_list = invoice_list )
  
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
  def stepCreateOtherSectionInvoices(self, sequence, **kw):
    """Create invoice for other sections."""
    other_source = self.getOrganisationModule().newContent(
                      portal_type = 'Organisation' )
    other_destination = self.getOrganisationModule().newContent(
                      portal_type = 'Organisation' )
    invoice = self.getAccountingModule().newContent(
        portal_type = self.sale_invoice_portal_type,
        source_section_value = other_source,
        source_value = other_source,
        destination_section_value = other_destination,
        destination_value = other_destination,
        resource_value = sequence.get('EUR'),
        start_date = self.start_date,
        stop_date = self.start_date,
681
        created_by_builder = 0,
682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    )
    
    line = invoice.newContent(
        portal_type = self.sale_invoice_transaction_line_portal_type,
        quantity = 100, source_value = sequence.get('account_list')[0])
    line = invoice.newContent(
        portal_type = self.sale_invoice_transaction_line_portal_type,
        quantity = -100, source_value = sequence.get('account_list')[1])
    sequence.edit(invoice_list = [invoice])
  
  def stepStopInvoices(self, sequence, **kw) :
    """Validates invoices."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
      self.getPortal().portal_workflow.doActionFor(
          invoice, 'stop_action')
698 699 700 701 702 703 704 705
  
  def stepCheckStopInvoicesRefused(self, sequence, **kw) :
    """Checks that invoices cannot be validated."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
      self.assertRaises(ValidationFailed,
          self.getPortal().portal_workflow.doActionFor,
          invoice, 'stop_action')
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724

  def stepCheckInvoicesAreDraft(self, sequence, **kw) :
    """Checks invoices are in draft state."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
      self.assertEquals(invoice.getSimulationState(), 'draft')

  def stepCheckInvoicesAreStopped(self, sequence, **kw) :
    """Checks invoices are in stopped state."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
      self.assertEquals(invoice.getSimulationState(), 'stopped')
      
  def stepCheckInvoicesAreDelivered(self, sequence, **kw) :
    """Checks invoices are in delivered state."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
      self.assertEquals(invoice.getSimulationState(), 'delivered')
      
725 726 727 728 729 730 731 732 733 734 735 736 737 738
  def checkAccountBalanceInCurrency(self, section, currency,
                                          sequence, **kw) :
    """ Checks accounts balances in a given currency."""
    invoice_list = sequence.get('invoice_list')
    for account_type in [ 'income', 'receivable', 'collected_vat',
                          'expense', 'payable', 'refundable_vat' ] :
      account = sequence.get('%s_account' % account_type)
      calculated_balance = 0
      for invoice in invoice_list :
        for line in invoice.getMovementList():
          # source
          if line.getSourceValue() == account and\
             line.getResourceValue() == currency and\
             section == line.getSourceSectionValue() :
739
            calculated_balance += (
740 741 742
                    line.getSourceDebit() - line.getSourceCredit())
          # dest.
          elif line.getDestinationValue() == account and\
743 744 745
            line.getResourceValue() == currency and\
            section == line.getDestinationSectionValue() :
            calculated_balance += (
746 747 748 749 750 751
                    line.getDestinationDebit() - line.getDestinationCredit())
      
      self.assertEquals(calculated_balance,
          self.getPortal().portal_simulation.getInventory(
            node_uid = account.getUid(),
            section_uid = section.getUid(),
752
            resource_uid = currency.getUid(),
753 754 755 756 757 758 759 760 761 762 763 764 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
          ))
  
  def stepCheckAccountBalanceLocalCurrency(self, sequence, **kw) :
    """ Checks accounts balances in the organisation default currency."""
    for section in (sequence.get('vendor'), sequence.get('client')) :
      currency = section.getPriceCurrencyValue()
      self.checkAccountBalanceInCurrency(section, currency, sequence)
  
  def stepCheckAccountBalanceExternalCurrency(self, sequence, **kw) :
    """ Checks accounts balances in external currencies ."""
    for section in (sequence.get('vendor'), sequence.get('client')) :
      for currency in (sequence.get('USD'), sequence.get('YEN')) :
        self.checkAccountBalanceInCurrency(section, currency, sequence)
    
  def checkAccountBalanceInConvertedCurrency(self, section, sequence, **kw) :
    """ Checks accounts balances converted in section default currency."""
    invoice_list = sequence.get('invoice_list')
    for account_type in [ 'income', 'receivable', 'collected_vat',
                          'expense', 'payable', 'refundable_vat' ] :
      account = sequence.get('%s_account' % account_type)
      calculated_balance = 0
      for invoice in invoice_list :
        for line in invoice.getMovementList() :
          if line.getSourceValue() == account and \
             section == line.getSourceSectionValue() :
            calculated_balance += line.getSourceInventoriatedTotalAssetPrice()
          elif line.getDestinationValue() == account and\
               section == line.getDestinationSectionValue() :
            calculated_balance += \
                             line.getDestinationInventoriatedTotalAssetPrice()
      self.assertEquals(calculated_balance,
          self.getPortal().portal_simulation.getInventoryAssetPrice(
            node_uid = account.getUid(),
            section_uid = section.getUid(),
          ))
  
  def stepCheckAccountBalanceConvertedCurrency(self, sequence, **kw):
    """Checks accounts balances converted in the organisation default
    currency."""
    for section in (sequence.get('vendor'), sequence.get('client')) :
      self.checkAccountBalanceInConvertedCurrency(section, sequence)
794 795 796 797 798 799 800 801 802 803 804 805
  
  def stepCheckAccountingTransactionDelivered(self, sequence, **kw):
    """Checks all accounting transaction related to `organisation`
      are in delivered state. """
    organisation = sequence.get('organisation').getRelativeUrl()
    accounting_module = self.getPortal().accounting_module
    for transaction in accounting_module.objectValues() :
      if transaction.getSourceSection() == organisation \
          or transaction.getDestinationSection() == organisation :
        if self.start_date <= transaction.getStartDate() <= self.stop_date :
          self.assertEquals(transaction.getSimulationState(), 'delivered')
  
806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
  def stepCheckAcquisition(self, sequence, **kw):
    """Checks acquisition and portal types configuration. """
    resource_value = sequence.get('EUR')
    source_section_title = "Source Section Title"
    destination_section_title = "Destination Section Title"
    source_section_value = self.getOrganisationModule().newContent(
        portal_type = self.organisation_portal_type,
        title = source_section_title,
        group = "group/client",
        price_currency = "currency_module/USD")
    destination_section_value = self.getOrganisationModule().newContent(
        portal_type = self.organisation_portal_type,
        title = destination_section_title,
        group = "group/vendor",
        price_currency = "currency_module/EUR")
    
    portal = self.getPortal()
    accounting_module = portal.accounting_module
824
    self.failUnless('Site Error' not in accounting_module.view())
825 826 827 828 829 830 831 832 833 834 835
    self.assertNotEquals(
          len(portal.getPortalAccountingMovementTypeList()), 0)
    self.assertNotEquals(
          len(portal.getPortalAccountingTransactionTypeList()), 0)
    for accounting_portal_type in portal\
                    .getPortalAccountingTransactionTypeList():
      accounting_transaction = accounting_module.newContent(
            portal_type = accounting_portal_type,
            source_section_value = source_section_value,
            destination_section_value = destination_section_value,
            resource_value = resource_value )
836
      self.failUnless('Site Error' not in accounting_transaction.view())
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
      self.assertEquals( accounting_transaction.getSourceSectionValue(),
                         source_section_value )
      self.assertEquals( accounting_transaction.getDestinationSectionValue(),
                         destination_section_value )
      self.assertEquals( accounting_transaction.getResourceValue(),
                         resource_value )
      self.assertNotEquals(
              len(accounting_transaction.allowedContentTypes()), 0)
      tested_line_portal_type = 0
      for line_portal_type in portal.getPortalAccountingMovementTypeList():
        allowed_content_types = [x.id for x in
                            accounting_transaction.allowedContentTypes()]
        if line_portal_type in allowed_content_types :
          line = accounting_transaction.newContent(
            portal_type = line_portal_type, )
852
          self.failUnless('Site Error' not in line.view())
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
          # section and resource is acquired from parent transaction.
          self.assertEquals( line.getDestinationSectionValue(),
                             destination_section_value )
          self.assertEquals( line.getDestinationSectionTitle(),
                             destination_section_title )
          self.assertEquals( line.getSourceSectionValue(),
                             source_section_value )
          self.assertEquals( line.getSourceSectionTitle(),
                             source_section_title )
          self.assertEquals( line.getResourceValue(),
                             resource_value )
          tested_line_portal_type = 1
      self.assert_(tested_line_portal_type, ("No lines tested ... " +
                          "getPortalAccountingMovementTypeList = %s " +
                          "<%s>.allowedContentTypes = %s") %
                          (portal.getPortalAccountingMovementTypeList(),
                            accounting_transaction.getPortalType(),
                            allowed_content_types ))
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
  def createAccountingTransaction(self,
                        portal_type=accounting_transaction_portal_type,
                        line_portal_type=accounting_transaction_line_portal_type,
                        quantity=100, reindex=1, check_consistency=1, **kw):
    """Creates an accounting transaction.
    By default, this transaction contains 2 lines, income and receivable.
      quantity          - The quantity property on created lines.
      reindex           - The transaction will be reindexed.
      check_consistency - a consistency check will be performed on the
                          transaction.
    """
    kw.setdefault('resource_value', self.EUR)
    kw.setdefault('source_section_value', self.vendor)
    kw.setdefault('destination_section_value', self.client)
    if 'start_date' not in kw:
      start_date = DateTime(2000, 01, 01)
      # get a valid date for source section
      for openned_source_section_period in\
        kw['source_section_value'].searchFolder(
              portal_type=self.accounting_period_portal_type,
              simulation_state='planned' ):
        start_date = openned_source_section_period.getStartDate() + 1
      kw['start_date'] = start_date

    if 'stop_date' not in kw:
      # get a valid date for destination section
      stop_date = DateTime(2000, 02, 02)
      for openned_destination_section_period in\
        kw['destination_section_value'].searchFolder(
              portal_type=self.accounting_period_portal_type,
              simulation_state='planned' ):
        stop_date = openned_destination_section_period.getStartDate() + 1
      kw['stop_date'] = stop_date
905

906
    # create the transaction.
907
    transaction = self.getAccountingModule().newContent(
908 909 910 911 912 913 914
      portal_type=portal_type,
      start_date=kw['start_date'],
      stop_date=kw['stop_date'],
      resource_value=kw['resource_value'],
      source_section_value=kw['source_section_value'],
      destination_section_value=kw['destination_section_value'],
      created_by_builder = 1 # prevent the init script from
915 916 917
                             # creating lines.
    )
    income = transaction.newContent(
918 919
                  id='income',
                  portal_type=line_portal_type,
920
                  quantity=-quantity,
921 922 923
                  source_value=kw.get('income_account', self.income_account),
                  destination_value=kw.get('expense_account',
                                              self.expense_account), )
924 925 926 927
    self.failUnless(income.getSource() != None)
    self.failUnless(income.getDestination() != None)
    
    receivable = transaction.newContent(
928 929
                  id='receivable',
                  portal_type=line_portal_type,
930
                  quantity=quantity,
931 932 933 934
                  source_value=kw.get('receivable_account',
                                          self.receivable_account),
                  destination_value=kw.get('payable_account',
                                            self.payable_account), )
935 936
    self.failUnless(receivable.getSource() != None)
    self.failUnless(receivable.getDestination() != None)
937 938 939 940 941 942 943 944
    if reindex:
      get_transaction().commit()
      self.tic()
    if check_consistency:
      self.failUnless(len(transaction.checkConsistency()) == 0,
         "Check consistency failed : %s" % transaction.checkConsistency())
    return transaction

945 946 947 948 949 950 951 952 953 954 955 956 957 958
  def test_createAccountingTransaction(self):
    """Make sure acounting transactions created by createAccountingTransaction
    method are valid.
    """
    transaction = self.createAccountingTransaction()
    self.assertEquals(self.vendor, transaction.getSourceSectionValue())
    self.assertEquals(self.client, transaction.getDestinationSectionValue())
    self.assertEquals(self.EUR, transaction.getResourceValue())
    self.failUnless(transaction.AccountingTransaction_isSourceView())
    
    self.workflow_tool.doActionFor(transaction, 'stop_action')
    self.assertEquals('stopped', transaction.getSimulationState())
    self.assertEquals([] , transaction.checkConsistency())

959 960 961 962 963 964 965 966 967 968 969 970
  def stepCreateValidAccountingTransaction(self, sequence,
                                          sequence_list=None, **kw) :
    """Creates a valid accounting transaction and put it in
    the sequence as `transaction` key. """
    transaction = self.createAccountingTransaction(
                            resource_value=sequence.get('EUR'),
                            source_section_value=sequence.get('vendor'),
                            destination_section_value=sequence.get('client'),
                            income_account=sequence.get('income_account'),
                            expense_account=sequence.get('expense_account'),
                            receivable_account=sequence.get('receivable_account'),
                            payable_account=sequence.get('payable_account'), )
971 972
    sequence.edit(
      transaction = transaction,
973 974
      income = transaction.income,
      receivable = transaction.receivable
975 976
    )
    
977 978 979 980 981 982 983 984 985
  def stepValidateNoDate(self, sequence, sequence_list=None, **kw) :
    """When no date is defined, validation should be impossible.
    
    Actually, we could say that if we have source_section, we need start_date,
    and if we have destination section, we need stop_date only, but we decided
    to update a date (of start_date / stop_date) using the other one if one is
    missing. (ie. stop_date defaults automatically to start_date if not set and
    start_date is set to stop_date in the workflow script if not set.
    """
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
    transaction = sequence.get('transaction')
    old_stop_date = transaction.getStopDate()
    old_start_date = transaction.getStartDate()
    transaction.setStopDate(None)
    if transaction.getStopDate() != None :
      transaction.setStartDate(None)
      transaction.setStopDate(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    transaction.setStartDate(old_start_date)
    transaction.setStopDate(old_stop_date)
    self.getWorkflowTool().doActionFor(transaction, 'stop_action')
    self.assertEquals(transaction.getSimulationState(), 'stopped')
  
  def stepValidateNoSection(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour related to section & mirror_section.
    When no source section is defined, we are in one of the following
    cases : 
      o if we use payable or receivable account, the validation should
        be refused.
      o if we do not use any payable or receivable accounts and we have
      a destination section, validation should be ok.
    """
    transaction = sequence.get('transaction')
    old_source_section = transaction.getSourceSection()
    old_destination_section = transaction.getDestinationSection()
    # default transaction uses payable accounts, so validating without
    # source section is refused.
    transaction.setSourceSection(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    # ... as well as validation without destination section
    transaction.setSourceSection(old_source_section)
    transaction.setDestinationSection(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    # mirror section can be set only on the line
    for line in transaction.getMovementList() :
      if line.getSourceValue().isMemberOf(
              'account_type/asset/receivable') or \
         line.getSourceValue().isMemberOf(
              'account_type/liability/payable') :
        line.setDestinationSection(old_destination_section)
    try:
      self.getWorkflowTool().doActionFor(transaction, 'stop_action')
      self.assertEquals(transaction.getSimulationState(), 'stopped')
    except ValidationFailed, err :
      self.assert_(0, "Validation failed : %s" % err.msg)
    
    # if we do not use any payable / receivable account, then we can
    # validate the transaction without setting the mirror section.
1043 1044 1045 1046
    for side in (SOURCE, ): # DESTINATION) :
      # TODO: for now, we only test for source, as it makes no sense to use for
      # destination section only. We could theoritically support it.

1047
      # get a new valid transaction
1048
      transaction = self.createAccountingTransaction()
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 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
      expense_account = sequence.get('expense_account')
      for line in transaction.getMovementList() :
        line.edit( source_value = expense_account,
                   destination_value = expense_account )
      if side == SOURCE :
        transaction.setDestinationSection(None)
      else :
        transaction.setSourceSection(None)
      try:
        self.getWorkflowTool().doActionFor(transaction, 'stop_action')
        self.assertEquals(transaction.getSimulationState(), 'stopped')
      except ValidationFailed, err :
        self.assert_(0, "Validation failed : %s" % err.msg)
        
  def stepValidateNoCurrency(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour related to currency.
    """
    transaction = sequence.get('transaction')
    old_resource = transaction.getResource()
    transaction.setResource(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    # setting a dummy relationship is not enough, resource must be a
    # currency
    transaction.setResource(transaction.getDestinationSection())
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
  def stepValidateClosedAccount(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour related to closed accounts.
    If an account is blocked, then it's impossible to validate a
    transaction related to this account.
    """
    transaction = sequence.get('transaction')
    account = transaction.getMovementList()[0].getSourceValue()
    self.getWorkflowTool().doActionFor(account, 'invalidate_action')
    self.assertEquals(account.getValidationState(), 'invalidated')
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    # reopen the account for other tests
    account.validate()
    self.assertEquals(account.getValidationState(), 'validated')
    
  def stepValidateNoAccounts(self, sequence, sequence_list=None, **kw) :
    """Simple check that the validation is refused when we do not have
    accounts correctly defined on lines.
    """
    transaction = sequence.get('transaction')
    # no account at all is refused
    for line in transaction.getMovementList():
      line.setSource(None)
      line.setDestination(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
    # only one line without account and with a quantity is also refused
1113
    transaction = self.createAccountingTransaction()
1114
    transaction.getMovementList()[0].setSource(None)
1115
    transaction.getMovementList()[0].setDestination(None)
1116 1117 1118 1119 1120 1121 1122
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
    # but if we have a line with 0 quantity on both sides, we can
    # validate the transaction and delete this line.
1123
    transaction = self.createAccountingTransaction()
1124 1125 1126 1127 1128 1129 1130 1131 1132
    line_count = len(transaction.getMovementList())
    transaction.newContent(
        portal_type = self.accounting_transaction_line_portal_type)
    self.getWorkflowTool().doActionFor(transaction, 'stop_action')
    self.assertEquals(transaction.getSimulationState(), 'stopped')
    self.assertEquals(line_count, len(transaction.getMovementList()))
    
    # 0 quantity, but a destination asset price => do not delete the
    # line
1133
    transaction = self.createAccountingTransaction()
1134 1135
    new_line = transaction.newContent(
        portal_type = self.accounting_transaction_line_portal_type)
1136
    self.assertEquals(len(transaction.getMovementList()), 3)
1137 1138
    line_list = transaction.getMovementList()
    line_list[0].setDestinationTotalAssetPrice(100)
1139 1140
    line_list[0]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
1141
    line_list[1].setDestinationTotalAssetPrice(- 50)
1142 1143
    line_list[1]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
1144
    line_list[2].setDestinationTotalAssetPrice(- 50)
1145 1146
    line_list[2]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164
    try:
      self.getWorkflowTool().doActionFor(transaction, 'stop_action')
      self.assertEquals(transaction.getSimulationState(), 'stopped')
    except ValidationFailed, err :
      self.assert_(0, "Validation failed : %s" % err.msg)
  
  def stepValidateNotBalanced(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour when transaction is not balanced.
    """
    transaction = sequence.get('transaction')
    transaction.getMovementList()[0].setQuantity(4325)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
    # asset price have priority (ie. if asset price is not balanced,
    # refuses validation even if quantity is balanced)
1165
    transaction = self.createAccountingTransaction()
1166 1167 1168 1169 1170 1171 1172 1173
    line_list = transaction.getMovementList()
    line_list[0].setDestinationTotalAssetPrice(10)
    line_list[1].setDestinationTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
1174
    transaction = self.createAccountingTransaction()
1175 1176 1177 1178 1179 1180 1181 1182 1183
    line_list = transaction.getMovementList()
    line_list[0].setSourceTotalAssetPrice(10)
    line_list[1].setSourceTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
    # only asset price needs to be balanced
1184
    transaction = self.createAccountingTransaction()
1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
    line_list = transaction.getMovementList()
    line_list[0].setSourceTotalAssetPrice(100)
    line_list[0].setDestinationTotalAssetPrice(100)
    line_list[0].setQuantity(432432)
    line_list[1].setSourceTotalAssetPrice(-100)
    line_list[1].setDestinationTotalAssetPrice(-100)
    line_list[1].setQuantity(32546787)
    try:
      self.getWorkflowTool().doActionFor(transaction, 'stop_action')
      self.assertEquals(transaction.getSimulationState(), 'stopped')
    except ValidationFailed, err :
      self.assert_(0, "Validation failed : %s" % err.msg)
  
  def stepValidateNoPayment(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour related to payment & mirror_payment.
    If we use an account of type asset/cash/bank, we must use set a Bank
    Account as source_payment or destination_payment.
    This this source/destination payment must be a portal type from the
    `payment node` portal type group. It can be defined on transaction
    or line.
    """
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218
    def useBankAccount(transaction):
      """Modify the transaction, so that a line will use an account member of
      account_type/cash/bank , which requires to use a payment category.
      """
      # get the default and replace income account by bank
      income_account_found = 0
      for line in transaction.getMovementList() :
        source_account = line.getSourceValue()
        if source_account.isMemberOf('account_type/income') :
          income_account_found = 1
          line.edit( source_value = sequence.get('bank_account'),
                     destination_value = sequence.get('bank_account') )
      self.failUnless(income_account_found)
1219
    # XXX
1220
    transaction = sequence.get('transaction')
1221
    useBankAccount(transaction)
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
        transaction,
        'stop_action')
    
    source_section_value = transaction.getSourceSectionValue()
    destination_section_value = transaction.getDestinationSectionValue()
    for ptype in self.getPortal().getPortalPaymentNodeTypeList() :
      source_payment_value = source_section_value.newContent(
                                  portal_type = ptype, )
      destination_payment_value = destination_section_value.newContent(
                                  portal_type = ptype, )
1234 1235
      transaction = self.createAccountingTransaction(
                      destination_section_value=self.other_vendor)
1236 1237
      useBankAccount(transaction)

1238 1239
      # payment node have to be set on both sides if both sides are member of
      # the same group.
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
      transaction.setSourcePaymentValue(source_payment_value)
      transaction.setDestinationPaymentValue(None)
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
          transaction,
          'stop_action')
      transaction.setSourcePaymentValue(None)
      transaction.setDestinationPaymentValue(destination_payment_value)
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
          transaction,
          'stop_action')
      transaction.setSourcePaymentValue(source_payment_value)
      transaction.setDestinationPaymentValue(destination_payment_value)
      try:
        self.getWorkflowTool().doActionFor(transaction, 'stop_action')
        self.assertEquals(transaction.getSimulationState(), 'stopped')
      except ValidationFailed, err :
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
        self.fail("Validation failed : %s" % err.msg)

      # if we are not interested in the accounting for the third party, no need
      # to have a destination_payment
      transaction = self.createAccountingTransaction()
      useBankAccount(transaction)
      # only set payment for source
      transaction.setSourcePaymentValue(source_payment_value)
      transaction.setDestinationPaymentValue(None)
      # then we should be able to validate.
      try:
        self.getWorkflowTool().doActionFor(transaction, 'stop_action')
        self.assertEquals(transaction.getSimulationState(), 'stopped')
      except ValidationFailed, err:
        self.fail("Validation failed : %s" % err.msg)
    
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
  def stepValidateRemoveEmptyLines(self, sequence, sequence_list=None, **kw):
    """Check validating a transaction remove empty lines. """
    transaction = sequence.get('transaction')
    lines_count = len(transaction.getMovementList())
    empty_lines_count = 0
    for line in transaction.getMovementList():
      if line.getSourceTotalAssetPrice() ==  \
         line.getDestinationTotalAssetPrice() == 0:
        empty_lines_count += 1
    if empty_lines_count == 0:
      transaction.newContent(
            portal_type=self.accounting_transaction_line_portal_type)
    
    self.getWorkflowTool().doActionFor(transaction, 'stop_action')
    self.assertEquals(len(transaction.getMovementList()),
                      lines_count - empty_lines_count)
    
    # we don't remove empty lines if there is only empty lines
    transaction = self.getAccountingModule().newContent(
                      portal_type=self.accounting_transaction_portal_type,
                      created_by_builder=1)
    for i in range(3):
      transaction.newContent(
            portal_type=self.accounting_transaction_line_portal_type)
    lines_count = len(transaction.getMovementList())
    transaction.AccountingTransaction_deleteEmptyLines(redirect=0)
    self.assertEquals(len(transaction.getMovementList()), lines_count)
    
1302 1303 1304
  ############################################################################
  ## Test Methods ############################################################
  ############################################################################
1305
  
Jérome Perrin's avatar
Jérome Perrin committed
1306
  def test_MultiCurrencyInvoice(self, quiet=QUIET, run=RUN_ALL_TESTS):
1307
    """Basic test for multi currency accounting"""
1308
    if not run : return
1309 1310 1311 1312 1313 1314 1315 1316 1317
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateInvoices
      stepTic
      stepCheckAccountBalanceLocalCurrency
      stepCheckAccountBalanceExternalCurrency
      stepCheckAccountBalanceConvertedCurrency
Jérome Perrin's avatar
Jérome Perrin committed
1318
    """, quiet=quiet)
1319

Jérome Perrin's avatar
Jérome Perrin committed
1320
  def test_AccountingPeriod(self, quiet=QUIET, run=RUN_ALL_TESTS):
1321
    """Basic test for Accounting Periods"""
1322
    if not run : return
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepUseValidDates
      stepCreateInvoices
      stepStopInvoices
      stepCheckInvoicesAreStopped
      stepTic
      stepConfirmAccountingPeriod
      stepTic
      stepDeliverAccountingPeriod
      stepTic
1339
      stepCheckAccountingPeriodDelivered
1340 1341 1342
      stepCheckInvoicesAreDelivered
      stepTic
      stepCheckAccountingTransactionDelivered
Jérome Perrin's avatar
Jérome Perrin committed
1343
    """, quiet=quiet)
1344 1345
  
  def test_AccountingPeriodRefusesWrongDateTransactionValidation(
Jérome Perrin's avatar
Jérome Perrin committed
1346
        self, quiet=QUIET, run=RUN_ALL_TESTS):
1347 1348
    """Accounting Periods prevents transactions to be validated
        when there is no oppened accounting period"""
1349
    if not run : return
1350 1351 1352 1353 1354 1355 1356 1357 1358
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepUseInvalidDates
      stepCreateInvoices
1359
      stepCheckStopInvoicesRefused
1360 1361
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
1362
    """, quiet=quiet)
1363

Jérome Perrin's avatar
Jérome Perrin committed
1364
  def test_AccountingPeriodNotStoppedTransactions(self, quiet=QUIET,
1365 1366 1367
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods refuse to close when some transactions are
      not stopped"""
1368
    if not run : return
1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateInvoices
      stepTic
      stepCheckAccountingPeriodRefusesClosing
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
1381
    """, quiet=quiet)
1382

Jérome Perrin's avatar
Jérome Perrin committed
1383
  def test_AccountingPeriodOtherSections(self, quiet=QUIET,
1384 1385
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods does not change other section transactions."""
1386
    if not run : return
1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateOtherSectionInvoices
      stepTic
      stepConfirmAccountingPeriod
      stepTic
      stepDeliverAccountingPeriod
      stepTic
1400
      stepCheckAccountingPeriodDelivered
1401
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
1402
    """, quiet=quiet)
1403

Jérome Perrin's avatar
Jérome Perrin committed
1404
  def test_MirrorAccounts(self, quiet=QUIET, run=RUN_ALL_TESTS):
1405 1406
    """Tests using an account on one sides uses the mirror account
    on the other size. """
1407
    if not run : return
1408 1409 1410 1411
    self.playSequence("""
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingTransactionAndCheckMirrorAccount
Jérome Perrin's avatar
Jérome Perrin committed
1412
    """, quiet=quiet)
1413

Jérome Perrin's avatar
Jérome Perrin committed
1414
  def test_Acquisition(self, quiet=QUIET, run=RUN_ALL_TESTS):
1415 1416 1417 1418 1419 1420
    """Tests acquisition, categories and portal types are well
    configured. """
    if not run : return
    self.playSequence("""
      stepCreateCurrencies
      stepCheckAcquisition
Jérome Perrin's avatar
Jérome Perrin committed
1421
      """, quiet=quiet)
1422

Jérome Perrin's avatar
Jérome Perrin committed
1423
  def test_AccountingTransactionValidationDate(self, quiet=QUIET,
1424 1425 1426 1427 1428 1429 1430 1431
                                            run=RUN_ALL_TESTS):
    """Transaction validation and dates"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
Jérome Perrin's avatar
Jérome Perrin committed
1432
      stepValidateNoDate""", quiet=quiet)
1433

Jérome Perrin's avatar
Jérome Perrin committed
1434
  def test_AccountingTransactionValidationSection(self, quiet=QUIET,
1435 1436 1437 1438 1439 1440 1441 1442
                                             run=RUN_ALL_TESTS):
    """Transaction validation and section"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
Jérome Perrin's avatar
Jérome Perrin committed
1443
      stepValidateNoSection""", quiet=quiet)
1444

Jérome Perrin's avatar
Jérome Perrin committed
1445
  def test_AccountingTransactionValidationCurrency(self, quiet=QUIET,
1446 1447 1448 1449 1450 1451 1452 1453
                                           run=RUN_ALL_TESTS):
    """Transaction validation and currency"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
Jérome Perrin's avatar
Jérome Perrin committed
1454
      stepValidateNoCurrency""", quiet=quiet)
1455

Jérome Perrin's avatar
Jérome Perrin committed
1456
  def test_AccountingTransactionValidationAccounts(self, quiet=QUIET,
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466
                                           run=RUN_ALL_TESTS):
    """Transaction validation and accounts"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
      stepValidateClosedAccount
      stepCreateValidAccountingTransaction
Jérome Perrin's avatar
Jérome Perrin committed
1467
      stepValidateNoAccounts""", quiet=quiet)
1468

Jérome Perrin's avatar
Jérome Perrin committed
1469
  def test_AccountingTransactionValidationBalanced(self, quiet=QUIET,
1470 1471 1472 1473 1474 1475 1476 1477
                                              run=RUN_ALL_TESTS):
    """Transaction validation and balance"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
Jérome Perrin's avatar
Jérome Perrin committed
1478
      stepValidateNotBalanced""", quiet=quiet)
1479

Jérome Perrin's avatar
Jérome Perrin committed
1480
  def test_AccountingTransactionValidationPayment(self, quiet=QUIET,
1481 1482 1483 1484 1485 1486 1487 1488 1489
                                             run=RUN_ALL_TESTS):
    """Transaction validation and payment"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
      stepValidateNoPayment
Jérome Perrin's avatar
Jérome Perrin committed
1490
    """, quiet=quiet)
1491

Jérome Perrin's avatar
Jérome Perrin committed
1492
  def test_AccountingTransactionValidationRemoveEmptyLines(self, quiet=QUIET,
1493 1494 1495 1496 1497 1498 1499 1500 1501
                                             run=RUN_ALL_TESTS):
    """Transaction validation removes empty lines"""
    if not run : return
    self.playSequence("""
      stepCreateEntities
      stepCreateCurrencies
      stepCreateAccounts
      stepCreateValidAccountingTransaction
      stepValidateRemoveEmptyLines
Jérome Perrin's avatar
Jérome Perrin committed
1502
    """, quiet=quiet)
1503

1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517
  def test_AccountingTransactionValidationRefusedWithCategoriesAsSections(self,
                                        quiet=QUIET, run=RUN_ALL_TESTS):
    """Validating a transaction with categories as sections is refused.
    See http://wiki.erp5.org/Discussion/AccountingProblems """
    category = self.vendor.getGroupValue()
    self.assertNotEquals(category, None)
    transaction = self.createAccountingTransaction(
                                    source_section_value=category)
    self.assertRaises(ValidationFailed, self.getWorkflowTool().doActionFor,
                      transaction, 'stop_action')
    transaction = self.createAccountingTransaction(
                                    destination_section_value=category)
    self.assertRaises(ValidationFailed, self.getWorkflowTool().doActionFor,
                      transaction, 'stop_action')
1518

1519 1520 1521 1522 1523 1524 1525
  def test_Account_isCreditAccount(self):
    """Tests the 'credit_account' property on account, which was named
    is_credit_account, which generated isIsCreditAccount accessor"""
    account = self.getAccountModule().newContent(portal_type='Account')
    # simulate an old object
    account.is_credit_account = True
    self.failUnless(account.isCreditAccount())
1526
    self.failUnless(account.getProperty('credit_account'))
1527
    
1528
    account.setCreditAccount(False)
1529
    self.failIf(account.isCreditAccount())
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

  # tests for Invoice_createRelatedPaymentTransaction
  def _checkRelatedSalePayment(self, invoice, payment, payment_node, quantity):
    """Check payment of a Sale Invoice.
    """
    eq = self.assertEquals
    eq('Payment Transaction', payment.getPortalTypeName())
    eq([invoice], payment.getCausalityValueList())
    eq(invoice.getSourceSection(), payment.getSourceSection())
    eq(invoice.getDestinationSection(), payment.getDestinationSection())
    eq(payment_node, payment.getSourcePaymentValue())
    eq(self.getCategoryTool().payment_mode.check,
       payment.getPaymentModeValue())
    # test lines
    eq(2, len(payment.getMovementList()))
    for line in payment.getMovementList():
      if line.getId() == 'bank':
        eq(quantity, line.getSourceCredit())
        eq(self.bank_account, line.getSourceValue())
      else:
        eq(quantity, line.getSourceDebit())
        eq(self.receivable_account, line.getSourceValue())
    # this transaction can be validated
    eq([], payment.checkConsistency())
    self.workflow_tool.doActionFor(payment, 'stop_action')
1555
    eq('stopped', payment.getSimulationState())
1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579

  def test_Invoice_createRelatedPaymentTransactionSimple(self):
    """Simple case of creating a related payment transaction.
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 100)

  def test_Invoice_createRelatedPaymentTransactionGroupedLines(self):
    """Simple creating a related payment transaction when grouping reference of
    some lines is already set.
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    invoice.receivable.setSourceCredit(60)
    invoice.newContent(id='receivable_groupped',
                       source_credit=40,
                       source_value=self.receivable_account)
    invoice.receivable_groupped.setGroupingReference('A')
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
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 60)
  
  def test_Invoice_createRelatedPaymentTransactionDifferentSection(self):
    """Simple creating a related payment transaction when we have two line for
    2 different destination sections.
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    invoice.receivable.setSourceCredit(60)
    invoice.newContent(id='receivable_other_third_party',
                       destination_section_value=self.other_vendor,
                       source_credit=40,
                       source_value=self.receivable_account)
    
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 60)
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
 
  def test_Invoice_createRelatedPaymentTransactionRelatedInvoice(self):
    """Simple creating a related payment transaction when we have related
    transactions.
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    accounting_transaction = self.createAccountingTransaction()
    accounting_transaction.receivable.setSourceDebit(20)
    accounting_transaction.income.setSourceCredit(20)
    accounting_transaction.setCausalityValue(invoice)
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                           'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
    get_transaction().commit()
    self.tic()
    
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 80)
    
  def test_Invoice_createRelatedPaymentTransactionRelatedInvoiceDifferentSide(self):
    """Simple creating a related payment transaction when we have related
    transactions with different side
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    accounting_transaction = self.createAccountingTransaction()
    accounting_transaction.edit(
            source_section=accounting_transaction.getDestinationSection(),
            destination_section=accounting_transaction.getSourceSection())
    accounting_transaction.receivable.edit(
          source=accounting_transaction.receivable.getDestination(),
          destination=accounting_transaction.receivable.getSource(),
          destination_debit=20)
    accounting_transaction.income.edit(
          source=accounting_transaction.income.getDestination(),
          destination=accounting_transaction.income.getSource(),
          destination_credit=20)
    accounting_transaction.setCausalityValue(invoice)
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                            'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
    get_transaction().commit()
    self.tic()
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
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 80)
 
  def test_Invoice_createRelatedPaymentTransactionRelatedInvoiceDraft(self):
    """Simple creating a related payment transaction when we have related
    transactions in draft/cancelled state (they are ignored)
    """
    payment_node = self.vendor.newContent(portal_type='Bank Account')
    invoice = self.createAccountingTransaction()
    accounting_transaction = self.createAccountingTransaction()
    accounting_transaction.setCausalityValue(invoice)
    other_accounting_transaction = self.createAccountingTransaction()
    other_accounting_transaction.setCausalityValue(invoice)
    other_accounting_transaction.cancel()
    get_transaction().commit()
    self.tic()

    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.bank_account.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 100)
1682 1683 1684 1685 1686 1687 1688

  def test_SourceDestinationReference(self):
    """Check that source reference and destination reference are filled
    automatically.
    """
    # clear all existing ids in portal ids
    if hasattr(self.portal.portal_ids, 'dict_ids'):
1689
      self.portal.portal_ids.dict_ids.clear()
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702
    accounting_transaction = self.createAccountingTransaction()
    self.portal.portal_workflow.doActionFor(
          accounting_transaction, 'stop_action')
    self.assertEquals('1', accounting_transaction.getSourceReference())
    self.assertEquals('1', accounting_transaction.getDestinationReference())

    other_transaction = self.createAccountingTransaction()
    other_transaction.setDestinationSectionValue(self.other_vendor)
    self.portal.portal_workflow.doActionFor(other_transaction, 'stop_action')
    self.assertEquals('2', other_transaction.getSourceReference())
    self.assertEquals('1', other_transaction.getDestinationReference())


1703 1704 1705 1706
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestAccounting))
  return suite
1707