testAccounting.py 177 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
import os
35

36
import transaction
37 38 39
from DateTime import DateTime
from Products.CMFCore.utils import _checkPermission

40
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
41
from Products.ERP5Type.tests.utils import reindex
42
from Products.DCWorkflow.DCWorkflow import ValidationFailed
43 44
from AccessControl.SecurityManagement import newSecurityManager
from Products.ERP5Type.tests.Sequence import Sequence, SequenceList
45
from Products.ERP5Form.Document.Preference import Priority
46

47 48 49
SOURCE = 'source'
DESTINATION = 'destination'
RUN_ALL_TESTS = 1
Jérome Perrin's avatar
Jérome Perrin committed
50
QUIET = 1
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
# 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',
  }


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
90
    * self.client_1, self.client_2 & self.supplier, some other organisations
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  
  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. 
  """
  
114
  username = 'username'
115 116

  @reindex
117 118
  def _makeOne(self, portal_type='Accounting Transaction', lines=None,
               simulation_state='draft', **kw):
119 120 121 122 123 124 125 126
    """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())
127 128
    if 'resource_value' not in kw:
      kw.setdefault('resource', 'currency_module/euro')
129 130
    if portal_type in ('Purchase Invoice Transaction',
                       'Balance Transaction'):
131 132 133 134 135 136 137 138 139 140 141
      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)
142 143 144 145 146 147 148 149
    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()
150 151 152
    return tr


153
  def login(self, name=username):
154 155 156 157 158 159 160 161 162 163 164
    """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)
165 166
    if os.environ.get('erp5_save_data_fs'):
      return
167 168 169 170 171 172
    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
173 174
    if not hasattr(self, 'section'):
      self.section = getattr(self.organisation_module, 'my_organisation', None)
175 176 177 178 179 180
    
    # make sure documents are validated
    for module in (self.account_module, self.organisation_module,
                   self.person_module):
      for doc in module.objectValues():
        doc.validate()
181

182
    # and the preference enabled
183 184 185 186 187 188 189 190
    pref = self.portal.portal_preferences._getOb(
                  'accounting_zuite_preference', None)
    if pref is not None:
      pref.manage_addLocalRoles(self.username, ('Auditor', ))
      # Make sure _aq_dynamic is called before calling the workflow method
      # otherwise .enable might not been wrapped yet. This happen in --load
      pref._aq_dynamic('hack')
      pref.enable()
191
    
Jérome Perrin's avatar
Jérome Perrin committed
192 193
    self.validateRules()

194
    # and all this available to catalog
195
    transaction.commit()
196 197 198 199 200 201
    self.tic()


  def tearDown(self):
    """Remove all documents, except the default ones.
    """
202 203
    if os.environ.get('erp5_save_data_fs'):
      return
204
    transaction.abort()
205 206
    self.accounting_module.manage_delObjects(
                      list(self.accounting_module.objectIds()))
207
    organisation_list = ('my_organisation', 'client_1', 'client_2', 'supplier')
208
    self.organisation_module.manage_delObjects([x for x in 
209 210
          self.accounting_module.objectIds() if x not in organisation_list])
    for organisation_id in organisation_list:
211 212 213
      organisation = self.organisation_module._getOb(organisation_id, None)
      if organisation is not None:
        organisation.manage_delObjects([x.getId() for x in
214 215
                organisation.objectValues(
                  portal_type=('Accounting Period', 'Bank Account'))])
216 217 218 219 220 221
    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',)])
222 223 224 225
    self.portal.portal_preferences.manage_delObjects([x.getId() for x in
          self.portal.portal_preferences.objectValues()
          if x.getId() not in ('accounting_zuite_preference', 'default_site_preference')
          and x.getPriority() != Priority.SITE])
226 227
    self.portal.portal_simulation.manage_delObjects(list(
          self.portal.portal_simulation.objectIds()))
228
    transaction.commit()
229 230 231 232 233 234
    self.tic()
    ERP5TypeTestCase.tearDown(self)


  def getBusinessTemplateList(self):
    """Returns list of BT to be installed."""
235 236 237 238
    # note that this test case does *not* install erp5_invoicing, even if it's
    # a dependancy of erp5_accounting_ui_test, because it's used to test
    # standalone accounting and only installs erp5_accounting_ui_test to have
    # some default content created.
239
    return ('erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_accounting',
240
            'erp5_accounting_ui_test', 'erp5_ods_style')
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
class TestAccounts(AccountingTestCase):
  """Tests Accounts.
  """
  def test_AccountValidation(self):
    # Accounts need a gap category and an account_type category to be valid
    account = self.portal.account_module.newContent(portal_type='Account')
    self.assertEquals(2, len(account.checkConsistency()))
    account.setAccountType('equity')
    self.assertEquals(1, len(account.checkConsistency()))
    account.setGap('my_country/my_accounting_standards/1')
    self.assertEquals(0, len(account.checkConsistency()))
    
  def test_AccountWorkflow(self):
    account = self.portal.account_module.newContent(portal_type='Account')
    self.assertEquals('draft', account.getValidationState())
    doActionFor = self.portal.portal_workflow.doActionFor
    self.assertRaises(ValidationFailed, doActionFor, account,
                          'validate_action')
    account.setAccountType('equity')
    account.setGap('my_country/my_accounting_standards/1')
    doActionFor(account, 'validate_action')
    self.assertEquals('validated', account.getValidationState())

266 267 268 269 270 271 272 273 274 275 276
  def test_isCreditAccount(self):
    """Tests the 'credit_account' property on account, which was named
    is_credit_account, which generated isIsCreditAccount accessor"""
    account = self.portal.account_module.newContent(portal_type='Account')
    # simulate an old object
    account.is_credit_account = True
    self.failUnless(account.isCreditAccount())
    self.failUnless(account.getProperty('credit_account'))
    
    account.setCreditAccount(False)
    self.failIf(account.isCreditAccount())
277 278


279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302
class TestTransactionValidation(AccountingTestCase):
  """Test validations of accounting transactions.

  In this test suite, the section have a closed accounting period for 2006, and
  an open one for 2007.
  """
  def afterSetUp(self):
    self.organisation_module = self.portal.organisation_module
    self.section = self.organisation_module.my_organisation

    if 'accounting_period_2006' not in self.section.objectIds():
      accounting_period_2006 = self.section.newContent(
                                  id='accounting_period_2006',
                                  portal_type='Accounting Period',
                                  start_date=DateTime('2006/01/01'),
                                  stop_date=DateTime('2006/12/31'))
      accounting_period_2006.start()
      accounting_period_2006.stop()
      accounting_period_2007 = self.section.newContent(
                                  id='accounting_period_2007',
                                  portal_type='Accounting Period',
                                  start_date=DateTime('2007/01/01'),
                                  stop_date=DateTime('2007/12/31'))
      accounting_period_2007.start()
303
      transaction.commit()
304 305 306 307
      self.tic()

  def test_SaleInvoiceTransactionValidationDate(self):
    # Accounting Period Date matters for Sale Invoice Transaction
308
    accounting_transaction = self._makeOne(
309 310 311 312 313 314 315 316 317 318
               portal_type='Sale Invoice Transaction',
               start_date=DateTime('2006/03/03'),
               destination_section_value=self.organisation_module.supplier,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because period is closed
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
319
        accounting_transaction, 'stop_action')
320
    # in 2007, it's OK
321 322
    accounting_transaction.setStartDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
323 324 325
  
  def test_PurchaseInvoiceTransactionValidationDate(self):
    # Accounting Period Date matters for Purchase Invoice Transaction
326
    accounting_transaction = self._makeOne(
327 328 329 330 331 332 333 334 335 336
               portal_type='Purchase Invoice Transaction',
               stop_date=DateTime('2006/03/03'),
               source_section_value=self.organisation_module.supplier,
               lines=(dict(destination_value=self.account_module.goods_purchase,
                           destination_debit=500),
                      dict(destination_value=self.account_module.receivable,
                           destination_credit=500)))
    # validation is refused, because period is closed
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
337
        accounting_transaction, 'stop_action')
338
    # in 2007, it's OK
339 340
    accounting_transaction.setStopDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
341 342 343

  def test_PaymentTransactionValidationDate(self):
    # Accounting Period Date matters for Payment Transaction
344
    accounting_transaction = self._makeOne(
345 346 347
               portal_type='Payment Transaction',
               start_date=DateTime('2006/03/03'),
               destination_section_value=self.organisation_module.supplier,
348
               payment_mode='default',
349 350 351 352 353 354 355
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because period is closed
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
356
        accounting_transaction, 'stop_action')
357
    # in 2007, it's OK
358 359
    accounting_transaction.setStartDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
360 361 362

  def test_DestinationPaymentTransactionValidationDate(self):
    # Accounting Period Date matters for Payment Transaction
363
    accounting_transaction = self._makeOne(
364 365 366 367
               portal_type='Payment Transaction',
               stop_date=DateTime('2006/03/03'),
               source_section_value=self.organisation_module.supplier,
               destination_section_value=self.section, 
368
               payment_mode='default',
369 370 371 372 373 374 375
               lines=(dict(destination_value=self.account_module.goods_purchase,
                           destination_debit=500),
                      dict(destination_value=self.account_module.receivable,
                           destination_credit=500)))
    # validation is refused, because period is closed
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
376
        accounting_transaction, 'stop_action')
377
    # in 2007, it's OK
378 379
    accounting_transaction.setStopDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
380

381 382 383
  def test_UnusedSectionTransactionValidationDate(self):
    # If a section doesn't have any accounts on its side, we don't check the
    # accounting period dates
384
    accounting_transaction = self._makeOne(
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/03/03'),
               source_section_value=self.organisation_module.supplier,
               destination_section_value=self.section,
               payment_mode='default',
               lines=(dict(source_value=self.account_module.goods_purchase,
                           destination_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.receivable,
                           source_credit=500)))

    # 2006 is closed for destination_section
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
400
        accounting_transaction, 'stop_action')
401 402
    # If we don't have accounts on destination side, validating transaction is
    # not refused
403
    for line in accounting_transaction.getMovementList():
404
      line.setDestination(None)
405
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
406

407 408
  def test_AccountingTransactionValidationStartDate(self):
    # Check we can/cannot validate at date boundaries of the period
409
    accounting_transaction = self._makeOne(
410 411 412
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/12/31'),
               destination_section_value=self.organisation_module.supplier,
413
               payment_mode='default',
414 415 416 417 418 419 420
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because period is closed
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
421 422 423
        accounting_transaction, 'stop_action')
    accounting_transaction.setStartDate(DateTime("2007/01/01"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
424
  
425 426
  def test_AccountingTransactionValidationBeforePeriod(self):
    # Check we cannot validate before the period
427
    accounting_transaction = self._makeOne(
428 429 430 431 432 433 434 435 436 437 438
               portal_type='Accounting Transaction',
               start_date=DateTime('2003/12/31'),
               destination_section_value=self.organisation_module.supplier,
               payment_mode='default',
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because there are no open period for 2008
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
439
        accounting_transaction, 'stop_action')
440 441 442
  
  def test_AccountingTransactionValidationAfterPeriod(self):
    # Check we cannot validate after the period
443
    accounting_transaction = self._makeOne(
444 445 446 447 448 449 450 451 452 453 454
               portal_type='Accounting Transaction',
               start_date=DateTime('2008/12/31'),
               destination_section_value=self.organisation_module.supplier,
               payment_mode='default',
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because there are no open period for 2008
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
455
        accounting_transaction, 'stop_action')
456
  
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
  def test_AccountingTransactionValidationRecursivePeriod(self):
    # Check we can/cannot validate when secondary period exists

    accounting_period_2007 = self.section.accounting_period_2007
    accounting_period_2007_1 = accounting_period_2007.newContent(
                                portal_type='Accounting Period',
                                start_date=DateTime('2007/01/01'),
                                stop_date=DateTime('2007/01/31'),)
    accounting_period_2007_1.start()
    accounting_period_2007_1.stop()

    accounting_period_2007_2 = accounting_period_2007.newContent(
                                portal_type='Accounting Period',
                                start_date=DateTime('2007/02/01'),
                                stop_date=DateTime('2007/02/28'),)
    accounting_period_2007_2.start()

474
    accounting_transaction = self._makeOne(
475 476 477 478 479 480 481 482 483 484 485
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.supplier,
               payment_mode='default',
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
    # validation is refused, because there are no open period for 2007-01
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
486
        accounting_transaction, 'stop_action')
487
    # in 2007-02, it's OK
488 489
    accounting_transaction.setStartDate(DateTime("2007/02/02"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
490
  
491

492 493 494
  def test_PaymentTransactionWithEmployee(self):
    # we have to set bank account if we use an asset/cash/bank account, but not
    # for our employees
495
    accounting_transaction = self._makeOne(
496 497 498 499 500 501 502 503
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.person_module.john_smith,
               payment_mode='default',
               lines=(dict(source_value=self.account_module.bank,
                           destination_value=self.account_module.bank,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
504
                           destination_value=self.account_module.receivable,
505 506 507 508
                           source_credit=500)))
    # refused because no bank account
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
509
        accounting_transaction, 'stop_action')
510 511
    # with bank account, it's OK
    bank_account = self.section.newContent(portal_type='Bank Account')
512 513
    accounting_transaction.setSourcePaymentValue(bank_account)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
514

515 516
  def test_NonBalancedAccountingTransaction(self):
    # Accounting Transactions have to be balanced to be validated
517
    accounting_transaction = self._makeOne(
518 519 520 521 522 523 524 525 526 527 528 529 530
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.payable,
                           source_asset_debit=39,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_asset_credit=38.99,
                           source_credit=500)))
    # refused because not balanced
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
531 532
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
533 534
      if line.getSourceId() == 'payable':
        line.setSourceAssetDebit(38.99)
535
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
536 537 538 539

  def test_NonBalancedDestinationAccountingTransaction(self):
    # Accounting Transactions have to be balanced to be validated,
    # also for destination
540
    accounting_transaction = self._makeOne(
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           destination_asset_debit=39,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           destination_asset_credit=38.99,
                           source_credit=500)))
    # refused because not balanced
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
556 557
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
558 559
      if line.getDestinationId() == 'receivable':
        line.setDestinationAssetDebit(38.99)
560
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
561

562 563 564
  def test_NonBalancedDestinationAccountingTransactionNoAccount(self):
    # Accounting Transactions have to be balanced to be validated,
    # also for destination
565
    accounting_transaction = self._makeOne(
566 567 568 569 570 571 572 573 574 575 576
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.payable,
                           destination_asset_debit=39,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.receivable,
                           destination_asset_credit=38.99,
                           source_credit=500)))
Jérome Perrin's avatar
Jérome Perrin committed
577
    # This is not balanced but there are no accounts on destination
578 579
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
580 581
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
582 583 584
      if line.getDestinationId() == 'receivable':
        line.setDestination(None)
    # but if there are no accounts defined it's not a problem
585
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
586

587
  def test_NonBalancedAccountingTransactionSectionOnLines(self):
588
    accounting_transaction = self._makeOne(
589 590 591 592 593 594 595 596 597 598 599 600 601
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.goods_sales,
                           destination_value=self.account_module.goods_purchase,
                           destination_section_value=self.organisation_module.client_1,
                           source_debit=500),
                      dict(source_value=self.account_module.goods_purchase,
                           source_credit=500)))

    # This is not balanced for client 1
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
602
        accounting_transaction, 'stop_action')
603

604
    for line in accounting_transaction.getMovementList():
605
      line.setDestinationSection(None)
606 607
    self.assertEquals([], accounting_transaction.checkConsistency())
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
608 609

  def test_NonBalancedAccountingTransactionDifferentSectionOnLines(self):
610
    accounting_transaction = self._makeOne(
611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.goods_sales,
                           destination_value=self.account_module.goods_purchase,
                           destination_section_value=self.organisation_module.client_1,
                           source_debit=500),
                      dict(source_value=self.account_module.goods_purchase,
                           destination_value=self.account_module.goods_sales,
                           destination_section_value=self.organisation_module.client_2,
                           source_credit=500)))

    # This is not balanced for client 1 and client 2, but if you look globally,
    # it looks balanced.
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
627 628 629
        accounting_transaction, 'stop_action')
    self.assertEquals(1, len(accounting_transaction.checkConsistency()),
                         accounting_transaction.checkConsistency())
630

631
    for line in accounting_transaction.getMovementList():
632 633 634
      line.setDestinationSectionValue(
          self.organisation_module.client_2)

635 636
    self.assertEquals([], accounting_transaction.checkConsistency())
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
637 638

  def test_NonBalancedAccountingTransactionSectionPersonOnLines(self):
639
    accounting_transaction = self._makeOne(
640 641 642 643 644 645 646 647 648 649 650 651
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.goods_purchase,
                           destination_value=self.account_module.goods_purchase,
                           destination_section_value=self.person_module.john_smith,
                           source_debit=500),
                      dict(source_value=self.account_module.goods_purchase,
                           source_credit=500)))

    # This is not balanced for john smith, but as he is a person, it's not a
    # problem
652 653
    self.assertEquals([], accounting_transaction.checkConsistency())
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
654

655 656 657 658 659
  def test_AccountingTransactionValidationRefusedWithCategoriesAsSections(self):
    # Validating a transaction with categories as sections is refused.
    # See http://wiki.erp5.org/Discussion/AccountingProblems
    category = self.section.getGroupValue()
    self.assertNotEquals(category, None)
660
    accounting_transaction = self._makeOne(
661 662 663 664 665 666 667 668 669
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               source_section_value=category,
               destination_section_value=self.organisation_module.client_1,
               resource='currency_module/yen',
               lines=(dict(source_value=self.account_module.payable,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500)))
670

671 672
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
673 674 675
        accounting_transaction, 'stop_action')
    accounting_transaction.setSourceSectionValue(self.section)
    accounting_transaction.setDestinationSectionValue(category)
676 677
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
678
        accounting_transaction, 'stop_action')
679

680 681
    accounting_transaction.setDestinationSectionValue(self.organisation_module.client_1)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
682
    
683
  def test_AccountingWorkflow(self):
684
    accounting_transaction = self._makeOne(
685 686 687 688 689 690 691 692 693 694 695
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           source_credit=500)))
    
    doActionFor = self.portal.portal_workflow.doActionFor
696 697 698
    self.assertEquals('draft', accounting_transaction.getSimulationState())
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))
699
                    
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
    doActionFor(accounting_transaction, 'plan_action')
    self.assertEquals('planned', accounting_transaction.getSimulationState())
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'confirm_action')
    self.assertEquals('confirmed', accounting_transaction.getSimulationState())
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'start_action')
    self.assertEquals('started', accounting_transaction.getSimulationState())
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
719
    
720 721 722 723
    doActionFor(accounting_transaction, 'restart_action')
    self.assertEquals('started', accounting_transaction.getSimulationState())
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))
724

725 726 727 728
    doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
729

730 731 732 733
    doActionFor(accounting_transaction, 'deliver_action')
    self.assertEquals('delivered', accounting_transaction.getSimulationState())
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
734

735 736 737
  def test_UneededSourceAssetPrice(self):
    # It is refunsed to validate an accounting transaction if lines have an
    # asset price but the resource is the same as the accounting resource
738
    accounting_transaction = self._makeOne(
739 740 741 742 743 744 745 746 747 748
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
                           source_debit=500,
                           source_asset_debit=600),
                      dict(source_value=self.account_module.receivable,
                           source_credit=500,
                           source_asset_credit=600)))

749
    section = accounting_transaction.getSourceSectionValue()
750
    self.assertEquals(section.getPriceCurrency(),
751
                      accounting_transaction.getResource())
752 753 754

    # validation is refused
    doActionFor = self.portal.portal_workflow.doActionFor
755
    self.assertRaises(ValidationFailed, doActionFor, accounting_transaction,
756 757 758
                      'stop_action')
    # and the source conversion tab is visible
    self.failUnless(
759
        accounting_transaction.AccountingTransaction_isSourceCurrencyConvertible())
760 761 762

    # if asset price is set to the same value as quantity, validation is
    # allowed
763
    for line in accounting_transaction.getMovementList():
764 765 766 767 768 769
      if line.getSourceValue() == self.account_module.payable:
        line.setSourceAssetDebit(line.getSourceDebit())
      elif line.getSourceValue() == self.account_module.receivable:
        line.setSourceAssetCredit(line.getSourceCredit())
      else:
        self.fail('wrong line ?')
770 771
    doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
772 773 774 775 776


  def test_UneededDestinationAssetPrice(self):
    # It is refunsed to validate an accounting transaction if lines have an
    # asset price but the resource is the same as the accounting resource
777
    accounting_transaction = self._makeOne(
778 779 780 781 782 783 784 785 786 787
               portal_type='Purchase Invoice Transaction',
               start_date=DateTime('2007/01/02'),
               source_section_value=self.organisation_module.client_1,
               lines=(dict(destination_value=self.account_module.payable,
                           destination_debit=500,
                           destination_asset_debit=600),
                      dict(destination_value=self.account_module.receivable,
                           destination_credit=500,
                           destination_asset_credit=600)))

788
    section = accounting_transaction.getDestinationSectionValue()
789
    self.assertEquals(section.getPriceCurrency(),
790
                      accounting_transaction.getResource())
791 792 793

    # validation is refused
    doActionFor = self.portal.portal_workflow.doActionFor
794
    self.assertRaises(ValidationFailed, doActionFor, accounting_transaction,
795 796 797
                      'stop_action')
    # and the destination conversion tab is visible
    self.failUnless(
798
        accounting_transaction.AccountingTransaction_isDestinationCurrencyConvertible())
799 800 801

    # if asset price is set to the same value as quantity, validation is
    # allowed
802
    for line in accounting_transaction.getMovementList():
803 804 805 806 807 808 809
      if line.getDestinationValue() == self.account_module.payable:
        line.setDestinationAssetDebit(line.getDestinationDebit())
      elif line.getDestinationValue() == self.account_module.receivable:
        line.setDestinationAssetCredit(line.getDestinationCredit())
      else:
        self.fail('wrong line ?')

810 811
    doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
812

813 814 815 816 817 818
  def test_CancellationAmount(self):
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
819
                           source_debit=500),
820 821 822 823 824 825 826 827 828
                      dict(source_value=self.account_module.receivable,
                           source_debit=-500,
                           cancellation_amount=True
                           )))

    self.assertEquals([], accounting_transaction.checkConsistency())
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                            'stop_action')

829

830 831 832
class TestClosingPeriod(AccountingTestCase):
  """Various tests for closing the period.
  """
833
  def beforeTearDown(self):
834
    transaction.abort()
835 836 837 838
    # we manually remove the content of stock table, because unindexObject
    # might not work correctly on Balance Transaction, and we don't want
    # leave something in stock table that will change the next test.
    self.portal.erp5_sql_connection.manage_test('truncate stock')
839
    transaction.commit()
840

841 842 843
  def test_createBalanceOnNode(self):
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
844
    period.setStopDate(DateTime(2006, 12, 31))
845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.equity,
                    source_debit=500),
               dict(source_value=self.account_module.stocks,
                    source_credit=500)))

    transaction2 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.stocks,
                    source_debit=100),
               dict(source_value=self.account_module.goods_purchase,
                    source_credit=100)))

864 865
    period.AccountingPeriod_createBalanceTransaction(
                               profit_and_loss_account=None)
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
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEquals(3, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    # this should create a balance with 3 lines,
    #   equity = 500 D
    #   stocks =     400 C
    #   pl     =     100 C 
    self.assertEquals(self.section,
                      balance_transaction.getDestinationSectionValue())
    self.assertEquals(None,
                      balance_transaction.getSourceSection())
    self.assertEquals([period], balance_transaction.getCausalityValueList())
    self.assertEquals(DateTime(2007, 1, 1),
                      balance_transaction.getStartDate())
    self.assertEquals('currency_module/euro',
                      balance_transaction.getResource())
    self.assertEquals('delivered', balance_transaction.getSimulationState())
    movement_list = balance_transaction.getMovementList()
    self.assertEquals(3, len(movement_list))

    equity_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.equity]
    self.assertEquals(1, len(equity_movement_list))
    equity_movement = equity_movement_list[0]
    self.assertEquals([], equity_movement.getValueList('resource'))
    self.assertEquals([], equity_movement.getValueList('destination_section'))
    self.assertEquals(None, equity_movement.getSource())
    self.assertEquals(None, equity_movement.getSourceSection())
    self.assertEquals(None, equity_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, equity_movement.getSourceTotalAssetPrice())
    self.assertEquals(500., equity_movement.getDestinationDebit())

    stock_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.stocks]
    self.assertEquals(1, len(stock_movement_list))
    stock_movement = stock_movement_list[0]
    self.assertEquals([], stock_movement.getValueList('resource'))
    self.assertEquals([], stock_movement.getValueList('destination_section'))
    self.assertEquals(None, stock_movement.getSource())
    self.assertEquals(None, stock_movement.getSourceSection())
    self.assertEquals(None, stock_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, stock_movement.getSourceTotalAssetPrice())
    self.assertEquals(400., stock_movement.getDestinationCredit())

    pl_movement_list = [m for m in movement_list
                        if m.getDestinationValue() is None]
    self.assertEquals(1, len(pl_movement_list))
    pl_movement = pl_movement_list[0]
    self.assertEquals([], pl_movement.getValueList('resource'))
    self.assertEquals([], pl_movement.getValueList('destination_section'))
    self.assertEquals(None, pl_movement.getSource())
    self.assertEquals(None, pl_movement.getSourceSection())
    self.assertEquals(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEquals(100., pl_movement.getDestinationCredit())


  def test_createBalanceOnMirrorSection(self):
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
931
    period.setStopDate(DateTime(2006, 12, 31))
932 933 934
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=100),
               dict(source_value=self.account_module.receivable,
                    source_credit=100)))

    transaction2 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        destination_section_value=organisation_module.client_2,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=200),
               dict(source_value=self.account_module.receivable,
                    source_credit=200)))

956
    period.AccountingPeriod_createBalanceTransaction(
957
                             profit_and_loss_account=pl.getRelativeUrl())
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
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEquals(3, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    # this should create a balance with 3 lines,
    #   pl                 = 300 D
    #   receivable/client1 =     200 C
    #   receivable/client2 =     100 C
    self.assertEquals(self.section,
                      balance_transaction.getDestinationSectionValue())
    self.assertEquals(None, balance_transaction.getSourceSection())
    self.assertEquals(DateTime(2007, 1, 1),
                      balance_transaction.getStartDate())
    self.assertEquals('currency_module/euro',
                      balance_transaction.getResource())
    self.assertEquals('delivered', balance_transaction.getSimulationState())
    movement_list = balance_transaction.getMovementList()
    self.assertEquals(3, len(movement_list))

    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
    self.assertEquals(1, len(client1_movement_list))
    client1_movement = client1_movement_list[0]
    self.assertEquals([], client1_movement.getValueList('resource'))
    self.assertEquals([], client1_movement.getValueList('destination_section'))
    self.assertEquals(None, client1_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      client1_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_1,
                      client1_movement.getSourceSectionValue())
    self.assertEquals(None, client1_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, client1_movement.getSourceTotalAssetPrice())
    self.assertEquals(100., client1_movement.getDestinationCredit())

    client2_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_2]
    self.assertEquals(1, len(client2_movement_list))
    client2_movement = client2_movement_list[0]
    self.assertEquals([], client2_movement.getValueList('resource'))
    self.assertEquals([], client2_movement.getValueList('destination_section'))
    self.assertEquals(None, client2_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      client2_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_2,
                      client2_movement.getSourceSectionValue())
    self.assertEquals(None, client2_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, client2_movement.getSourceTotalAssetPrice())
    self.assertEquals(200., client2_movement.getDestinationCredit())

    pl_movement_list = [m for m in movement_list
1011
                        if m.getDestinationValue() == pl]
1012 1013 1014 1015
    self.assertEquals(1, len(pl_movement_list))
    pl_movement = pl_movement_list[0]
    self.assertEquals([], pl_movement.getValueList('resource'))
    self.assertEquals(None, pl_movement.getSource())
1016
    self.assertEquals(pl,
1017 1018 1019 1020 1021 1022
                      pl_movement.getDestinationValue())
    self.assertEquals(None,
                      pl_movement.getSourceSection())
    self.assertEquals(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEquals(300., pl_movement.getDestinationDebit())
1023
    transaction.commit()
1024
    self.tic()
1025 1026 1027 1028 1029

  def test_createBalanceOnPayment(self):
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1030
    period.setStopDate(DateTime(2006, 12, 31))
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

    bank1 = self.section.newContent(
                    id='bank1', reference='bank1',
                    portal_type='Bank Account')
    bank2 = self.section.newContent(
                    id='bank2', reference='bank2',
                    portal_type='Bank Account')

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        destination_section_value=organisation_module.client_1,
        source_payment_value=bank1,
        title='bank 1',
        portal_type='Payment Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.receivable,
                    source_debit=100),
               dict(source_value=self.account_module.bank,
                    source_credit=100)))
    
    # we are destination on this one
    transaction2 = self._makeOne(
        stop_date=DateTime(2006, 1, 2),
        destination_section_value=self.section,
        destination_payment_value=bank2,
        source_section_value=organisation_module.client_2,
        title='bank 2',
        portal_type='Payment Transaction',
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.bank,
                    destination_debit=200),
               dict(destination_value=self.account_module.goods_purchase,
                    destination_credit=200)))

1065 1066
    period.AccountingPeriod_createBalanceTransaction(
                             profit_and_loss_account=None)
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 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
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEquals(3, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    # this should create a balance with 4 lines,
    #   receivable/client_1 = 100 D
    #   bank/bank1          =     100 C
    #   bank/bank2          = 200 D
    #   pl                  =     200 C

    self.assertEquals(self.section,
                      balance_transaction.getDestinationSectionValue())
    self.assertEquals(None,
                      balance_transaction.getSourceSection())
    self.assertEquals([period], balance_transaction.getCausalityValueList())
    self.assertEquals(DateTime(2007, 1, 1),
                      balance_transaction.getStartDate())
    self.assertEquals('currency_module/euro',
                      balance_transaction.getResource())
    self.assertEquals('delivered', balance_transaction.getSimulationState())
    movement_list = balance_transaction.getMovementList()
    self.assertEquals(4, len(movement_list))
    
    receivable_movement_list = [m for m in movement_list
        if m.getDestinationValue() == self.account_module.receivable]
    self.assertEquals(1, len(receivable_movement_list))
    receivable_movement = receivable_movement_list[0]
    self.assertEquals([], receivable_movement.getValueList('resource'))
    self.assertEquals(None, receivable_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      receivable_movement.getDestinationValue())
    self.assertEquals(self.organisation_module.client_1,
                      receivable_movement.getSourceSectionValue())
    self.assertEquals(None, receivable_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, receivable_movement.getSourceTotalAssetPrice())
    self.assertEquals(100., receivable_movement.getDestinationDebit())

    bank1_movement_list = [m for m in movement_list
                       if m.getDestinationPaymentValue() == bank1]
    self.assertEquals(1, len(bank1_movement_list))
    bank1_movement = bank1_movement_list[0]
    self.assertEquals([], bank1_movement.getValueList('resource'))
    self.assertEquals(None, bank1_movement.getSource())
    self.assertEquals(self.account_module.bank,
                      bank1_movement.getDestinationValue())
    self.assertEquals(bank1,
                      bank1_movement.getDestinationPaymentValue())
    self.assertEquals(None,
                      bank1_movement.getSourceSectionValue())
    self.assertEquals(None, bank1_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, bank1_movement.getSourceTotalAssetPrice())
    self.assertEquals(100., bank1_movement.getDestinationCredit())

    bank2_movement_list = [m for m in movement_list
                         if m.getDestinationPaymentValue() == bank2]
    self.assertEquals(1, len(bank2_movement_list))
    bank2_movement = bank2_movement_list[0]
    self.assertEquals([], bank2_movement.getValueList('resource'))
    self.assertEquals(None, bank2_movement.getSource())
    self.assertEquals(self.account_module.bank,
                      bank2_movement.getDestinationValue())
    self.assertEquals(bank2,
                      bank2_movement.getDestinationPaymentValue())
    self.assertEquals(None,
                      bank2_movement.getSourceSectionValue())
    self.assertEquals(None, bank2_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, bank2_movement.getSourceTotalAssetPrice())
    self.assertEquals(200., bank2_movement.getDestinationDebit())

    pl_movement_list = [m for m in movement_list
                         if m.getDestination() is None]
    self.assertEquals(1, len(pl_movement_list))
    pl_movement = pl_movement_list[0]
    self.assertEquals([], pl_movement.getValueList('resource'))
    self.assertEquals(None, pl_movement.getSource())
    self.assertEquals(None, pl_movement.getDestination())
    self.assertEquals(None, pl_movement.getDestinationPaymentValue())
    self.assertEquals(None, pl_movement.getSourceSectionValue())
    self.assertEquals(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEquals(200., pl_movement.getDestinationCredit())


  def test_createBalanceOnMirrorSectionMultiCurrency(self):
1154 1155 1156
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
1157 1158 1159
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1160
    period.setStopDate(DateTime(2006, 12, 31))
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        title='Yen',
        resource='currency_module/yen',
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_asset_debit=1.1,
                    source_debit=100),
               dict(source_value=self.account_module.receivable,
                    source_asset_credit=1.1,
                    source_credit=100)))

    transaction2 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        title='Dollar',
        resource='currency_module/usd',
        destination_section_value=organisation_module.client_2,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_asset_debit=2.2,
                    source_debit=200),
               dict(source_value=self.account_module.receivable,
                    source_asset_credit=2.2,
                    source_credit=200)))

1190
    period.AccountingPeriod_createBalanceTransaction(
1191
                      profit_and_loss_account=pl.getRelativeUrl())
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
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEquals(3, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    self.assertEquals(self.section,
                      balance_transaction.getDestinationSectionValue())
    self.assertEquals(None, balance_transaction.getSourceSection())
    self.assertEquals(DateTime(2007, 1, 1),
                      balance_transaction.getStartDate())
    self.assertEquals('currency_module/euro',
                      balance_transaction.getResource())

    # this should create a balance with 3 lines,
    #   pl                 = 3.3 D     ( resource acquired )
    #   receivable/client1 =     1.1 C ( resource yen ) qty=100
    #   receivable/client2 =     2.2 C ( resource usd ) qyt=200
    
    accounting_currency_precision = \
        self.portal.currency_module.euro.getQuantityPrecision()
    self.assertEquals(accounting_currency_precision, 2)

    movement_list = balance_transaction.getMovementList()
    self.assertEquals(3, len(movement_list))
    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
    self.assertEquals(1, len(client1_movement_list))
    client1_movement = client1_movement_list[0]
    self.assertEquals('currency_module/yen',
                      client1_movement.getResource())
    self.assertEquals([], client1_movement.getValueList('destination_section'))
    self.assertEquals(None, client1_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      client1_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_1,
                      client1_movement.getSourceSectionValue())
    self.assertAlmostEquals(1.1,
          client1_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
    self.assertEquals(None, client1_movement.getSourceTotalAssetPrice())
    self.assertEquals(100, client1_movement.getDestinationCredit())

    client2_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_2]
    self.assertEquals(1, len(client2_movement_list))
    client2_movement = client2_movement_list[0]
    self.assertEquals('currency_module/usd',
                      client2_movement.getResource())
    self.assertEquals([], client2_movement.getValueList('destination_section'))
    self.assertEquals(None, client2_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      client2_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_2,
                      client2_movement.getSourceSectionValue())
    self.assertAlmostEquals(2.2,
        client2_movement.getDestinationInventoriatedTotalAssetCredit(),
        accounting_currency_precision)
    self.assertEquals(None, client2_movement.getSourceTotalAssetPrice())
    self.assertEquals(200., client2_movement.getDestinationCredit())

    pl_movement_list = [m for m in movement_list
1255
                         if m.getDestinationValue() == pl]
1256 1257 1258 1259
    self.assertEquals(1, len(pl_movement_list))
    pl_movement = pl_movement_list[0]
    self.assertEquals([], pl_movement.getValueList('resource'))
    self.assertEquals(None, pl_movement.getSource())
1260
    self.assertEquals(pl,
1261 1262 1263 1264 1265 1266 1267 1268
                      pl_movement.getDestinationValue())
    self.assertEquals(None,
                      pl_movement.getSourceSection())
    self.assertEquals(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEquals(None, pl_movement.getSourceTotalAssetPrice())
    self.assertAlmostEquals(3.3,
                  pl_movement.getDestinationDebit(),
                  accounting_currency_precision)
1269
    
1270
    transaction.commit()
1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301
    self.tic()

    # now check content of stock table
    q = self.portal.erp5_sql_connection.manage_test
    self.assertEquals(1, q(
      "SELECT count(*) FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(3.3, q(
      "SELECT total_price FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(3.3, q(
      "SELECT quantity FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(self.portal.currency_module.euro.getUid(), q(
      "SELECT resource_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(self.section.getUid(), q(
      "SELECT section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(None, q(
      "SELECT mirror_section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(pl.getUid(), q(
      "SELECT node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(None, q(
      "SELECT mirror_node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(DateTime(2007, 1, 1), q(
      "SELECT date FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1302 1303


1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339
  def test_createBalanceOnMirrorSectionMultiCurrencySameMirrorSection(self):
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        title='Yen',
        resource='currency_module/yen',
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_asset_debit=1.1,
                    source_debit=100),
               dict(source_value=self.account_module.receivable,
                    source_asset_credit=1.1,
                    source_credit=100)))

    transaction2 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        title='Dollar',
        resource='currency_module/usd',
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_asset_debit=2.2,
                    source_debit=200),
               dict(source_value=self.account_module.receivable,
                    source_asset_credit=2.2,
                    source_credit=200)))
1340
    transaction.commit()
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401
    self.tic()

    period.AccountingPeriod_createBalanceTransaction(
                          profit_and_loss_account=pl.getRelativeUrl())
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEquals(3, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    self.assertEquals(self.section,
                      balance_transaction.getDestinationSectionValue())
    self.assertEquals(None, balance_transaction.getSourceSection())
    self.assertEquals(DateTime(2007, 1, 1),
                      balance_transaction.getStartDate())
    self.assertEquals('currency_module/euro',
                      balance_transaction.getResource())

    # this should create a balance with 3 lines,
    #   pl                 = 3.3 D     ( resource acquired )
    #   receivable/client1 =     1.1 C ( resource yen ) qty=100
    #   receivable/client1 =     2.2 C ( resource usd ) qyt=200
    
    accounting_currency_precision = \
        self.portal.currency_module.euro.getQuantityPrecision()
    self.assertEquals(accounting_currency_precision, 2)

    movement_list = balance_transaction.getMovementList()
    self.assertEquals(3, len(movement_list))
    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
    self.assertEquals(2, len(client1_movement_list))
    yen_movement = [x for x in client1_movement_list if
                    x.getResource() == 'currency_module/yen'][0]
    self.assertEquals([], yen_movement.getValueList('destination_section'))
    self.assertEquals(None, yen_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      yen_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_1,
                      yen_movement.getSourceSectionValue())
    self.assertAlmostEquals(1.1,
          yen_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
    self.assertEquals(None, yen_movement.getSourceTotalAssetPrice())
    self.assertEquals(100, yen_movement.getDestinationCredit())

    dollar_movement = [x for x in client1_movement_list if
                    x.getResource() == 'currency_module/usd'][0]
    self.assertEquals([], dollar_movement.getValueList('destination_section'))
    self.assertEquals(None, dollar_movement.getSource())
    self.assertEquals(self.account_module.receivable,
                      dollar_movement.getDestinationValue())
    self.assertEquals(organisation_module.client_1,
                      dollar_movement.getSourceSectionValue())
    self.assertAlmostEquals(2.2,
          dollar_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
    self.assertEquals(None, dollar_movement.getSourceTotalAssetPrice())
    self.assertEquals(200, dollar_movement.getDestinationCredit())

1402
    transaction.commit()
1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
    self.tic()

    # now check content of stock table
    q = self.portal.erp5_sql_connection.manage_test
    self.assertEquals(1, q(
      "SELECT count(*) FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(3.3, q(
      "SELECT total_price FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(3.3, q(
      "SELECT quantity FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(self.portal.currency_module.euro.getUid(), q(
      "SELECT resource_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(self.section.getUid(), q(
      "SELECT section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(None, q(
      "SELECT mirror_section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(pl.getUid(), q(
      "SELECT node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(None, q(
      "SELECT mirror_node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
    self.assertEquals(DateTime(2007, 1, 1), q(
      "SELECT date FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])


1436 1437 1438 1439 1440 1441
  def test_AccountingPeriodWorkflow(self):
    """Tests that accounting_period_workflow creates a balance transaction.
    """
    # open a period for our section
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1442
    period.setStopDate(DateTime(2006, 12, 31))
1443 1444 1445 1446 1447
    self.assertEquals('draft', period.getSimulationState())
    self.portal.portal_workflow.doActionFor(period, 'start_action')
    self.assertEquals('started', period.getSimulationState())

    # create a simple transaction in the period
1448
    accounting_transaction = self._makeOne(
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477
        start_date=DateTime(2006, 6, 30),
        portal_type='Sale Invoice Transaction',
        destination_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.receivable,
                    source_credit=100),
               dict(source_value=self.account_module.goods_purchase,
                    source_debit=100)))
    self.assertEquals(1, len(self.accounting_module))

    # close the period
    self.portal.portal_workflow.doActionFor(period, 'stop_action')
    self.assertEquals('stopped', period.getSimulationState())
    # reopen it, then close it got real
    self.portal.portal_workflow.doActionFor(period, 'restart_action')
    self.assertEquals('started', period.getSimulationState())
    self.portal.portal_workflow.doActionFor(period, 'stop_action')
    self.assertEquals('stopped', period.getSimulationState())
    
    pl_account = self.portal.account_module.newContent(
                    portal_type='Account',
                    account_type='equity',
                    gap='my_country/my_accounting_standards/1',
                    title='Profit & Loss')
    pl_account.validate()
    self.portal.portal_workflow.doActionFor(
            period, 'deliver_action',
            profit_and_loss_account=pl_account.getRelativeUrl())

1478
    transaction.commit()
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
    self.tic()
    self.assertEquals('delivered', period.getSimulationState())
    
    # this created a balance transaction
    balance_transaction_list = self.accounting_module.contentValues(
                                  portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]

    # and this transaction must use the account we used in the workflow action.
    self.assertEquals(1, len([m for m in
                              balance_transaction.getMovementList()
                              if m.getDestinationValue() == pl_account]))


  def test_SecondAccountingPeriod(self):
    """Tests having two accounting periods.
    """
    period1 = self.section.newContent(portal_type='Accounting Period')
    period1.setStartDate(DateTime(2006, 1, 1))
1499
    period1.setStopDate(DateTime(2006, 12, 31))
1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
    period1.start()
    
    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        source_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=100),
               dict(destination_value=self.account_module.payable,
                    destination_credit=100)))
    period1.stop()
    # deliver the period1 using workflow, so that we have 
    pl_account = self.portal.account_module.newContent(
                    portal_type='Account',
                    account_type='equity',
                    gap='my_country/my_accounting_standards/1',
                    title='Profit & Loss')
    pl_account.validate()
    self.portal.portal_workflow.doActionFor(
            period1, 'deliver_action',
            profit_and_loss_account=pl_account.getRelativeUrl())
    
    balance_transaction_list = self.accounting_module.contentValues(
                                  portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction1 = balance_transaction_list[0]
    
    period2 = self.section.newContent(portal_type='Accounting Period')
    period2.setStartDate(DateTime(2007, 1, 1))
1530
    period2.setStopDate(DateTime(2007, 12, 31))
1531 1532 1533 1534 1535 1536
    period2.start()

    transaction2 = self._makeOne(
        start_date=DateTime(2007, 1, 2),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
1537 1538 1539 1540
        lines=(dict(source_value=self.account_module.equity,
                    source_debit=100),
               dict(source_value=pl_account,
                    source_credit=100)))
1541 1542 1543 1544 1545 1546 1547 1548 1549
    transaction3 = self._makeOne(
        start_date=DateTime(2007, 1, 3),
        portal_type='Purchase Invoice Transaction',
        source_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=300),
               dict(destination_value=self.account_module.payable,
                    destination_credit=300)))
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
    period2.AccountingPeriod_createBalanceTransaction(
                profit_and_loss_account=pl_account.getRelativeUrl())
    balance_transaction_list = [tr for tr in 
                          self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
                          if tr != balance_transaction1]
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction2 = balance_transaction_list[0]
    
    self.assertEquals(DateTime(2008, 1, 1),
                      balance_transaction2.getStartDate())
    # this should create a balance with 3 lines,
    #   equity          = 100 D
    #   payable/client1 =       100 + 300 C
    #   pl              = 300 D    
    movement_list = balance_transaction2.getMovementList()
    self.assertEquals(3, len(movement_list))

    equity_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.equity]
    self.assertEquals(1, len(equity_movement_list))
    equity_movement = equity_movement_list[0]
    self.assertEquals(100., equity_movement.getDestinationDebit())
    
    payable_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.payable]
    self.assertEquals(1, len(payable_movement_list))
    payable_movement = payable_movement_list[0]
    self.assertEquals(400., payable_movement.getDestinationCredit())
    
    pl_movement_list = [m for m in movement_list
          if m.getDestinationValue() == pl_account]
    self.assertEquals(1, len(pl_movement_list))
    pl_movement = pl_movement_list[0]
    self.assertEquals(300., pl_movement.getDestinationDebit())


  def test_ProfitAndLossUsedInPeriod(self):
    """When the profit and loss account has a non zero balance at the end of
    the period, AccountingPeriod_createBalanceTransaction script should add
    this balance and the new calculated profit and loss to have only one line.
    """
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1595
    period.setStopDate(DateTime(2006, 12, 31))
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
    pl_account = self.portal.account_module.newContent(
                    portal_type='Account',
                    account_type='equity',
                    gap='my_country/my_accounting_standards/1',
                    title='Profit & Loss')
    pl_account.validate()

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_purchase,
                    source_debit=400),
               dict(source_value=pl_account,
                    source_debit=100),
               dict(source_value=self.account_module.stocks,
                    source_credit=500)))

    period.AccountingPeriod_createBalanceTransaction(
                  profit_and_loss_account=pl_account.getRelativeUrl())
    
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEquals(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]
1621
    balance_transaction.alternateReindexObject()
1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
    movement_list = balance_transaction.getMovementList()
    self.assertEquals(2, len(movement_list))

    pl_movement_list = [m for m in movement_list
                      if m.getDestinationValue() == pl_account]
    self.assertEquals(1, len(pl_movement_list))
    self.assertEquals(500, pl_movement_list[0].getDestinationDebit())
    
    stock_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.stocks]
    self.assertEquals(1, len(stock_movement_list))
    self.assertEquals(500, stock_movement_list[0].getDestinationCredit())
    

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
  def test_InventoryIndexingNodeAndMirrorSection(self):
    # Balance Transactions are indexed as Inventories.
    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        destination_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.receivable,
                    source_debit=100),
               dict(source_value=self.account_module.goods_sales,
                    source_credit=100)))

    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                source_section_value=self.organisation_module.client_1,
                destination_debit=100,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.stocks,
                destination_credit=100,)
    balance.stop()
    balance.deliver()
    balance.immediateReindexObject()

    # now check inventory
    stool = self.getSimulationTool()
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(100, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(100, stool.getInventory(
                    section_uid=self.section.getUid(),
                    mirror_section_uid=self.organisation_module.client_1.getUid(),
                    node_uid=node_uid))
    self.assertEquals(100, stool.getInventoryAssetPrice(
                    section_uid=self.section.getUid(),
                    node_uid=node_uid))
    # and only one movement is returned by getMovementHistoryList
    self.assertEquals(1, len(stool.getMovementHistoryList(
                    section_uid=self.section.getUid(),
                    node_uid=node_uid)))
    
    # the account 'goods_sales' has a balance of -100
    node_uid = self.account_module.goods_sales.getUid()
    self.assertEquals(-100, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))

    # the account 'stocks' has a balance of -100
    node_uid = self.account_module.stocks.getUid()
    self.assertEquals(-100, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))

  def test_InventoryIndexingNodeDiffOnNode(self):
    # Balance Transactions are indexed as Inventories.
    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.receivable,
                    source_debit=100),
               dict(source_value=self.account_module.stocks,
                    source_credit=100)))

    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                destination_debit=150,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.stocks,
                destination_credit=90,)
    balance.stop()
1722
    transaction.commit()
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738
    self.tic()
    
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 150
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(150, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    # movement history list shows 2 movements, the initial with qty 100, and
    # the balance with quantity 50

    # the account 'stocks' has a balance of -100
    node_uid = self.account_module.stocks.getUid()
    self.assertEquals(-90, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760

  def test_IndexingBalanceTransactionLinesWithSameNodes(self):
    # Indexes balance transaction without any previous inventory.
    # This make sure that indexing two balance transaction lines with same
    # categories does not try to insert duplicate keys in category table.
    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                source_section_value=self.organisation_module.client_1,
                destination_value=self.account_module.receivable,
                destination_debit=150,)
    balance.newContent(
                portal_type='Balance Transaction Line',
                source_section_value=self.organisation_module.client_2,
                destination_value=self.account_module.receivable,
                destination_debit=30,)

    balance.stop()
1761
    transaction.commit()
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
    self.tic()
    
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 150 + 30
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(180, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(150, stool.getInventory(
                              section_uid=self.section.getUid(),
                              mirror_section_uid=self.organisation_module\
                                                    .client_1.getUid(),
                              node_uid=node_uid))
    self.assertEquals(30, stool.getInventory(
                              section_uid=self.section.getUid(),
                              mirror_section_uid=self.organisation_module\
                                                    .client_2.getUid(),
                              node_uid=node_uid))
1780 1781
    

1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797
  def test_BalanceTransactionLineBrainGetObject(self):
    # Balance Transaction Line can be retrieved using Brain.getObject
    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                destination_debit=100,)
    balance_line2 = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.payable,
                destination_credit=100,)
    balance.stop()
1798
    transaction.commit()
1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823
    self.tic()
    
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(100, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    # there is one line in getMovementHistoryList:
    mvt_history_list = stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt_history_list[0].getObject(),
                      balance_line)

    # There is also one line on payable account
    node_uid = self.account_module.payable.getUid()
    mvt_history_list = stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)
    self.assertEquals(1, len(mvt_history_list))
    self.assertEquals(mvt_history_list[0].getObject(),
                      balance_line2)

1824

1825 1826
  def test_BalanceTransactionDate(self):
    # check that dates are correctly used for Balance Transaction indexing
1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854
    organisation_module = self.organisation_module

    transaction1 = self._makeOne(
        start_date=DateTime(2006, 12, 31),
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=100),
               dict(source_value=self.account_module.receivable,
                    source_credit=100)))

    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2007, 1, 1),
                          resource_value=self.currency_module.euro,)
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.equity,
                destination_debit=100,)
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                source_section_value=organisation_module.client_1,
                destination_value=self.account_module.receivable,
                destination_credit=100,)
    balance.stop()
    balance.deliver()
1855
    transaction.commit()
1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
    self.tic()

    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of -100
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(-100, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(1, len(stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)))

    # this is a transaction with the same date as the balance transaction, but
    # this transaction should not be taken into account when we reindex the
    # Balance Transaction.
    transaction2 = self._makeOne(
        start_date=DateTime(2007, 1, 1),
        destination_section_value=organisation_module.client_1,
        portal_type='Sale Invoice Transaction',
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=50),
               dict(source_value=self.account_module.receivable,
                    source_credit=50)))
1880
    transaction.commit()
1881 1882 1883
    self.tic()
    # let's try to reindex and check if values are still OK
    balance.reindexObject()
1884
    transaction.commit()
1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897
    self.tic()
    
    self.assertEquals(-150, stool.getInventory(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(2, len(stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)))


  def test_BalanceTransactionDateInInventoryAPI(self):
    # check that dates are correctly used for Balance Transaction when making
    # reports using inventory API
1898 1899 1900 1901 1902 1903 1904 1905 1906 1907
    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                destination_debit=100,)
    balance.stop()
1908
    transaction.commit()
1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945
    self.tic()
    
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100 after 2006/12/31
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(100, stool.getInventory(
                              at_date=DateTime(2006, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(1, len(stool.getMovementHistoryList(
                              at_date=DateTime(2006, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)))
    # and 0 before
    self.assertEquals(0, stool.getInventory(
                              at_date=DateTime(2005, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    self.assertEquals(0, len(stool.getMovementHistoryList(
                              at_date=DateTime(2005, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)))


  def test_BalanceTransactionLineInventoryAPIParentPortalType(self):
    # related keys like parent_portal_type= can be used in inventory API to get
    # balance transaction lines
    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                destination_debit=100,)
    balance.stop()
1946
    transaction.commit()
1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961
    self.tic()
    
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
    self.assertEquals(100, stool.getInventory(
                              parent_portal_type='Balance Transaction',
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    # there is one line in getMovementHistoryList:
    mvt_history_list = stool.getMovementHistoryList(
                              parent_portal_type='Balance Transaction',
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)
    self.assertEquals(1, len(mvt_history_list))
1962

1963
  # TODO : test deletion ?
1964

1965 1966 1967 1968 1969 1970

class TestAccountingExport(AccountingTestCase):
  """Test accounting export features with erp5_ods_style.
  """
  def test_export_transaction(self):
    # test we can export an accounting transaction as ODS
1971
    accounting_transaction = self._makeOne(lines=(
1972 1973
              dict(source_value=self.account_module.payable,
                   quantity=200),))
1974
    ods_data = accounting_transaction.Base_viewAsODS(
1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989
                    form_id='AccountingTransaction_view')
    from Products.ERP5OOo.OOoUtils import OOoParser
    parser = OOoParser()
    parser.openFromString(ods_data)
    content_xml = parser.oo_files['content.xml']
    # just make sure that we have the correct account name
    self.assertEquals(
        '40 - Payable',
        self.account_module.payable.Account_getFormattedTitle())
    # check that this account name can be found in the content
    self.assertTrue('40 - Payable' in content_xml)
    # check that we don't have unknown categories
    self.assertFalse('???' in content_xml)


1990 1991 1992
class TestTransactions(AccountingTestCase):
  """Test behaviours and utility scripts for Accounting Transactions.
  """
1993
  
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046
  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'):
      self.portal.portal_ids.dict_ids.clear()
    section_period_2001 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
                        start_date=DateTime(2001, 01, 01),
                        stop_date=DateTime(2001, 12, 31))
    section_period_2001.start()
    section_period_2002 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2002',
                        start_date=DateTime(2002, 01, 01),
                        stop_date=DateTime(2002, 12, 31))
    section_period_2002.start()

    accounting_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
              start_date=DateTime(2001, 01, 01),
              stop_date=DateTime(2001, 01, 01))
    self.portal.portal_workflow.doActionFor(
          accounting_transaction, 'stop_action')
    # The reference generated for the source section uses the short title from
    # the accounting period
    self.assertEquals('code-2001-1', accounting_transaction.getSourceReference())
    # This works, because we use
    # 'AccountingTransaction_getAccountingPeriodForSourceSection' script
    self.assertEquals(section_period_2001, accounting_transaction\
              .AccountingTransaction_getAccountingPeriodForSourceSection())
    # If no accounting period exists on this side, the transaction date is
    # used.
    self.assertEquals('2001-1', accounting_transaction.getDestinationReference())

    other_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_2,
              start_date=DateTime(2001, 01, 01),
              stop_date=DateTime(2001, 01, 01))
    self.portal.portal_workflow.doActionFor(other_transaction, 'stop_action')
    self.assertEquals('code-2001-2', other_transaction.getSourceReference())
    self.assertEquals('2001-1', other_transaction.getDestinationReference())

    next_year_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
              start_date=DateTime(2002, 01, 01),
              stop_date=DateTime(2002, 01, 01))
    self.portal.portal_workflow.doActionFor(next_year_transaction, 'stop_action')
    self.assertEquals('code-2002-1', next_year_transaction.getSourceReference())
    self.assertEquals('2002-1', next_year_transaction.getDestinationReference())

2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
  def test_SourceDestinationReferenceSecurity(self):
    # Check that we don't need specific roles to set source reference and
    # destination reference, as long as we can pass the workflow transition

    # clear all existing ids in portal ids
    if hasattr(self.portal.portal_ids, 'dict_ids'):
      self.portal.portal_ids.dict_ids.clear()

    section_period_2001 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
                        start_date=DateTime(2001, 01, 01),
                        stop_date=DateTime(2001, 12, 31))
    section_period_2001.start()

    accounting_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
              start_date=DateTime(2001, 01, 01),
              stop_date=DateTime(2001, 01, 01))
    accounting_transaction.manage_permission('Modify portal content',
                                             roles=['Manager'], acquire=0)
2068 2069
    self.assertFalse(_checkPermission('Modify portal content',
                                      accounting_transaction))
2070 2071 2072
    accounting_transaction.stop()
    self.assertEquals('code-2001-1', accounting_transaction.getSourceReference())

2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
  def test_generate_sub_accounting_periods(self):
    accounting_period_2007 = self.section.newContent(
                                portal_type='Accounting Period',
                                start_date=DateTime('2007/01/01'),
                                stop_date=DateTime('2007/12/31'),)
    accounting_period_2007.start()
    
    accounting_period_2007.AccountingPeriod_createSecondaryPeriod(
          frequency='monthly', open_periods=1)
    sub_period_list = sorted(accounting_period_2007.contentValues(),
                              key=lambda x:x.getStartDate())
    self.assertEquals(12, len(sub_period_list))
    first_period = sub_period_list[0]
    self.assertEquals(DateTime(2007, 1, 1), first_period.getStartDate())
    self.assertEquals(DateTime(2007, 1, 31), first_period.getStopDate())
    self.assertEquals('2007-01', first_period.getShortTitle())
    self.assertEquals('January', first_period.getTitle())


2092
  def test_SearchableText(self):
2093
    accounting_transaction = self._makeOne(title='A new Transaction',
2094 2095
                                description="A description",
                                comment="Some comments")
2096
    searchable_text = accounting_transaction.SearchableText()
2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    self.assertTrue('A new Transaction' in searchable_text)
    self.assertTrue('A description' in searchable_text)
    self.assertTrue('Some comments' in searchable_text)

  # 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.account_module.bank, line.getSourceValue())
      else:
        eq(quantity, line.getSourceDebit())
        eq(self.account_module.receivable, line.getSourceValue())
    # this transaction can be validated
    eq([], payment.checkConsistency())
    self.portal.portal_workflow.doActionFor(payment, 'stop_action')
    eq('stopped', payment.getSimulationState())

  def test_Invoice_createRelatedPaymentTransactionSimple(self):
    # Simple case of creating a related payment transaction.
    payment_node = self.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100)))
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.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.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=60),
                      dict(source_value=self.account_module.receivable,
                           source_credit=40,
                           grouping_reference='A'),))
    
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.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.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=60),
                      dict(source_value=self.account_module.receivable,
                           source_credit=40,
                           destination_section_value=self.organisation_module.client_2),))
    
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 60)
 
  def test_Invoice_createRelatedPaymentTransactionRelatedInvoice(self):
    # Simple creating a related payment transaction when we have related
    # transactions.
    payment_node = self.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100),))
    accounting_transaction = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               causality_value=invoice,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_credit=20),
                      dict(source_value=self.account_module.receivable,
                           source_debit=20),))

    accounting_transaction.setCausalityValue(invoice)
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                           'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
2207
    transaction.commit()
2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
    self.tic()
    
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.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.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100),))
    accounting_transaction = self._makeOne(
               source_section_value=self.organisation_module.client_1,
               destination_section_value=self.section,
               causality_value=invoice,
               lines=(dict(destination_value=self.account_module.goods_purchase,
                           destination_credit=20),
                      dict(destination_value=self.account_module.receivable,
                           destination_debit=20),))
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                            'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
2238
    transaction.commit()
2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
    self.tic()

    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.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.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100),))
    accounting_transaction = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               causality_value=invoice,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_credit=20),
                      dict(source_value=self.account_module.receivable,
                           source_debit=20),))

    other_accounting_transaction = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               causality_value=invoice,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_credit=20),
                      dict(source_value=self.account_module.receivable,
                           source_debit=20),))

    other_accounting_transaction.cancel()
2275
    transaction.commit()
2276 2277 2278 2279 2280 2281 2282 2283 2284
    self.tic()

    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
    self._checkRelatedSalePayment(invoice, payment, payment_node, 100)

2285 2286 2287 2288 2289 2290 2291 2292
  # tests for Grouping References
  def test_GroupingReferenceResetedOnCopyPaste(self):
    accounting_module = self.portal.accounting_module
    for portal_type in self.portal.getPortalAccountingTransactionTypeList():
      if portal_type == 'Balance Transaction':
        # Balance Transaction cannot be copy and pasted, because they are not
        # in visible allowed types.
        continue
2293
      accounting_transaction = accounting_module.newContent(
2294
                            portal_type=portal_type)
2295
      line = accounting_transaction.newContent(
2296 2297 2298 2299
                  id = 'line_with_grouping_reference',
                  grouping_reference='A',
                  portal_type=transaction_to_line_mapping[portal_type])

2300
      cp = accounting_module.manage_copyObjects(ids=[accounting_transaction.getId()])
2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374
      copy_id = accounting_module.manage_pasteObjects(cp)[0]['new_id']
      self.failIf(accounting_module[copy_id]\
          .line_with_grouping_reference.getGroupingReference())

  def test_AccountingTransaction_lineResetGroupingReference(self):
    invoice = self._makeOne(
               title='First Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_with_grouping_reference',
                           grouping_reference='A'),))
    invoice_line = invoice.line_with_grouping_reference

    other_account_invoice = self._makeOne(
               title='Other Account Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.goods_sales,
                           source_credit=100,
                           id='line_with_grouping_reference',
                           grouping_reference='A'),))
    other_account_line = other_account_invoice.line_with_grouping_reference
    
    other_section_invoice = self._makeOne(
               title='Other Section Invoice',
               destination_section_value=self.organisation_module.client_2,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_with_grouping_reference',
                           grouping_reference='A'),))
    other_section_line = other_section_invoice.line_with_grouping_reference

    other_letter_invoice = self._makeOne(
               title='Other letter Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_with_grouping_reference',
                           grouping_reference='B'),))
    other_letter_line = other_letter_invoice.line_with_grouping_reference

    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               source_payment_value=self.section.newContent(
                                            portal_type='Bank Account'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
                           id='line_with_grouping_reference',
                           grouping_reference='A',
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
    payment_line = payment.line_with_grouping_reference
    
    # reset from the payment line, the invoice line from the same group will be
    # ungrouped
    payment_line.AccountingTransactionLine_resetGroupingReference()
    self.failIf(payment_line.getGroupingReference())
    self.failIf(invoice_line.getGroupingReference())

    # other lines are not touched:
    self.failUnless(other_account_line.getGroupingReference())
    self.failUnless(other_section_line.getGroupingReference())
    self.failUnless(other_letter_line.getGroupingReference())

2375
  def test_automatically_setting_grouping_reference(self):
2376 2377 2378 2379 2380 2381 2382
    invoice = self._makeOne(
               title='First Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
2383 2384
                           id='line_for_grouping_reference',)))
    invoice_line = invoice.line_for_grouping_reference
2385 2386 2387 2388 2389

    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               simulation_state='delivered',
2390
               causality_value=invoice,
2391 2392 2393 2394
               source_payment_value=self.section.newContent(
                                            portal_type='Bank Account'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
2395
                           id='line_for_grouping_reference',
2396 2397 2398
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
2399
    payment_line = payment.line_for_grouping_reference
2400
    
2401 2402 2403 2404 2405
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())
    
    # lines match, they are automatically grouped
    invoice.stop()
2406 2407
    self.failUnless(invoice_line.getGroupingReference())
    self.failUnless(payment_line.getGroupingReference())
2408 2409 2410
  
    # when restarting, grouping is removed
    invoice.restart()
2411
    transaction.commit()
2412
    self.tic()
2413 2414 2415
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())
    invoice.stop()
2416 2417
    self.failUnless(invoice_line.getGroupingReference())
    self.failUnless(payment_line.getGroupingReference())
2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444

  def test_automatically_setting_grouping_reference_only_related(self):
    invoice = self._makeOne(
               title='First Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_for_grouping_reference',)))
    invoice_line = invoice.line_for_grouping_reference

    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               simulation_state='delivered',
               # payment is not related with invoice, so no automatic grouping
               # will occur
               source_payment_value=self.section.newContent(
                                            portal_type='Bank Account'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
                           id='line_for_grouping_reference',
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
    payment_line = payment.line_for_grouping_reference
2445 2446 2447
    
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())
2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462
    
    invoice.stop()
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())

  def test_automatically_setting_grouping_reference_same_section(self):
    invoice = self._makeOne(
               title='First Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_for_grouping_reference',)))
    invoice_line = invoice.line_for_grouping_reference
2463

2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               simulation_state='delivered',
               causality_value=invoice,
               source_payment_value=self.section.newContent(
                                            portal_type='Bank Account'),
               destination_section_value=self.organisation_module.client_2,
               lines=(dict(source_value=self.account_module.receivable,
                           id='line_for_grouping_reference',
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
    payment_line = payment.line_for_grouping_reference
    
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())
    
    # different sections, no grouping
    invoice.stop()
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())
2486

2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517
  def test_automatically_unsetting_grouping_reference_when_cancelling(self):
    invoice = self._makeOne(
               title='First Invoice',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           id='line_for_grouping_reference',)))
    invoice_line = invoice.line_for_grouping_reference

    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               simulation_state='delivered',
               causality_value=invoice,
               source_payment_value=self.section.newContent(
                                            portal_type='Bank Account'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
                           id='line_for_grouping_reference',
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
    payment_line = payment.line_for_grouping_reference

    invoice.stop()
    self.failUnless(invoice_line.getGroupingReference())
    self.failUnless(payment_line.getGroupingReference())

    invoice.cancel()
2518
    transaction.commit()
2519 2520 2521 2522
    self.tic()
    self.failIf(invoice_line.getGroupingReference())
    self.failIf(payment_line.getGroupingReference())

2523 2524
  def test_AccountingTransaction_getTotalDebitCredit(self):
    # source view
2525
    accounting_transaction = self._makeOne(
2526 2527 2528 2529 2530 2531 2532 2533 2534
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           source_credit=400)))
2535 2536 2537
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(400, accounting_transaction.AccountingTransaction_getTotalCredit())
2538 2539

    # destination view
2540
    accounting_transaction = self._makeOne(
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               source_section_value=self.organisation_module.client_1,
               destination_section_value=self.section,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           destination_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           destination_credit=400)))
2551 2552 2553
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(400, accounting_transaction.AccountingTransaction_getTotalCredit())
2554 2555

    # source view, with conversion on our side
2556
    accounting_transaction = self._makeOne(
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           source_asset_debit=50,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           source_asset_credit=40,
                           source_credit=400)))
2568 2569 2570
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(50, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(40, accounting_transaction.AccountingTransaction_getTotalCredit())
2571 2572

    # destination view, with conversion on our side
2573
    accounting_transaction = self._makeOne(
2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               source_section_value=self.organisation_module.client_1,
               destination_section_value=self.section,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           destination_asset_debit=50,
                           destination_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           destination_asset_credit=40,
                           destination_credit=400)))
2586 2587 2588
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(50, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(40, accounting_transaction.AccountingTransaction_getTotalCredit())
2589 2590

    # source view, with conversion on other side
2591
    accounting_transaction = self._makeOne(
2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           destination_asset_debit=50,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           destination_asset_credit=40,
                           source_credit=400)))
2603 2604 2605
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(400, accounting_transaction.AccountingTransaction_getTotalCredit())
2606 2607
    
    # destination view, with conversion on other side
2608
    accounting_transaction = self._makeOne(
2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               source_section_value=self.organisation_module.client_1,
               destination_section_value=self.section,
               lines=(dict(source_value=self.account_module.payable,
                           destination_value=self.account_module.receivable,
                           source_asset_debit=50,
                           destination_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.payable,
                           source_asset_credit=40,
                           destination_credit=400)))
2621 2622 2623
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
    self.assertEquals(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEquals(400, accounting_transaction.AccountingTransaction_getTotalCredit())
2624

2625

2626

2627
class TestAccountingWithSequences(AccountingTestCase):
2628 2629
  """The first test for Accounting
  """
2630 2631 2632 2633 2634 2635 2636 2637 2638
  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
2639
  def playSequence(self, sequence_string, quiet=1) :
2640 2641
    sequence_list = SequenceList()
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
2642
    sequence_list.play(self, quiet=quiet)
2643
  
2644
  account_portal_type           = 'Account'
2645
  accounting_period_portal_type = 'Accounting Period'
2646 2647
  accounting_transaction_portal_type = 'Accounting Transaction'
  accounting_transaction_line_portal_type = 'Accounting Transaction Line'
2648 2649 2650 2651 2652 2653 2654 2655
  currency_portal_type          = 'Currency'
  organisation_portal_type      = 'Organisation'
  sale_invoice_portal_type      = 'Sale Invoice Transaction'
  sale_invoice_transaction_line_portal_type = 'Sale Invoice Transaction Line'
  purchase_invoice_portal_type      = 'Purchase Invoice Transaction'
  purchase_invoice_transaction_line_portal_type = \
                'Purchase Invoice Transaction Line'

2656 2657 2658
  start_date = DateTime(2004, 01, 01)
  stop_date  = DateTime(2004, 12, 31)

2659 2660
  default_region = 'europe/west/france'

2661 2662 2663
  def getTitle(self):
    return "Accounting"
  
2664 2665
  def afterSetUp(self):
    """Prepare the test."""
2666 2667 2668 2669 2670
    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
2671
    self.createCategories()
2672 2673 2674
    self.createCurrencies()
    self.createEntities()
    self.createAccounts()
Jérome Perrin's avatar
Jérome Perrin committed
2675
    self.validateRules()
2676 2677 2678 2679 2680

    # 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',
2681
         priority=Priority.USER )
2682 2683
    self.workflow_tool.doActionFor(self.pref, 'enable_action')

2684 2685
    self.login()

2686 2687 2688 2689
  def beforeTearDown(self):
    """Cleanup for next test.
    All tests uses the same accounts and same entities, so we just cleanup
    accounting module and simulation. """
2690
    transaction.abort()
2691 2692
    for folder in (self.accounting_module, self.portal.portal_simulation):
      folder.manage_delObjects([i for i in folder.objectIds()])
2693
    transaction.commit()
2694 2695
    self.tic()

2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
  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
2707
    for cat_string in self.getNeededCategoryList():
2708 2709
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
2710 2711
      for cat in cat_string.split("/")[1:]:
        if not cat in path.objectIds():
2712
          path = path.newContent(
2713 2714 2715 2716 2717 2718
            portal_type='Category',
            id=cat,
            immediate_reindex=1)
        else:
          path = path[cat]
          
2719 2720 2721 2722 2723 2724 2725
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
                
  def getNeededCategoryList(self):
2726
    """Returns a list of categories that should be created."""
2727
    return ('group/client', 'group/vendor/sub1', 'group/vendor/sub2',
2728
            'payment_mode/check', 'region/%s' % self.default_region, )
2729 2730
  
  def stepTic(self, **kw):
2731
    """Flush activity queue. """
2732
    self.tic()
2733 2734 2735 2736
  
  def createEntities(self):
    """Create entities. """
    self.client = self.getOrganisationModule().newContent(
2737
        title = 'Client',
2738
        portal_type = self.organisation_portal_type,
2739
        group = "client",
2740
        price_currency = "currency_module/USD")
2741
    self.section = self.vendor = self.getOrganisationModule().newContent(
2742
        title = 'Vendor',
2743
        portal_type = self.organisation_portal_type,
2744
        group = "vendor/sub1",
2745 2746
        price_currency = "currency_module/EUR")
    self.other_vendor = self.getOrganisationModule().newContent(
2747
        title = 'Other Vendor',
2748
        portal_type = self.organisation_portal_type,
2749
        group = "vendor/sub2",
2750
        price_currency = "currency_module/EUR")
2751
    # validate entities
2752
    for entity in (self.client, self.vendor, self.other_vendor):
2753 2754
      entity.setRegion(self.default_region)
      self.getWorkflowTool().doActionFor(entity, 'validate_action')
2755
    transaction.commit()
2756
    self.tic()
2757
    
2758 2759 2760 2761 2762 2763 2764
  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 )
2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776
  
  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] )
2777
    
2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790
  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,
2791
                        'start_action' )
2792
    self.assertEquals(accounting_period.getSimulationState(),
2793
                      'started')
2794 2795 2796 2797 2798 2799
                      
  def stepConfirmAccountingPeriod(self, sequence, **kw):
    """Confirm the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
    self.getPortal().portal_workflow.doActionFor(
                        accounting_period,
2800
                        'stop_action' )
2801
    self.assertEquals(accounting_period.getSimulationState(),
2802
                      'stopped')
2803

2804 2805 2806 2807 2808
  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,
2809
          accounting_period, 'stop_action' )
2810

2811 2812 2813
  def stepDeliverAccountingPeriod(self, sequence, **kw):
    """Deliver the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
2814 2815
    # take any account for profit and loss account, here we don't care
    profit_and_loss_account = self.portal.account_module.contentValues()[0]
2816
    self.getPortal().portal_workflow.doActionFor(
2817 2818
           accounting_period, 'deliver_action',
           profit_and_loss_account=profit_and_loss_account.getRelativeUrl())
2819
    self.assertEquals(accounting_period.getSimulationState(),
2820
                      'delivered')
2821 2822 2823 2824
    
  def stepCheckAccountingPeriodDelivered(self, sequence, **kw):
    """Check the Accounting Period is delivered."""
    accounting_period = sequence.get('accounting_period')
2825 2826
    self.assertEquals(accounting_period.getSimulationState(),
                      'delivered')
2827
    
2828 2829 2830 2831 2832 2833 2834 2835
  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(
2836
          portal_type = self.currency_portal_type,
2837 2838
          reference = "EUR", id = "EUR" )
      self.USD = currency_module.newContent(
2839
          portal_type = self.currency_portal_type,
2840 2841
          reference = "USD", id = "USD" )
      self.YEN = currency_module.newContent(
2842
          portal_type = self.currency_portal_type,
2843
          reference = "YEN", id = "YEN" )
2844
      transaction.commit()
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854
      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)
2855
  
2856 2857 2858 2859
  def createAccounts(self):
    """Create some accounts.
    """
    receivable = self.receivable_account = self.getAccountModule().newContent(
2860 2861 2862
          title = 'receivable',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable' )
2863
    payable = self.payable_account = self.getAccountModule().newContent(
2864 2865 2866
          title = 'payable',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable' )
2867
    expense = self.expense_account = self.getAccountModule().newContent(
2868 2869 2870
          title = 'expense',
          portal_type = self.account_portal_type,
          account_type = 'expense' )
2871
    income = self.income_account = self.getAccountModule().newContent(
2872 2873 2874
          title = 'income',
          portal_type = self.account_portal_type,
          account_type = 'income' )
2875 2876
    collected_vat = self.collected_vat_account = self\
                                        .getAccountModule().newContent(
2877 2878 2879
          title = 'collected_vat',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable/collected_vat' )
2880 2881
    refundable_vat = self.refundable_vat_account = self\
                                        .getAccountModule().newContent(
2882 2883 2884
          title = 'refundable_vat',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable/refundable_vat' )
2885
    bank = self.bank_account = self.getAccountModule().newContent(
2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898
          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)
    
2899 2900 2901 2902 2903 2904 2905
    self.account_list = [ receivable,
                          payable,
                          expense,
                          income,
                          collected_vat,
                          refundable_vat,
                          bank ]
2906

2907
    for account in self.account_list :
2908
      account.validate()
2909
      self.failUnless('Site Error' not in account.view())
2910
      self.assertEquals(account.getValidationState(), 'validated')
2911
    transaction.commit()
2912
    self.tic()
2913

2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924
  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 )
2925 2926
  
    
2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940
  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,
2941
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
2942 2943 2944 2945
        'receivable' : 90,      'destination_converted_payable' : 100,
        'currency' : 'currency_module/EUR' },
      
      { 'income' : -100,        'destination_converted_expense' : -200,
2946
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973
        '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 = []
2974 2975 2976
    date_list = sequence.get('date_list')
    if not date_list : date_list = [ DateTime(2004, 12, 31) ]
    i = 0
2977
    for invoice_prop in invoice_prop_list :
2978 2979
      i += 1
      date = date_list[i % len(date_list)]
2980 2981 2982 2983 2984 2985 2986
      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'],
2987
          start_date = date, stop_date = date,
2988
          created_by_builder = 0,
2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013
      )
      
      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 )
  
3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
  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,
3029
        created_by_builder = 0,
3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045
    )
    
    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')
3046 3047 3048 3049 3050 3051 3052 3053
  
  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')
3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066

  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')
      
3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080
  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() :
3081
            calculated_balance += (
3082 3083 3084
                    line.getSourceDebit() - line.getSourceCredit())
          # dest.
          elif line.getDestinationValue() == account and\
3085 3086 3087
            line.getResourceValue() == currency and\
            section == line.getDestinationSectionValue() :
            calculated_balance += (
3088 3089 3090 3091 3092 3093
                    line.getDestinationDebit() - line.getDestinationCredit())
      
      self.assertEquals(calculated_balance,
          self.getPortal().portal_simulation.getInventory(
            node_uid = account.getUid(),
            section_uid = section.getUid(),
3094
            resource_uid = currency.getUid(),
3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135
          ))
  
  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)
3136
  
3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154
  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
3155
    self.failUnless('Site Error' not in accounting_module.view())
3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166
    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 )
3167
      self.failUnless('Site Error' not in accounting_transaction.view())
3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182
      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, )
3183
          self.failUnless('Site Error' not in line.view())
3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201
          # 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 ))
3202
  
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235
  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
3236

3237
    # create the transaction.
3238
    accounting_transaction = self.getAccountingModule().newContent(
3239 3240 3241 3242 3243 3244 3245
      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
3246 3247
                             # creating lines.
    )
3248
    income = accounting_transaction.newContent(
3249 3250
                  id='income',
                  portal_type=line_portal_type,
3251
                  quantity=-quantity,
3252 3253 3254
                  source_value=kw.get('income_account', self.income_account),
                  destination_value=kw.get('expense_account',
                                              self.expense_account), )
3255 3256 3257
    self.failUnless(income.getSource() != None)
    self.failUnless(income.getDestination() != None)
    
3258
    receivable = accounting_transaction.newContent(
3259 3260
                  id='receivable',
                  portal_type=line_portal_type,
3261
                  quantity=quantity,
3262 3263 3264 3265
                  source_value=kw.get('receivable_account',
                                          self.receivable_account),
                  destination_value=kw.get('payable_account',
                                            self.payable_account), )
3266 3267
    self.failUnless(receivable.getSource() != None)
    self.failUnless(receivable.getDestination() != None)
3268
    if reindex:
3269
      transaction.commit()
3270 3271
      self.tic()
    if check_consistency:
3272 3273 3274
      self.failUnless(len(accounting_transaction.checkConsistency()) == 0,
         "Check consistency failed : %s" % accounting_transaction.checkConsistency())
    return accounting_transaction
3275

3276 3277 3278 3279
  def test_createAccountingTransaction(self):
    """Make sure acounting transactions created by createAccountingTransaction
    method are valid.
    """
3280 3281 3282 3283 3284
    accounting_transaction = self.createAccountingTransaction()
    self.assertEquals(self.vendor, accounting_transaction.getSourceSectionValue())
    self.assertEquals(self.client, accounting_transaction.getDestinationSectionValue())
    self.assertEquals(self.EUR, accounting_transaction.getResourceValue())
    self.failUnless(accounting_transaction.AccountingTransaction_isSourceView())
3285
    
3286 3287 3288
    self.workflow_tool.doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals('stopped', accounting_transaction.getSimulationState())
    self.assertEquals([] , accounting_transaction.checkConsistency())
3289

3290 3291 3292 3293
  def stepCreateValidAccountingTransaction(self, sequence,
                                          sequence_list=None, **kw) :
    """Creates a valid accounting transaction and put it in
    the sequence as `transaction` key. """
3294
    accounting_transaction = self.createAccountingTransaction(
3295 3296 3297 3298 3299 3300 3301
                            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'), )
3302
    sequence.edit(
3303 3304 3305
      transaction = accounting_transaction,
      income = accounting_transaction.income,
      receivable = accounting_transaction.receivable
3306 3307
    )
    
3308 3309 3310 3311 3312 3313 3314 3315 3316
  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.
    """
3317 3318 3319 3320 3321 3322 3323
    accounting_transaction = sequence.get('transaction')
    old_stop_date = accounting_transaction.getStopDate()
    old_start_date = accounting_transaction.getStartDate()
    accounting_transaction.setStopDate(None)
    if accounting_transaction.getStopDate() != None :
      accounting_transaction.setStartDate(None)
      accounting_transaction.setStopDate(None)
3324 3325
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3326
        accounting_transaction,
3327
        'stop_action')
3328 3329 3330 3331
    accounting_transaction.setStartDate(old_start_date)
    accounting_transaction.setStopDate(old_stop_date)
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3332 3333 3334 3335 3336 3337 3338 3339 3340 3341
  
  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.
    """
3342 3343 3344
    accounting_transaction = sequence.get('transaction')
    old_source_section = accounting_transaction.getSourceSection()
    old_destination_section = accounting_transaction.getDestinationSection()
3345 3346
    # default transaction uses payable accounts, so validating without
    # source section is refused.
3347
    accounting_transaction.setSourceSection(None)
3348 3349
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3350
        accounting_transaction,
3351 3352
        'stop_action')
    # ... as well as validation without destination section
3353 3354
    accounting_transaction.setSourceSection(old_source_section)
    accounting_transaction.setDestinationSection(None)
3355 3356
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3357
        accounting_transaction,
3358 3359
        'stop_action')
    # mirror section can be set only on the line
3360
    for line in accounting_transaction.getMovementList() :
3361
      line.setDestinationSection(old_destination_section)
3362
    try:
3363 3364
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
      self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3365 3366 3367 3368 3369
    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.
3370 3371 3372 3373
    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.

3374
      # get a new valid transaction
3375
      accounting_transaction = self.createAccountingTransaction()
3376
      expense_account = sequence.get('expense_account')
3377
      for line in accounting_transaction.getMovementList() :
3378 3379 3380
        line.edit( source_value = expense_account,
                   destination_value = expense_account )
      if side == SOURCE :
3381
        accounting_transaction.setDestinationSection(None)
3382
      else :
3383
        accounting_transaction.setSourceSection(None)
3384
      try:
3385 3386
        self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
        self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3387 3388 3389 3390 3391 3392
      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.
    """
3393 3394 3395
    accounting_transaction = sequence.get('transaction')
    old_resource = accounting_transaction.getResource()
    accounting_transaction.setResource(None)
3396 3397
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3398
        accounting_transaction,
3399 3400 3401
        'stop_action')
    # setting a dummy relationship is not enough, resource must be a
    # currency
3402
    accounting_transaction.setResourceValue(
3403
         self.portal.product_module.newContent(portal_type='Product'))
3404 3405
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3406
        accounting_transaction,
3407 3408 3409 3410 3411 3412 3413
        '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.
    """
3414 3415
    accounting_transaction = sequence.get('transaction')
    account = accounting_transaction.getMovementList()[0].getSourceValue()
3416 3417 3418 3419
    self.getWorkflowTool().doActionFor(account, 'invalidate_action')
    self.assertEquals(account.getValidationState(), 'invalidated')
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3420
        accounting_transaction,
3421 3422 3423 3424 3425 3426 3427 3428 3429
        '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.
    """
3430
    accounting_transaction = sequence.get('transaction')
3431
    # no account at all is refused
3432
    for line in accounting_transaction.getMovementList():
3433 3434 3435 3436
      line.setSource(None)
      line.setDestination(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3437
        accounting_transaction,
3438 3439 3440
        'stop_action')
    
    # only one line without account and with a quantity is also refused
3441 3442 3443
    accounting_transaction = self.createAccountingTransaction()
    accounting_transaction.getMovementList()[0].setSource(None)
    accounting_transaction.getMovementList()[0].setDestination(None)
3444 3445
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3446
        accounting_transaction,
3447 3448 3449 3450
        'stop_action')
    
    # but if we have a line with 0 quantity on both sides, we can
    # validate the transaction and delete this line.
3451 3452 3453
    accounting_transaction = self.createAccountingTransaction()
    line_count = len(accounting_transaction.getMovementList())
    accounting_transaction.newContent(
3454
        portal_type = self.accounting_transaction_line_portal_type)
3455 3456 3457
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
    self.assertEquals(line_count, len(accounting_transaction.getMovementList()))
3458 3459 3460
    
    # 0 quantity, but a destination asset price => do not delete the
    # line
3461 3462
    accounting_transaction = self.createAccountingTransaction()
    new_line = accounting_transaction.newContent(
3463
        portal_type = self.accounting_transaction_line_portal_type)
3464 3465
    self.assertEquals(len(accounting_transaction.getMovementList()), 3)
    line_list = accounting_transaction.getMovementList()
3466
    line_list[0].setDestinationTotalAssetPrice(100)
3467 3468
    line_list[0]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
3469
    line_list[1].setDestinationTotalAssetPrice(- 50)
3470 3471
    line_list[1]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
3472
    line_list[2].setDestinationTotalAssetPrice(- 50)
3473 3474
    line_list[2]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
3475
    try:
3476 3477
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
      self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3478 3479 3480 3481 3482 3483
    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.
    """
3484 3485
    accounting_transaction = sequence.get('transaction')
    accounting_transaction.getMovementList()[0].setQuantity(4325)
3486 3487
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3488
        accounting_transaction,
3489 3490 3491 3492
        'stop_action')
    
    # asset price have priority (ie. if asset price is not balanced,
    # refuses validation even if quantity is balanced)
3493 3494
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
3495 3496 3497 3498
    line_list[0].setDestinationTotalAssetPrice(10)
    line_list[1].setDestinationTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3499
        accounting_transaction,
3500 3501
        'stop_action')
    
3502 3503
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
3504 3505 3506 3507
    line_list[0].setSourceTotalAssetPrice(10)
    line_list[1].setSourceTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3508
        accounting_transaction,
3509 3510 3511
        'stop_action')
    
    # only asset price needs to be balanced
3512 3513
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
3514 3515 3516 3517 3518 3519 3520
    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:
3521 3522
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
      self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
    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.
    """
3534
    def useBankAccount(accounting_transaction):
3535 3536 3537 3538 3539
      """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
3540
      for line in accounting_transaction.getMovementList() :
3541 3542 3543 3544 3545 3546
        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)
3547
    # XXX
3548 3549
    accounting_transaction = sequence.get('transaction')
    useBankAccount(accounting_transaction)
3550 3551
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
3552
        accounting_transaction,
3553 3554
        'stop_action')
    
3555 3556
    source_section_value = accounting_transaction.getSourceSectionValue()
    destination_section_value = accounting_transaction.getDestinationSectionValue()
3557 3558 3559 3560 3561
    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, )
3562
      accounting_transaction = self.createAccountingTransaction(
3563
                      destination_section_value=self.other_vendor)
3564
      useBankAccount(accounting_transaction)
3565

3566 3567
      # payment node have to be set on both sides if both sides are member of
      # the same group.
3568 3569
      accounting_transaction.setSourcePaymentValue(source_payment_value)
      accounting_transaction.setDestinationPaymentValue(None)
3570 3571
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
3572
          accounting_transaction,
3573
          'stop_action')
3574 3575
      accounting_transaction.setSourcePaymentValue(None)
      accounting_transaction.setDestinationPaymentValue(destination_payment_value)
3576 3577
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
3578
          accounting_transaction,
3579
          'stop_action')
3580 3581
      accounting_transaction.setSourcePaymentValue(source_payment_value)
      accounting_transaction.setDestinationPaymentValue(destination_payment_value)
3582
      try:
3583 3584
        self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
        self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3585
      except ValidationFailed, err :
3586 3587 3588 3589
        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
3590 3591
      accounting_transaction = self.createAccountingTransaction()
      useBankAccount(accounting_transaction)
3592
      # only set payment for source
3593 3594
      accounting_transaction.setSourcePaymentValue(source_payment_value)
      accounting_transaction.setDestinationPaymentValue(None)
3595 3596
      # then we should be able to validate.
      try:
3597 3598
        self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
        self.assertEquals(accounting_transaction.getSimulationState(), 'stopped')
3599 3600 3601
      except ValidationFailed, err:
        self.fail("Validation failed : %s" % err.msg)
    
3602 3603
  def stepValidateRemoveEmptyLines(self, sequence, sequence_list=None, **kw):
    """Check validating a transaction remove empty lines. """
3604 3605
    accounting_transaction = sequence.get('transaction')
    lines_count = len(accounting_transaction.getMovementList())
3606
    empty_lines_count = 0
3607
    for line in accounting_transaction.getMovementList():
3608 3609 3610 3611
      if line.getSourceTotalAssetPrice() ==  \
         line.getDestinationTotalAssetPrice() == 0:
        empty_lines_count += 1
    if empty_lines_count == 0:
3612
      accounting_transaction.newContent(
3613 3614
            portal_type=self.accounting_transaction_line_portal_type)
    
3615 3616
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
    self.assertEquals(len(accounting_transaction.getMovementList()),
3617 3618 3619
                      lines_count - empty_lines_count)
    
    # we don't remove empty lines if there is only empty lines
3620
    accounting_transaction = self.getAccountingModule().newContent(
3621 3622 3623
                      portal_type=self.accounting_transaction_portal_type,
                      created_by_builder=1)
    for i in range(3):
3624
      accounting_transaction.newContent(
3625
            portal_type=self.accounting_transaction_line_portal_type)
3626 3627 3628
    lines_count = len(accounting_transaction.getMovementList())
    accounting_transaction.AccountingTransaction_deleteEmptyLines(redirect=0)
    self.assertEquals(len(accounting_transaction.getMovementList()), lines_count)
3629
    
3630 3631 3632
  ############################################################################
  ## Test Methods ############################################################
  ############################################################################
3633
  
Jérome Perrin's avatar
Jérome Perrin committed
3634
  def test_MultiCurrencyInvoice(self, quiet=QUIET, run=RUN_ALL_TESTS):
3635
    """Basic test for multi currency accounting"""
3636
    if not run : return
3637 3638 3639 3640 3641 3642 3643 3644 3645
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateInvoices
      stepTic
      stepCheckAccountBalanceLocalCurrency
      stepCheckAccountBalanceExternalCurrency
      stepCheckAccountBalanceConvertedCurrency
Jérome Perrin's avatar
Jérome Perrin committed
3646
    """, quiet=quiet)
3647 3648

  def test_AccountingPeriodRefusesWrongDateTransactionValidation(
Jérome Perrin's avatar
Jérome Perrin committed
3649
        self, quiet=QUIET, run=RUN_ALL_TESTS):
3650 3651
    """Accounting Periods prevents transactions from being validated when there
    is no oppened accounting period"""
3652
    if not run : return
3653 3654 3655 3656 3657 3658 3659 3660 3661
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepUseInvalidDates
      stepCreateInvoices
3662
      stepCheckStopInvoicesRefused
3663 3664
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
3665
    """, quiet=quiet)
3666

Jérome Perrin's avatar
Jérome Perrin committed
3667
  def test_AccountingPeriodNotStoppedTransactions(self, quiet=QUIET,
3668 3669 3670
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods refuse to close when some transactions are
      not stopped"""
3671
    if not run : return
3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateInvoices
      stepTic
      stepCheckAccountingPeriodRefusesClosing
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
3684
    """, quiet=quiet)
3685

Jérome Perrin's avatar
Jérome Perrin committed
3686
  def test_AccountingPeriodOtherSections(self, quiet=QUIET,
3687 3688
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods does not change other section transactions."""
3689
    if not run : return
3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateOtherSectionInvoices
      stepTic
      stepConfirmAccountingPeriod
      stepTic
      stepDeliverAccountingPeriod
      stepTic
3703
      stepCheckAccountingPeriodDelivered
3704
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
3705
    """, quiet=quiet)
3706

Jérome Perrin's avatar
Jérome Perrin committed
3707
  def test_Acquisition(self, quiet=QUIET, run=RUN_ALL_TESTS):
3708 3709 3710 3711 3712 3713
    """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
3714
      """, quiet=quiet)
3715

Jérome Perrin's avatar
Jérome Perrin committed
3716
  def test_AccountingTransactionValidationDate(self, quiet=QUIET,
3717 3718 3719 3720 3721 3722 3723 3724
                                            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
3725
      stepValidateNoDate""", quiet=quiet)
3726

3727

Jérome Perrin's avatar
Jérome Perrin committed
3728
  def test_AccountingTransactionValidationSection(self, quiet=QUIET,
3729 3730 3731 3732 3733 3734 3735 3736
                                             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
3737
      stepValidateNoSection""", quiet=quiet)
3738

Jérome Perrin's avatar
Jérome Perrin committed
3739
  def test_AccountingTransactionValidationCurrency(self, quiet=QUIET,
3740 3741 3742 3743 3744 3745 3746 3747
                                           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
3748
      stepValidateNoCurrency""", quiet=quiet)
3749

Jérome Perrin's avatar
Jérome Perrin committed
3750
  def test_AccountingTransactionValidationAccounts(self, quiet=QUIET,
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760
                                           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
3761
      stepValidateNoAccounts""", quiet=quiet)
3762

Jérome Perrin's avatar
Jérome Perrin committed
3763
  def test_AccountingTransactionValidationBalanced(self, quiet=QUIET,
3764 3765 3766 3767 3768 3769 3770 3771
                                              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
3772
      stepValidateNotBalanced""", quiet=quiet)
3773

Jérome Perrin's avatar
Jérome Perrin committed
3774
  def test_AccountingTransactionValidationPayment(self, quiet=QUIET,
3775 3776 3777 3778 3779 3780 3781 3782 3783
                                             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
3784
    """, quiet=quiet)
3785

Jérome Perrin's avatar
Jérome Perrin committed
3786
  def test_AccountingTransactionValidationRemoveEmptyLines(self, quiet=QUIET,
3787 3788 3789 3790 3791 3792 3793 3794 3795
                                             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
3796
    """, quiet=quiet)
3797

3798

3799 3800 3801 3802 3803 3804 3805
class TestAccountingTransactionTemplate(AccountingTestCase):
  """A test for Accounting Transaction Template
  """

  def getTitle(self):
    return "Accounting Transaction Template"

3806 3807 3808 3809 3810 3811
  def disableUserPreferenceList(self):
    """Disable existing User preferences."""
    for preference in self.portal.portal_preferences.objectValues():
      if preference.getPriority() == Priority.USER:
        preference.disable()

3812
  def test_Template(self):
3813
    self.disableUserPreferenceList()
3814 3815 3816 3817 3818
    self.login('claudie')
    preference = self.portal.portal_preferences.newContent('Preference')
    preference.priority = Priority.USER
    preference.enable()

3819
    transaction.commit()
3820 3821
    self.tic()

Jérome Perrin's avatar
Jérome Perrin committed
3822 3823
    document = self.accounting_module.newContent(
                    portal_type='Accounting Transaction')
3824 3825 3826
    document.edit(title='My Accounting Transaction')
    document.Base_makeTemplateFromDocument(form_id=None)

3827
    transaction.commit()
3828 3829 3830 3831
    self.tic()

    self.assertEqual(len(preference.objectIds()), 1)

Yusei Tahara's avatar
Yusei Tahara committed
3832 3833 3834 3835
    # make sure that subobjects are not unindexed after making template.
    subobject_uid = document.objectValues()[0].getUid()
    self.assertEqual(len(self.portal.portal_catalog(uid=subobject_uid)), 1)

3836 3837
    self.accounting_module.manage_delObjects(ids=[document.getId()])

3838
    transaction.commit()
3839 3840 3841 3842
    self.tic()

    template = preference.objectValues()[0]

Jérome Perrin's avatar
Jérome Perrin committed
3843 3844
    cp = preference.manage_copyObjects(ids=[template.getId()],
                                       REQUEST=None, RESPONSE=None)
3845 3846 3847 3848 3849
    new_document_list = self.accounting_module.manage_pasteObjects(cp)
    new_document_id = new_document_list[0]['new_id']
    new_document = self.accounting_module[new_document_id]
    new_document.makeTemplateInstance()

3850
    transaction.commit()
3851 3852 3853 3854
    self.tic()

    self.assertEqual(new_document.getTitle(), 'My Accounting Transaction')

3855 3856 3857
  def test_Base_doAction(self):
    # test creating a template using Base_doAction script (this is what
    # erp5_xhtml_style does)
3858
    self.disableUserPreferenceList()
3859 3860 3861 3862 3863
    self.login('claudie')
    preference = self.portal.portal_preferences.newContent('Preference')
    preference.priority = Priority.USER
    preference.enable()

3864
    transaction.commit()
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875
    self.tic()

    document = self.accounting_module.newContent(
                              portal_type='Accounting Transaction')
    document.edit(title='My Accounting Transaction')
    document.Base_makeTemplateFromDocument(form_id=None)
    
    template = preference.objectValues()[0]
    ret = self.accounting_module.Base_doAction(
        select_action='template %s' % template.getRelativeUrl(),
        form_id='', cancel_url='')
Yusei Tahara's avatar
Yusei Tahara committed
3876
    self.failUnless('Template%20created.' in ret, ret)
3877 3878
    self.assertEquals(2, len(self.accounting_module.contentValues()))

3879

3880 3881
def test_suite():
  suite = unittest.TestSuite()
3882 3883
  suite.addTest(unittest.makeSuite(TestAccountingWithSequences))
  suite.addTest(unittest.makeSuite(TestTransactions))
3884
  suite.addTest(unittest.makeSuite(TestAccounts))
3885
  suite.addTest(unittest.makeSuite(TestClosingPeriod))
3886
  suite.addTest(unittest.makeSuite(TestTransactionValidation))
3887
  suite.addTest(unittest.makeSuite(TestAccountingExport))
3888
  suite.addTest(unittest.makeSuite(TestAccountingTransactionTemplate))
3889
  return suite