testAccounting.py 269 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 34 35
from DateTime import DateTime
from Products.CMFCore.utils import _checkPermission

36
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
37
from Products.ERP5Type.tests import CodingStyleTestCase
38
from Products.ERP5Type.tests.utils import reindex
39
from Products.DCWorkflow.DCWorkflow import ValidationFailed
40
from AccessControl.SecurityManagement import newSecurityManager
41
from Products.ERP5Type.tests.Sequence import SequenceList
Sebastien Robin's avatar
Sebastien Robin committed
42
from Products.ERP5Form.PreferenceTool import Priority
43

44 45
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod

46 47 48
SOURCE = 'source'
DESTINATION = 'destination'
RUN_ALL_TESTS = 1
Jérome Perrin's avatar
Jérome Perrin committed
49
QUIET = 1
50

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
# 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:
67 68 69
    * currency_module/euro (EUR) with precision 2
    * currency_module/usd (USD) with precision 2
    * currency_module/yen (JPY) with precision 0
70 71 72

  Regions:
    * region/europe/west/france
73

74 75 76 77 78 79
  Group:
    * group/demo_group
    * group/demo_group/sub1
    * group/demo_group/sub2
    * group/client
    * group/vendor'
80

81 82 83
  Payment Mode:
    * payment_mode/cash
    * payment_mode/check
84

85
  Organisations:
86 87 88
    * `self.section` an organisation using EUR as default currency, without any
    openned accounting period by default. This organisation is member of
    group/demo_group/sub1
89
    * `self.main_section` an using EUR as default currency, without any
90
    openned accounting period by default. This organisation is member of
91
    group/demo_group. Both self.main_section and self.section are in the same
92
    company from accounting point of view.
93
    * self.client_1, self.client_2 & self.supplier, some other organisations
94

95 96 97 98 99 100 101 102 103 104 105 106 107
  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
108

109 110 111 112 113
  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
114
  rather than modifying default documents.
115
  """
116

117
  username = 'username'
118
  business_process = 'business_process_module/erp5_default_business_process'
119 120

  @reindex
121 122
  def _makeOne(self, portal_type='Accounting Transaction', lines=None,
               simulation_state='draft', **kw):
123
    """Creates an accounting transaction, and edit it with kw.
124

125 126 127 128 129 130
    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())
131 132
    if 'resource_value' not in kw:
      kw.setdefault('resource', 'currency_module/euro')
133 134
    if portal_type in ('Purchase Invoice Transaction',
                       'Balance Transaction'):
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)
142 143
    if self.business_process and not tr.getSpecialise():
      tr._setSpecialise(self.business_process)
144 145 146 147
    if lines:
      for line in lines:
        line.setdefault('portal_type', transaction_to_line_mapping[portal_type])
        tr.newContent(**line)
148 149 150 151 152 153 154 155
    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()
156 157
    return tr

158
  def createUserAndlogin(self, name=username):
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)

165
  def afterSetUp(self):
166
    super(AccountingTestCase, self).login()
167 168 169 170 171
    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
172 173
    self.section = getattr(self.organisation_module, 'my_organisation', None)
    self.main_section = getattr(self.organisation_module, 'main_organisation', None)
174

175 176 177 178
    # make sure documents are validated
    for module in (self.account_module, self.organisation_module,
                   self.person_module):
      for doc in module.objectValues():
179 180
        if doc.getValidationState() != 'validated':
          doc.validate()
181

182
    # and the preference enabled
183 184 185 186
    pref = self.portal.portal_preferences._getOb(
                  'accounting_zuite_preference', None)
    if pref is not None:
      pref.manage_addLocalRoles(self.username, ('Auditor', ))
187 188
      if pref.getPreferenceState() != 'enabled':
        pref.enable()
189

Jérome Perrin's avatar
Jérome Perrin committed
190 191
    self.validateRules()

192 193
    self.createUserAndlogin(self.username)

194 195 196
    # and all this available to catalog
    self.tic()

197
  def beforeTearDown(self):
198 199
    """Remove all documents, except the default ones.
    """
200
    self.abort()
201
    self.login()
202 203
    self.accounting_module.manage_delObjects(
                      list(self.accounting_module.objectIds()))
204 205
    organisation_list = ('my_organisation', 'main_organisation',
                         'client_1', 'client_2', 'supplier')
206
    self.organisation_module.manage_delObjects([x for x in
207 208
          self.accounting_module.objectIds() if x not in organisation_list])
    for organisation_id in organisation_list:
209 210 211
      organisation = self.organisation_module._getOb(organisation_id, None)
      if organisation is not None:
        organisation.manage_delObjects([x.getId() for x in
212 213
                organisation.objectValues(
                  portal_type=('Accounting Period', 'Bank Account'))])
214
    self.person_module.manage_delObjects([x for x in
215
          self.person_module.objectIds() if x not in ('john_smith',)])
216
    self.account_module.manage_delObjects([x for x in
217 218 219
          self.account_module.objectIds() if x not in ('bank', 'collected_vat',
            'equity', 'fixed_assets', 'goods_purchase', 'goods_sales',
            'payable', 'receivable', 'refundable_vat', 'stocks',)])
220 221 222 223
    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])
224 225 226 227 228 229
    self.portal.portal_simulation.manage_delObjects(list(
          self.portal.portal_simulation.objectIds()))
    self.tic()

  def getBusinessTemplateList(self):
    """Returns list of BT to be installed."""
230 231 232 233
    # 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.
234 235
    return ('erp5_core_proxy_field_legacy',
            'erp5_base', 'erp5_pdm', 'erp5_simulation', 'erp5_trade',
236
            'erp5_accounting', 'erp5_project', 'erp5_accounting_ui_test',
237 238 239 240 241
            'erp5_ods_style',
            'erp5_configurator_standard_trade_template',
            'erp5_configurator_standard_accounting_template',
            'erp5_configurator_standard_invoicing_template',
            'erp5_simulation_test')
242

243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  @UnrestrictedMethod
  def setUpLedger(self):
   # Create Ledger Categories
    ledger_category = self.portal.portal_categories.ledger
    ledger_accounting_category = ledger_category.get('accounting', None)
    if ledger_accounting_category is None:
      ledger_accounting_category = ledger_category.newContent(portal_type='Category', id='accounting')
    if ledger_accounting_category.get('general', None) is None:
      ledger_accounting_category.newContent(portal_type='Category', id='general')
    if ledger_accounting_category.get('detailed', None) is None:
      ledger_accounting_category.newContent(portal_type='Category', id='detailed')
    if ledger_accounting_category.get('other', None) is None:
      ledger_accounting_category.newContent(portal_type='Category', id='other')

    # Allow some ledgers on the 'Sale Invoice Transaction' portal type
    self.portal.portal_types['Sale Invoice Transaction'].edit(
      ledger=['accounting/general', 'accounting/detailed'])


262

263 264 265 266
class TestAccounts(AccountingTestCase):
  """Tests Accounts.
  """
  def test_AccountValidation(self):
267
    # Accounts need an account_type category to be valid
268
    account = self.portal.account_module.newContent(portal_type='Account')
269
    self.assertEqual(1, len(account.checkConsistency()))
270
    account.setAccountType('equity')
271
    self.assertEqual(0, len(account.checkConsistency()))
272

273 274
  def test_AccountWorkflow(self):
    account = self.portal.account_module.newContent(portal_type='Account')
275
    self.assertEqual('draft', account.getValidationState())
276 277 278 279 280 281
    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')
282
    self.assertEqual('validated', account.getValidationState())
283

284 285 286 287 288 289
  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
290 291
    self.assertTrue(account.isCreditAccount())
    self.assertTrue(account.getProperty('credit_account'))
292

293
    account.setCreditAccount(False)
294
    self.assertFalse(account.isCreditAccount())
295

296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
  def test_ERP5Site_getAccountItemList_cache(self):
    # added accounts are directly availble
    account = self.portal.account_module.newContent(
        portal_type='Account',
        gap='my_country/my_accounting_standards/1',
    )
    account.validate()
    self.tic()
    self.assertIn(
        account.getRelativeUrl(),
        [x[1] for x in self.portal.ERP5Site_getAccountItemList(
            section_category='',
            section_category_strict=False,
            from_date=None)])

    # changes to validated accounts are also reflected
    account.setTitle('test account')
    self.tic()
    self.assertIn(
        account.Account_getFormattedTitle(),
        [x[0] for x in self.portal.ERP5Site_getAccountItemList(
            section_category='',
            section_category_strict=False,
            from_date=None)])

    # invalidated accounts are removed
    account.invalidate()
    self.tic()
    self.assertNotIn(
        account.getRelativeUrl(),
        [x[1] for x in self.portal.ERP5Site_getAccountItemList(
            section_category='',
            section_category_strict=False,
            from_date=None)])

  def test_AccountingTransactionLine_getNodeItemList_cache(self):
    accounting_line = self._makeOne(lines=(dict(id='income'),)).income
    # added accounts are directly availble
    account = self.portal.account_module.newContent(
        portal_type='Account',
        account_type='income'
    )
    account.validate()
    self.tic()
    self.assertIn(
        account.getRelativeUrl(),
        [x[1] for x in accounting_line.AccountingTransactionLine_getNodeItemList()])

    # changes to validated accounts are also reflected
    account.setTitle('test account')
    self.tic()
    self.assertIn(
        account.Account_getFormattedTitle(),
        [x[0] for x in accounting_line.AccountingTransactionLine_getNodeItemList()])

    # invalidated accounts are removed
    account.invalidate()
    self.tic()
    self.assertNotIn(
        account.getRelativeUrl(),
        [x[1] for x in accounting_line.AccountingTransactionLine_getNodeItemList()])

358

359 360 361
class TestTransactionValidation(AccountingTestCase):
  """Test validations of accounting transactions.

362 363
  In this test suite, the main section have a closed accounting period for
  2006, and an open one for 2007.
364 365
  """
  def afterSetUp(self):
366
    super(TestTransactionValidation, self).afterSetUp()
367
    self.organisation_module = self.portal.organisation_module
368
    self.main_section = self.organisation_module.main_organisation
369

370 371
    if 'accounting_period_2006' not in self.main_section.objectIds():
      accounting_period_2006 = self.main_section.newContent(
372 373 374 375 376
                                  id='accounting_period_2006',
                                  portal_type='Accounting Period',
                                  start_date=DateTime('2006/01/01'),
                                  stop_date=DateTime('2006/12/31'))
      accounting_period_2006.start()
377 378 379
      self.portal.portal_workflow.doActionFor(accounting_period_2006,
          'stop_action',
          profit_and_loss_account=self.portal.account_module.contentValues()[0].getRelativeUrl())
380
      accounting_period_2007 = self.main_section.newContent(
381 382 383 384 385 386 387 388 389
                                  id='accounting_period_2007',
                                  portal_type='Accounting Period',
                                  start_date=DateTime('2007/01/01'),
                                  stop_date=DateTime('2007/12/31'))
      accounting_period_2007.start()
      self.tic()

  def test_SaleInvoiceTransactionValidationDate(self):
    # Accounting Period Date matters for Sale Invoice Transaction
390
    accounting_transaction = self._makeOne(
391 392 393 394 395 396 397 398 399 400
               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,
401
        accounting_transaction, 'stop_action')
402
    # in 2007, it's OK
403 404
    accounting_transaction.setStartDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
405

406 407
  def test_PurchaseInvoiceTransactionValidationDate(self):
    # Accounting Period Date matters for Purchase Invoice Transaction
408
    accounting_transaction = self._makeOne(
409 410 411 412 413 414 415 416 417 418
               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,
419
        accounting_transaction, 'stop_action')
420
    # in 2007, it's OK
421 422
    accounting_transaction.setStopDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
423 424 425

  def test_PaymentTransactionValidationDate(self):
    # Accounting Period Date matters for Payment Transaction
426
    accounting_transaction = self._makeOne(
427 428 429
               portal_type='Payment Transaction',
               start_date=DateTime('2006/03/03'),
               destination_section_value=self.organisation_module.supplier,
430
               payment_mode='default',
431 432 433 434 435 436 437
               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,
438
        accounting_transaction, 'stop_action')
439
    # in 2007, it's OK
440 441
    accounting_transaction.setStartDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
442 443 444

  def test_DestinationPaymentTransactionValidationDate(self):
    # Accounting Period Date matters for Payment Transaction
445
    accounting_transaction = self._makeOne(
446 447 448
               portal_type='Payment Transaction',
               stop_date=DateTime('2006/03/03'),
               source_section_value=self.organisation_module.supplier,
449
               destination_section_value=self.section,
450
               payment_mode='default',
451 452 453 454 455 456 457
               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,
458
        accounting_transaction, 'stop_action')
459
    # in 2007, it's OK
460 461
    accounting_transaction.setStopDate(DateTime("2007/03/03"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
462

463 464 465
  def test_UnusedSectionTransactionValidationDate(self):
    # If a section doesn't have any accounts on its side, we don't check the
    # accounting period dates
466
    accounting_transaction = self._makeOne(
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
               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,
482
        accounting_transaction, 'stop_action')
483 484
    # If we don't have accounts on destination side, validating transaction is
    # not refused
485
    for line in accounting_transaction.getMovementList():
486
      line.setDestination(None)
487
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
488

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
  def test_UnusedSectionTransactionValidationDateDestination(self):
    # If a section doesn't have any accounts on its side, we don't check the
    # accounting period dates. Symetric test of test_UnusedSectionTransactionValidationDate
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/03/03'),
               destination_section_value=self.organisation_module.supplier,
               source_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 source_section
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
        accounting_transaction, 'stop_action')
    # If we don't have accounts on source side, validating transaction is
    # not refused
    for line in accounting_transaction.getMovementList():
      line.setSource(None)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

  def test_UnusedSectionTransactionValidationDateWithSourceSetOnDelivery(self):
    # If a section doesn't have any accounts on its side, we don't check the
    # accounting period dates
    # Corner case that a source organisation is set on the transaction.
    # Acquisition should not be a problem.
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/03/03'),
               source_section_value=self.organisation_module.supplier,
               source_value=self.organisation_module.supplier,
               destination_section_value=self.section,
               destination_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,
        accounting_transaction, 'stop_action')
    # If we don't have accounts on destination side, validating transaction is
    # not refused
    for line in accounting_transaction.getMovementList():
      line.setDestination(None)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

  def test_UnusedSectionTransactionValidationDateDestinationWithDestinationSetOnDelivery(self):
    # If a section doesn't have any accounts on its side, we don't check the
    # accounting period dates.
    # Symetric test of test_UnusedSectionTransactionValidationDateWithSourceSetOnDelivery
    # Corner case that a destination organisation is set on the transaction.
    # Acquisition should not be a problem.
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/03/03'),
               destination_section_value=self.organisation_module.supplier,
               destination_value=self.organisation_module.supplier,
               source_section_value=self.section,
               source_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 source_section
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
        accounting_transaction, 'stop_action')
    # If we don't have accounts on source side, validating transaction is
    # not refused
    for line in accounting_transaction.getMovementList():
      line.setSource(None)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

576 577
  def test_AccountingTransactionValidationStartDate(self):
    # Check we can/cannot validate at date boundaries of the period
578
    accounting_transaction = self._makeOne(
579 580 581
               portal_type='Accounting Transaction',
               start_date=DateTime('2006/12/31'),
               destination_section_value=self.organisation_module.supplier,
582
               payment_mode='default',
583 584 585 586 587 588 589
               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,
590 591 592
        accounting_transaction, 'stop_action')
    accounting_transaction.setStartDate(DateTime("2007/01/01"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
593

594 595
  def test_AccountingTransactionValidationBeforePeriod(self):
    # Check we cannot validate before the period
596
    accounting_transaction = self._makeOne(
597 598 599 600 601 602 603 604 605 606 607
               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,
608
        accounting_transaction, 'stop_action')
609

610 611
  def test_AccountingTransactionValidationAfterPeriod(self):
    # Check we cannot validate after the period
612
    accounting_transaction = self._makeOne(
613 614 615 616 617 618 619 620 621 622 623
               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,
624
        accounting_transaction, 'stop_action')
625

626 627 628
  def test_AccountingTransactionValidationRecursivePeriod(self):
    # Check we can/cannot validate when secondary period exists

629
    accounting_period_2007 = self.main_section.accounting_period_2007
630 631 632 633 634 635 636 637 638 639 640 641 642
    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()

643
    accounting_transaction = self._makeOne(
644 645
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
646
               source_section_value=self.main_section,
647 648 649 650 651 652 653 654 655
               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,
656
        accounting_transaction, 'stop_action')
657
    # in 2007-02, it's OK
658 659
    accounting_transaction.setStartDate(DateTime("2007/02/02"))
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
660

661

662 663 664
  def test_PaymentTransactionWithEmployee(self):
    # we have to set bank account if we use an asset/cash/bank account, but not
    # for our employees
665
    accounting_transaction = self._makeOne(
666 667 668 669 670 671 672 673
               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,
674
                           destination_value=self.account_module.receivable,
675 676 677 678
                           source_credit=500)))
    # refused because no bank account
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
679
        accounting_transaction, 'stop_action')
680 681
    # with bank account, it's OK
    bank_account = self.section.newContent(portal_type='Bank Account')
682 683
    accounting_transaction.setSourcePaymentValue(bank_account)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
684

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
  def test_PaymentTransactionValidationCheckBankAccountPriceCurrency(self):
    # we have to declare a transaction with price_currency different from the
    # bank account
    bank_account = self.section.newContent(portal_type='Bank Account',
        price_currency_value=self.currency_module.euro)
    accounting_transaction = self._makeOne(
               portal_type='Payment Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.person_module.john_smith,
               payment_mode='default',
               resource_value=self.currency_module.usd,
               source_payment_value=bank_account,
               lines=(dict(source_value=self.account_module.bank,
                           destination_value=self.account_module.bank,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.receivable,
                           source_credit=500)))
    # refused because bank account currency different from transaction resource
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
        accounting_transaction, 'stop_action')
    # with same currency in bank account and transaction, it's OK
    accounting_transaction.setResourceValue(self.currency_module.euro)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

711 712
  def test_NonBalancedAccountingTransaction(self):
    # Accounting Transactions have to be balanced to be validated
713
    accounting_transaction = self._makeOne(
714 715 716 717 718 719 720 721 722 723 724 725 726
               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,
727 728
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
729 730
      if line.getSourceId() == 'payable':
        line.setSourceAssetDebit(38.99)
731
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
732 733 734 735

  def test_NonBalancedDestinationAccountingTransaction(self):
    # Accounting Transactions have to be balanced to be validated,
    # also for destination
736
    accounting_transaction = self._makeOne(
737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
               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,
752 753
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
754 755
      if line.getDestinationId() == 'receivable':
        line.setDestinationAssetDebit(38.99)
756
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
757

758 759 760
  def test_NonBalancedDestinationAccountingTransactionNoAccount(self):
    # Accounting Transactions have to be balanced to be validated,
    # also for destination
761
    accounting_transaction = self._makeOne(
762 763 764 765 766 767 768 769 770 771 772
               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
773
    # This is not balanced but there are no accounts on destination
774 775
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
776 777
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
778 779 780
      if line.getDestinationId() == 'receivable':
        line.setDestination(None)
    # but if there are no accounts defined it's not a problem
781
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
782

783
  def test_NonBalancedAccountingTransactionSectionOnLines(self):
784
    accounting_transaction = self._makeOne(
785 786 787 788 789 790 791 792 793 794 795 796 797
               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,
798
        accounting_transaction, 'stop_action')
799

800
    for line in accounting_transaction.getMovementList():
801
      line.setDestinationSection(None)
802
    self.assertEqual([], accounting_transaction.checkConsistency())
803
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
804 805

  def test_NonBalancedAccountingTransactionDifferentSectionOnLines(self):
806
    accounting_transaction = self._makeOne(
807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
               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,
823
        accounting_transaction, 'stop_action')
824
    self.assertEqual(1, len(accounting_transaction.checkConsistency()),
825
                         accounting_transaction.checkConsistency())
826

827
    for line in accounting_transaction.getMovementList():
828 829 830
      line.setDestinationSectionValue(
          self.organisation_module.client_2)

831
    self.assertEqual([], accounting_transaction.checkConsistency())
832
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
833 834

  def test_NonBalancedAccountingTransactionSectionPersonOnLines(self):
835
    accounting_transaction = self._makeOne(
836 837 838 839 840 841 842 843 844 845 846 847
               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
848
    self.assertEqual([], accounting_transaction.checkConsistency())
849
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
850

851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902
  def test_NonBalancedSourceAccountingTransactionNoAccountSourceAcquired(self):
    # Accounting Transactions have to be balanced to be validated,
    # the constraint should take care that the lines may acquire
    # a source from the transaction
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               source_value=self.section,
               resource='currency_module/yen',
               lines=(dict(destination_value=self.account_module.payable,
                           source_asset_debit=39,
                           source_debit=500),
                      dict(source_value=self.account_module.receivable,
                           destination_value=self.account_module.receivable,
                           source_asset_credit=38.99,
                           source_credit=500)))
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
      if line.getSourceId() == 'receivable':
        line.setSource(None)
    # but if there are no accounts defined it's not a problem
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

  def test_NonBalancedDestinationAccountingTransactionNoAccountDestinationAcquired(self):
    # Accounting Transactions have to be balanced to be validated,
    # the constraint should take care that the lines may acquire
    # a destination from the transaction
    accounting_transaction = self._makeOne(
               portal_type='Accounting Transaction',
               start_date=DateTime('2007/01/02'),
               destination_section_value=self.organisation_module.client_1,
               destination_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)))
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
        accounting_transaction, 'stop_action')
    for line in accounting_transaction.getMovementList():
      if line.getDestinationId() == 'receivable':
        line.setDestination(None)
    # but if there are no accounts defined it's not a problem
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')

903 904 905 906 907
  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)
908
    accounting_transaction = self._makeOne(
909 910 911 912 913 914 915 916 917
               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)))
918

919 920
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
921 922 923
        accounting_transaction, 'stop_action')
    accounting_transaction.setSourceSectionValue(self.section)
    accounting_transaction.setDestinationSectionValue(category)
924 925
    self.assertRaises(ValidationFailed,
        self.portal.portal_workflow.doActionFor,
926
        accounting_transaction, 'stop_action')
927

928 929
    accounting_transaction.setDestinationSectionValue(self.organisation_module.client_1)
    self.portal.portal_workflow.doActionFor(accounting_transaction, 'stop_action')
930

931
  def test_AccountingWorkflow(self):
932
    accounting_transaction = self._makeOne(
933 934 935 936 937 938 939 940 941
               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)))
942

943
    doActionFor = self.portal.portal_workflow.doActionFor
944
    self.assertEqual('draft', accounting_transaction.getSimulationState())
945 946
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))
947

948
    doActionFor(accounting_transaction, 'plan_action')
949
    self.assertEqual('planned', accounting_transaction.getSimulationState())
950 951 952 953
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'confirm_action')
954
    self.assertEqual('confirmed', accounting_transaction.getSimulationState())
955 956 957 958
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'start_action')
959
    self.assertEqual('started', accounting_transaction.getSimulationState())
960 961 962 963
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))

    doActionFor(accounting_transaction, 'stop_action')
964
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
965 966
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
967

968
    doActionFor(accounting_transaction, 'restart_action')
969
    self.assertEqual('started', accounting_transaction.getSimulationState())
970 971
    self.assertTrue(_checkPermission('Modify portal content',
      accounting_transaction))
972

973
    doActionFor(accounting_transaction, 'stop_action')
974
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
975 976
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
977

978
    doActionFor(accounting_transaction, 'deliver_action')
979
    self.assertEqual('delivered', accounting_transaction.getSimulationState())
980 981
    self.assertFalse(_checkPermission('Modify portal content',
      accounting_transaction))
982

983 984 985
  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
986
    accounting_transaction = self._makeOne(
987 988 989 990 991 992 993 994 995 996
               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)))

997
    section = accounting_transaction.getSourceSectionValue()
998
    self.assertEqual(section.getPriceCurrency(),
999
                      accounting_transaction.getResource())
1000 1001 1002

    # validation is refused
    doActionFor = self.portal.portal_workflow.doActionFor
1003
    self.assertRaises(ValidationFailed, doActionFor, accounting_transaction,
1004 1005
                      'stop_action')
    # and the source conversion tab is visible
1006
    self.assertTrue(
1007
        accounting_transaction.AccountingTransaction_isSourceCurrencyConvertible())
1008 1009 1010

    # if asset price is set to the same value as quantity, validation is
    # allowed
1011
    for line in accounting_transaction.getMovementList():
1012 1013 1014 1015 1016 1017
      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 ?')
1018
    doActionFor(accounting_transaction, 'stop_action')
1019
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
1020 1021 1022 1023 1024


  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
1025
    accounting_transaction = self._makeOne(
1026
               portal_type='Purchase Invoice Transaction',
1027
               stop_date=DateTime('2007/01/02'),
1028 1029 1030 1031 1032 1033 1034 1035
               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)))

1036
    section = accounting_transaction.getDestinationSectionValue()
1037
    self.assertEqual(section.getPriceCurrency(),
1038
                      accounting_transaction.getResource())
1039 1040 1041

    # validation is refused
    doActionFor = self.portal.portal_workflow.doActionFor
1042
    self.assertRaises(ValidationFailed, doActionFor, accounting_transaction,
1043 1044
                      'stop_action')
    # and the destination conversion tab is visible
1045
    self.assertTrue(
1046
        accounting_transaction.AccountingTransaction_isDestinationCurrencyConvertible())
1047 1048 1049

    # if asset price is set to the same value as quantity, validation is
    # allowed
1050
    for line in accounting_transaction.getMovementList():
1051 1052 1053 1054 1055 1056 1057
      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 ?')

1058
    doActionFor(accounting_transaction, 'stop_action')
1059
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
1060

1061 1062 1063 1064 1065 1066
  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
1067
                           source_debit=500),
1068 1069 1070 1071 1072
                      dict(source_value=self.account_module.receivable,
                           source_debit=-500,
                           cancellation_amount=True
                           )))

1073
    self.assertEqual([], accounting_transaction.checkConsistency())
1074 1075 1076
    self.portal.portal_workflow.doActionFor(accounting_transaction,
                                            'stop_action')

1077

1078 1079 1080 1081 1082 1083
class TestClosingPeriod(AccountingTestCase):
  """Various tests for closing the period.
  """
  def test_createBalanceOnNode(self):
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1084
    period.setStopDate(DateTime(2006, 12, 31))
1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103

    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)))

1104 1105
    period.AccountingPeriod_createBalanceTransaction(
                               profit_and_loss_account=None)
1106
    accounting_transaction_list = self.accounting_module.contentValues()
1107
    self.assertEqual(3, len(accounting_transaction_list))
1108 1109
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
1110
    self.assertEqual(1, len(balance_transaction_list))
1111 1112 1113 1114 1115
    balance_transaction = balance_transaction_list[0]

    # this should create a balance with 3 lines,
    #   equity = 500 D
    #   stocks =     400 C
1116
    #   pl     =     100 C
1117
    self.assertEqual(self.section,
1118
                      balance_transaction.getDestinationSectionValue())
1119
    self.assertEqual(None,
1120
                      balance_transaction.getSourceSection())
1121 1122
    self.assertEqual([period], balance_transaction.getCausalityValueList())
    self.assertEqual(DateTime(2007, 1, 1),
1123
                      balance_transaction.getStartDate())
1124
    self.assertEqual('currency_module/euro',
1125
                      balance_transaction.getResource())
1126
    self.assertEqual('delivered', balance_transaction.getSimulationState())
1127
    movement_list = balance_transaction.getMovementList()
1128
    self.assertEqual(3, len(movement_list))
1129 1130 1131

    equity_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.equity]
1132
    self.assertEqual(1, len(equity_movement_list))
1133
    equity_movement = equity_movement_list[0]
1134 1135 1136 1137 1138 1139 1140
    self.assertEqual([], equity_movement.getValueList('resource'))
    self.assertEqual([], equity_movement.getValueList('destination_section'))
    self.assertEqual(None, equity_movement.getSource())
    self.assertEqual(None, equity_movement.getSourceSection())
    self.assertEqual(None, equity_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, equity_movement.getSourceTotalAssetPrice())
    self.assertEqual(500., equity_movement.getDestinationDebit())
1141 1142 1143

    stock_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.stocks]
1144
    self.assertEqual(1, len(stock_movement_list))
1145
    stock_movement = stock_movement_list[0]
1146 1147 1148 1149 1150 1151 1152
    self.assertEqual([], stock_movement.getValueList('resource'))
    self.assertEqual([], stock_movement.getValueList('destination_section'))
    self.assertEqual(None, stock_movement.getSource())
    self.assertEqual(None, stock_movement.getSourceSection())
    self.assertEqual(None, stock_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, stock_movement.getSourceTotalAssetPrice())
    self.assertEqual(400., stock_movement.getDestinationCredit())
1153 1154 1155

    pl_movement_list = [m for m in movement_list
                        if m.getDestinationValue() is None]
1156
    self.assertEqual(1, len(pl_movement_list))
1157
    pl_movement = pl_movement_list[0]
1158 1159 1160 1161 1162 1163 1164
    self.assertEqual([], pl_movement.getValueList('resource'))
    self.assertEqual([], pl_movement.getValueList('destination_section'))
    self.assertEqual(None, pl_movement.getSource())
    self.assertEqual(None, pl_movement.getSourceSection())
    self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEqual(100., pl_movement.getDestinationCredit())
1165 1166 1167 1168 1169 1170


  def test_createBalanceOnMirrorSection(self):
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1171
    period.setStopDate(DateTime(2006, 12, 31))
1172 1173 1174
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195

    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)))

1196
    period.AccountingPeriod_createBalanceTransaction(
1197
                             profit_and_loss_account=pl.getRelativeUrl())
1198
    accounting_transaction_list = self.accounting_module.contentValues()
1199
    self.assertEqual(3, len(accounting_transaction_list))
1200 1201
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
1202
    self.assertEqual(1, len(balance_transaction_list))
1203 1204 1205 1206 1207 1208
    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
1209
    self.assertEqual(self.section,
1210
                      balance_transaction.getDestinationSectionValue())
1211 1212
    self.assertEqual(None, balance_transaction.getSourceSection())
    self.assertEqual(DateTime(2007, 1, 1),
1213
                      balance_transaction.getStartDate())
1214
    self.assertEqual('currency_module/euro',
1215
                      balance_transaction.getResource())
1216
    self.assertEqual('delivered', balance_transaction.getSimulationState())
1217
    movement_list = balance_transaction.getMovementList()
1218
    self.assertEqual(3, len(movement_list))
1219 1220 1221

    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
1222
    self.assertEqual(1, len(client1_movement_list))
1223
    client1_movement = client1_movement_list[0]
1224 1225 1226 1227
    self.assertEqual([], client1_movement.getValueList('resource'))
    self.assertEqual([], client1_movement.getValueList('destination_section'))
    self.assertEqual(None, client1_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1228
                      client1_movement.getDestinationValue())
1229
    self.assertEqual(organisation_module.client_1,
1230
                      client1_movement.getSourceSectionValue())
1231 1232 1233
    self.assertEqual(None, client1_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, client1_movement.getSourceTotalAssetPrice())
    self.assertEqual(100., client1_movement.getDestinationCredit())
1234 1235 1236

    client2_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_2]
1237
    self.assertEqual(1, len(client2_movement_list))
1238
    client2_movement = client2_movement_list[0]
1239 1240 1241 1242
    self.assertEqual([], client2_movement.getValueList('resource'))
    self.assertEqual([], client2_movement.getValueList('destination_section'))
    self.assertEqual(None, client2_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1243
                      client2_movement.getDestinationValue())
1244
    self.assertEqual(organisation_module.client_2,
1245
                      client2_movement.getSourceSectionValue())
1246 1247 1248
    self.assertEqual(None, client2_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, client2_movement.getSourceTotalAssetPrice())
    self.assertEqual(200., client2_movement.getDestinationCredit())
1249 1250

    pl_movement_list = [m for m in movement_list
1251
                        if m.getDestinationValue() == pl]
1252
    self.assertEqual(1, len(pl_movement_list))
1253
    pl_movement = pl_movement_list[0]
1254 1255 1256
    self.assertEqual([], pl_movement.getValueList('resource'))
    self.assertEqual(None, pl_movement.getSource())
    self.assertEqual(pl,
1257
                      pl_movement.getDestinationValue())
1258
    self.assertEqual(None,
1259
                      pl_movement.getSourceSection())
1260 1261 1262
    self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEqual(300., pl_movement.getDestinationDebit())
1263
    self.tic()
1264 1265 1266 1267 1268

  def test_createBalanceOnPayment(self):
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1269
    period.setStopDate(DateTime(2006, 12, 31))
1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288

    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)))
1289

1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
    # 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)))

1304 1305
    period.AccountingPeriod_createBalanceTransaction(
                             profit_and_loss_account=None)
1306
    accounting_transaction_list = self.accounting_module.contentValues()
1307
    self.assertEqual(3, len(accounting_transaction_list))
1308 1309
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
1310
    self.assertEqual(1, len(balance_transaction_list))
1311 1312 1313 1314 1315 1316 1317 1318
    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

1319
    self.assertEqual(self.section,
1320
                      balance_transaction.getDestinationSectionValue())
1321
    self.assertEqual(None,
1322
                      balance_transaction.getSourceSection())
1323 1324
    self.assertEqual([period], balance_transaction.getCausalityValueList())
    self.assertEqual(DateTime(2007, 1, 1),
1325
                      balance_transaction.getStartDate())
1326
    self.assertEqual('currency_module/euro',
1327
                      balance_transaction.getResource())
1328
    self.assertEqual('delivered', balance_transaction.getSimulationState())
1329
    movement_list = balance_transaction.getMovementList()
1330
    self.assertEqual(4, len(movement_list))
1331

1332 1333
    receivable_movement_list = [m for m in movement_list
        if m.getDestinationValue() == self.account_module.receivable]
1334
    self.assertEqual(1, len(receivable_movement_list))
1335
    receivable_movement = receivable_movement_list[0]
1336 1337 1338
    self.assertEqual([], receivable_movement.getValueList('resource'))
    self.assertEqual(None, receivable_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1339
                      receivable_movement.getDestinationValue())
1340
    self.assertEqual(self.organisation_module.client_1,
1341
                      receivable_movement.getSourceSectionValue())
1342 1343 1344
    self.assertEqual(None, receivable_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, receivable_movement.getSourceTotalAssetPrice())
    self.assertEqual(100., receivable_movement.getDestinationDebit())
1345 1346 1347

    bank1_movement_list = [m for m in movement_list
                       if m.getDestinationPaymentValue() == bank1]
1348
    self.assertEqual(1, len(bank1_movement_list))
1349
    bank1_movement = bank1_movement_list[0]
1350 1351 1352
    self.assertEqual([], bank1_movement.getValueList('resource'))
    self.assertEqual(None, bank1_movement.getSource())
    self.assertEqual(self.account_module.bank,
1353
                      bank1_movement.getDestinationValue())
1354
    self.assertEqual(bank1,
1355
                      bank1_movement.getDestinationPaymentValue())
1356
    self.assertEqual(None,
1357
                      bank1_movement.getSourceSectionValue())
1358 1359 1360
    self.assertEqual(None, bank1_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, bank1_movement.getSourceTotalAssetPrice())
    self.assertEqual(100., bank1_movement.getDestinationCredit())
1361 1362 1363

    bank2_movement_list = [m for m in movement_list
                         if m.getDestinationPaymentValue() == bank2]
1364
    self.assertEqual(1, len(bank2_movement_list))
1365
    bank2_movement = bank2_movement_list[0]
1366 1367 1368
    self.assertEqual([], bank2_movement.getValueList('resource'))
    self.assertEqual(None, bank2_movement.getSource())
    self.assertEqual(self.account_module.bank,
1369
                      bank2_movement.getDestinationValue())
1370
    self.assertEqual(bank2,
1371
                      bank2_movement.getDestinationPaymentValue())
1372
    self.assertEqual(None,
1373
                      bank2_movement.getSourceSectionValue())
1374 1375 1376
    self.assertEqual(None, bank2_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, bank2_movement.getSourceTotalAssetPrice())
    self.assertEqual(200., bank2_movement.getDestinationDebit())
1377 1378 1379

    pl_movement_list = [m for m in movement_list
                         if m.getDestination() is None]
1380
    self.assertEqual(1, len(pl_movement_list))
1381
    pl_movement = pl_movement_list[0]
1382 1383 1384 1385 1386 1387 1388 1389
    self.assertEqual([], pl_movement.getValueList('resource'))
    self.assertEqual(None, pl_movement.getSource())
    self.assertEqual(None, pl_movement.getDestination())
    self.assertEqual(None, pl_movement.getDestinationPaymentValue())
    self.assertEqual(None, pl_movement.getSourceSectionValue())
    self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
    self.assertEqual(200., pl_movement.getDestinationCredit())
1390

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
  def test_createBalanceOnLedgerWithTransactionsWithNoLedger(self):
    self.setUpLedger()
    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))

    pl = self.portal.account_module.newContent(
          portal_type='Account',
          account_type='equity')

    # 2 Transactions for clients 1 and 2 on ledger accounting/general
    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/general',
        destination_section_value=organisation_module.client_1,
        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),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/general',
        destination_section_value=organisation_module.client_2,
        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)))

    # 2 Transactions for clients 1 and 2 on ledger accounting/detailed
    transaction3 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/detailed',
        destination_section_value=organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=400),
               dict(source_value=self.account_module.receivable,
                    source_credit=400)))

    transaction4 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/detailed',
        destination_section_value=organisation_module.client_2,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=800),
               dict(source_value=self.account_module.receivable,
                    source_credit=800)))

    # 2 Transactions for clients 1 and 2 with no ledger
    transaction5 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        destination_section_value=organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=1600),
               dict(source_value=self.account_module.receivable,
                    source_credit=1600)))
1458
    transaction5.setLedger(None)
1459 1460 1461 1462 1463 1464 1465 1466 1467 1468

    transaction6 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Sale Invoice Transaction',
        destination_section_value=organisation_module.client_2,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=3200),
               dict(source_value=self.account_module.receivable,
                    source_credit=3200)))
1469 1470 1471
    transaction6.setLedger(None)

    self.tic()
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 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 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721

    period.AccountingPeriod_createBalanceTransaction(
                               profit_and_loss_account=pl.getRelativeUrl())
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEqual(9, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEqual(3, len(balance_transaction_list))

    # 1st balance has 3 lines :           # 2nd balance has 3 lines :
    #   on ledger/accounting/general      #   on ledger/accounting/detailed
    #   pl                 = 300 D        #   pl                 = 1200 D
    #   receivable/client1 =      200 C   #   receivable/client1 =       800 C
    #   receivable/client2 =      100 C   #   receivable/client2 =       400 C
    # 3rd balance has 3 lines :
    #   on no ledger
    #   pl                 = 4800 D
    #   receivable/client1 =       3200 C
    #   receivable/client2 =       1600 C

    result_mapping = {}
    result_mapping['accounting/general'] = {'client1': 100., 'client2': 200., 'pl': 300.}
    result_mapping['accounting/detailed'] = {'client1': 400., 'client2': 800., 'pl': 1200.}
    result_mapping[None] = {'client1': 1600., 'client2': 3200., 'pl': 4800.}

    for balance_transaction in balance_transaction_list:

      self.assertEqual(self.section,
                       balance_transaction.getDestinationSectionValue())
      self.assertEqual(None, balance_transaction.getSourceSection())
      self.assertEqual(DateTime(2007, 1, 1),
                       balance_transaction.getStartDate())
      self.assertEqual('currency_module/euro',
                       balance_transaction.getResource())
      self.assertEqual('delivered', balance_transaction.getSimulationState())
      movement_list = balance_transaction.getMovementList()
      self.assertEqual(3, len(movement_list))

      current_ledger = balance_transaction.getLedger()
      assert current_ledger in (None, 'accounting/general', 'accounting/detailed')
      result = result_mapping[current_ledger]

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

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

      pl_movement_list = [m for m in movement_list
                          if m.getDestinationValue() == pl]
      self.assertEqual(1, len(pl_movement_list))
      pl_movement = pl_movement_list[0]
      self.assertEqual([], pl_movement.getValueList('resource'))
      self.assertEqual(None, pl_movement.getSource())
      self.assertEqual(pl,
                        pl_movement.getDestinationValue())
      self.assertEqual(None,
                        pl_movement.getSourceSection())
      self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
      self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
      self.assertEqual(result['pl'], pl_movement.getDestinationDebit())
      self.tic()

  def test_createBalanceOnLedgerWithAllTransactionsWithLedger(self):
    self.setUpLedger()
    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))

    pl = self.portal.account_module.newContent(
          portal_type='Account',
          account_type='equity')

    # 2 Transactions for clients 1 and 2 on ledger accounting/general
    transaction1 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/general',
        destination_section_value=organisation_module.client_1,
        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),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/general',
        destination_section_value=organisation_module.client_2,
        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)))

    # 2 Transactions for clients 1 and 2 on ledger accounting/detailed
    transaction3 = self._makeOne(
        start_date=DateTime(2006, 1, 1),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/detailed',
        destination_section_value=organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=400),
               dict(source_value=self.account_module.receivable,
                    source_credit=400)))

    transaction4 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Sale Invoice Transaction',
        ledger='accounting/detailed',
        destination_section_value=organisation_module.client_2,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_sales,
                    source_debit=800),
               dict(source_value=self.account_module.receivable,
                    source_credit=800)))

    period.AccountingPeriod_createBalanceTransaction(
                               profit_and_loss_account=pl.getRelativeUrl())
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEqual(6, len(accounting_transaction_list))
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEqual(2, len(balance_transaction_list))

    # 1st balance has 3 lines :           # 2nd balance has 3 lines :
    #   on ledger/accounting/general      #   on ledger/accounting/detailed
    #   pl                 = 300 D        #   pl                 = 1200 D
    #   receivable/client1 =      200 C   #   receivable/client1 =       800 C
    #   receivable/client2 =      100 C   #   receivable/client2 =       400 C

    result_mapping = {}
    result_mapping['accounting/general'] = {'client1': 100., 'client2': 200., 'pl': 300.}
    result_mapping['accounting/detailed'] = {'client1': 400., 'client2': 800., 'pl': 1200.}

    for balance_transaction in balance_transaction_list:

      self.assertEqual(self.section,
                       balance_transaction.getDestinationSectionValue())
      self.assertEqual(None, balance_transaction.getSourceSection())
      self.assertEqual(DateTime(2007, 1, 1),
                       balance_transaction.getStartDate())
      self.assertEqual('currency_module/euro',
                       balance_transaction.getResource())
      self.assertEqual('delivered', balance_transaction.getSimulationState())
      movement_list = balance_transaction.getMovementList()
      self.assertEqual(3, len(movement_list))

      current_ledger = balance_transaction.getLedger()
      assert current_ledger in ('accounting/general', 'accounting/detailed')
      result = result_mapping[current_ledger]

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

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

      pl_movement_list = [m for m in movement_list
                          if m.getDestinationValue() == pl]
      self.assertEqual(1, len(pl_movement_list))
      pl_movement = pl_movement_list[0]
      self.assertEqual([], pl_movement.getValueList('resource'))
      self.assertEqual(None, pl_movement.getSource())
      self.assertEqual(pl,
                        pl_movement.getDestinationValue())
      self.assertEqual(None,
                        pl_movement.getSourceSection())
      self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
      self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
      self.assertEqual(result['pl'], pl_movement.getDestinationDebit())
      self.tic()

    def testStockTableContent():
      q = self.portal.erp5_sql_connection.manage_test
      self.assertEqual(2, q(
        "SELECT count(*) FROM stock WHERE portal_type="
        "'Balance Transaction Line'")[0][0])
      self.assertEqual(300, q(
        "SELECT sum(total_price) FROM stock WHERE portal_type="
        "'Balance Transaction Line' AND ledger_uid="
        "%s GROUP BY ledger_uid" %
        self.portal.portal_categories.ledger.accounting.general.getUid())[0][0])
      self.assertEqual(300, q(
        "SELECT sum(quantity) FROM stock WHERE portal_type="
        "'Balance Transaction Line' AND ledger_uid="
        "%s GROUP BY ledger_uid" %
        self.portal.portal_categories.ledger.accounting.general.getUid())[0][0])
      self.assertEqual(1200, q(
        "SELECT sum(total_price) FROM stock WHERE portal_type="
        "'Balance Transaction Line' AND ledger_uid="
        "%s GROUP BY ledger_uid" % self.portal.portal_categories.ledger.accounting.detailed.getUid())[0][0])
      self.assertEqual(1200, q(
        "SELECT sum(quantity) FROM stock WHERE portal_type="
        "'Balance Transaction Line' AND ledger_uid="
        "%s GROUP BY ledger_uid" % self.portal.portal_categories.ledger.accounting.detailed.getUid())[0][0])

    # now check content of stock table
    testStockTableContent()
1722
    balance_transaction.reindexObject()
1723 1724
    self.tic()
    testStockTableContent()
1725 1726

  def test_createBalanceOnMirrorSectionMultiCurrency(self):
1727 1728 1729
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
1730 1731 1732
    organisation_module = self.organisation_module
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
1733
    period.setStopDate(DateTime(2006, 12, 31))
1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762

    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)))

1763
    period.AccountingPeriod_createBalanceTransaction(
1764
                      profit_and_loss_account=pl.getRelativeUrl())
1765
    accounting_transaction_list = self.accounting_module.contentValues()
1766
    self.assertEqual(3, len(accounting_transaction_list))
1767 1768
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
1769
    self.assertEqual(1, len(balance_transaction_list))
1770 1771
    balance_transaction = balance_transaction_list[0]

1772
    self.assertEqual(self.section,
1773
                      balance_transaction.getDestinationSectionValue())
1774 1775
    self.assertEqual(None, balance_transaction.getSourceSection())
    self.assertEqual(DateTime(2007, 1, 1),
1776
                      balance_transaction.getStartDate())
1777
    self.assertEqual('currency_module/euro',
1778 1779 1780 1781 1782 1783
                      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
1784

1785 1786
    accounting_currency_precision = \
        self.portal.currency_module.euro.getQuantityPrecision()
1787
    self.assertEqual(accounting_currency_precision, 2)
1788 1789

    movement_list = balance_transaction.getMovementList()
1790
    self.assertEqual(3, len(movement_list))
1791 1792
    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
1793
    self.assertEqual(1, len(client1_movement_list))
1794
    client1_movement = client1_movement_list[0]
1795
    self.assertEqual('currency_module/yen',
1796
                      client1_movement.getResource())
1797 1798 1799
    self.assertEqual([], client1_movement.getValueList('destination_section'))
    self.assertEqual(None, client1_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1800
                      client1_movement.getDestinationValue())
1801
    self.assertEqual(organisation_module.client_1,
1802 1803 1804 1805
                      client1_movement.getSourceSectionValue())
    self.assertAlmostEquals(1.1,
          client1_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
1806 1807
    self.assertEqual(None, client1_movement.getSourceTotalAssetPrice())
    self.assertEqual(100, client1_movement.getDestinationCredit())
1808 1809 1810

    client2_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_2]
1811
    self.assertEqual(1, len(client2_movement_list))
1812
    client2_movement = client2_movement_list[0]
1813
    self.assertEqual('currency_module/usd',
1814
                      client2_movement.getResource())
1815 1816 1817
    self.assertEqual([], client2_movement.getValueList('destination_section'))
    self.assertEqual(None, client2_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1818
                      client2_movement.getDestinationValue())
1819
    self.assertEqual(organisation_module.client_2,
1820 1821 1822 1823
                      client2_movement.getSourceSectionValue())
    self.assertAlmostEquals(2.2,
        client2_movement.getDestinationInventoriatedTotalAssetCredit(),
        accounting_currency_precision)
1824 1825
    self.assertEqual(None, client2_movement.getSourceTotalAssetPrice())
    self.assertEqual(200., client2_movement.getDestinationCredit())
1826 1827

    pl_movement_list = [m for m in movement_list
1828
                         if m.getDestinationValue() == pl]
1829
    self.assertEqual(1, len(pl_movement_list))
1830
    pl_movement = pl_movement_list[0]
1831 1832 1833
    self.assertEqual([], pl_movement.getValueList('resource'))
    self.assertEqual(None, pl_movement.getSource())
    self.assertEqual(pl,
1834
                      pl_movement.getDestinationValue())
1835
    self.assertEqual(None,
1836
                      pl_movement.getSourceSection())
1837 1838
    self.assertEqual(None, pl_movement.getDestinationTotalAssetPrice())
    self.assertEqual(None, pl_movement.getSourceTotalAssetPrice())
1839 1840 1841
    self.assertAlmostEquals(3.3,
                  pl_movement.getDestinationDebit(),
                  accounting_currency_precision)
1842

1843 1844 1845 1846
    self.tic()

    # now check content of stock table
    q = self.portal.erp5_sql_connection.manage_test
1847
    # 3 lines, one with quantity 3.3, 2 with quantity 0
1848
    self.assertEqual(1, q(
1849 1850
      "SELECT count(*) FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1851
    self.assertAlmostEquals(3.3, q(
1852
      "SELECT total_price FROM stock WHERE portal_type="
1853 1854 1855
      "'Balance Transaction Line'")[0][0],
      accounting_currency_precision)
    self.assertAlmostEquals(3.3, q(
1856
      "SELECT quantity FROM stock WHERE portal_type="
1857 1858
      "'Balance Transaction Line'")[0][0],
      accounting_currency_precision)
1859
    self.assertEqual(self.portal.currency_module.euro.getUid(), q(
1860 1861
      "SELECT resource_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1862
    self.assertEqual(self.section.getUid(), q(
1863 1864
      "SELECT section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1865
    self.assertEqual(None, q(
1866 1867
      "SELECT mirror_section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1868
    self.assertEqual(pl.getUid(), q(
1869 1870
      "SELECT node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1871
    self.assertEqual(None, q(
1872 1873
      "SELECT mirror_node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1874
    self.assertEqual(DateTime(2007, 1, 1), q(
1875 1876
      "SELECT date FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1877

Sebastien Robin's avatar
Sebastien Robin committed
1878 1879 1880 1881
    # we can reindex again
    balance_transaction.reindexObject()
    self.tic()

1882

1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
  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)))
    self.tic()

    period.AccountingPeriod_createBalanceTransaction(
                          profit_and_loss_account=pl.getRelativeUrl())
    accounting_transaction_list = self.accounting_module.contentValues()
1924
    self.assertEqual(3, len(accounting_transaction_list))
1925 1926
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
1927
    self.assertEqual(1, len(balance_transaction_list))
1928 1929
    balance_transaction = balance_transaction_list[0]

1930
    self.assertEqual(self.section,
1931
                      balance_transaction.getDestinationSectionValue())
1932 1933
    self.assertEqual(None, balance_transaction.getSourceSection())
    self.assertEqual(DateTime(2007, 1, 1),
1934
                      balance_transaction.getStartDate())
1935
    self.assertEqual('currency_module/euro',
1936 1937 1938 1939 1940 1941
                      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
1942

1943 1944
    accounting_currency_precision = \
        self.portal.currency_module.euro.getQuantityPrecision()
1945
    self.assertEqual(accounting_currency_precision, 2)
1946 1947

    movement_list = balance_transaction.getMovementList()
1948
    self.assertEqual(3, len(movement_list))
1949 1950
    client1_movement_list = [m for m in movement_list
     if m.getSourceSectionValue() == organisation_module.client_1]
1951
    self.assertEqual(2, len(client1_movement_list))
1952 1953
    yen_movement = [x for x in client1_movement_list if
                    x.getResource() == 'currency_module/yen'][0]
1954 1955 1956
    self.assertEqual([], yen_movement.getValueList('destination_section'))
    self.assertEqual(None, yen_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1957
                      yen_movement.getDestinationValue())
1958
    self.assertEqual(organisation_module.client_1,
1959 1960 1961 1962
                      yen_movement.getSourceSectionValue())
    self.assertAlmostEquals(1.1,
          yen_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
1963 1964
    self.assertEqual(None, yen_movement.getSourceTotalAssetPrice())
    self.assertEqual(100, yen_movement.getDestinationCredit())
1965 1966 1967

    dollar_movement = [x for x in client1_movement_list if
                    x.getResource() == 'currency_module/usd'][0]
1968 1969 1970
    self.assertEqual([], dollar_movement.getValueList('destination_section'))
    self.assertEqual(None, dollar_movement.getSource())
    self.assertEqual(self.account_module.receivable,
1971
                      dollar_movement.getDestinationValue())
1972
    self.assertEqual(organisation_module.client_1,
1973 1974 1975 1976
                      dollar_movement.getSourceSectionValue())
    self.assertAlmostEquals(2.2,
          dollar_movement.getDestinationInventoriatedTotalAssetCredit(),
          accounting_currency_precision)
1977 1978
    self.assertEqual(None, dollar_movement.getSourceTotalAssetPrice())
    self.assertEqual(200, dollar_movement.getDestinationCredit())
1979 1980 1981 1982 1983

    self.tic()

    # now check content of stock table
    q = self.portal.erp5_sql_connection.manage_test
1984
    self.assertEqual(1, q(
1985 1986
      "SELECT count(*) FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1987
    self.assertAlmostEquals(3.3, q(
1988
      "SELECT total_price FROM stock WHERE portal_type="
1989 1990 1991
      "'Balance Transaction Line'")[0][0],
      accounting_currency_precision)
    self.assertAlmostEquals(3.3, q(
1992
      "SELECT quantity FROM stock WHERE portal_type="
1993 1994
      "'Balance Transaction Line'")[0][0],
      accounting_currency_precision)
1995
    self.assertEqual(self.portal.currency_module.euro.getUid(), q(
1996 1997
      "SELECT resource_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
1998
    self.assertEqual(self.section.getUid(), q(
1999 2000
      "SELECT section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
2001
    self.assertEqual(None, q(
2002 2003
      "SELECT mirror_section_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
2004
    self.assertEqual(pl.getUid(), q(
2005 2006
      "SELECT node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
2007
    self.assertEqual(None, q(
2008 2009
      "SELECT mirror_node_uid FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])
2010
    self.assertEqual(DateTime(2007, 1, 1), q(
2011 2012 2013
      "SELECT date FROM stock WHERE portal_type="
      "'Balance Transaction Line'")[0][0])

Sebastien Robin's avatar
Sebastien Robin committed
2014 2015 2016 2017
    # we can reindex again
    balance_transaction.reindexObject()
    self.tic()

2018

2019 2020 2021 2022 2023 2024
  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))
2025
    period.setStopDate(DateTime(2006, 12, 31))
2026
    self.assertEqual('draft', period.getSimulationState())
2027
    self.portal.portal_workflow.doActionFor(period, 'start_action')
2028
    self.assertEqual('started', period.getSimulationState())
2029 2030

    # create a simple transaction in the period
2031
    accounting_transaction = self._makeOne(
2032 2033 2034 2035 2036 2037 2038 2039
        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)))
2040
    self.assertEqual(1, len(self.accounting_module))
2041 2042 2043 2044 2045 2046 2047

    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()
2048 2049 2050

    # close the period
    self.portal.portal_workflow.doActionFor(period, 'stop_action',
2051
            profit_and_loss_account=pl_account.getRelativeUrl())
2052
    self.assertEqual('stopped', period.getSimulationState())
2053 2054 2055
    self.tic()
    # reopen it, then close it got real
    self.portal.portal_workflow.doActionFor(period, 'restart_action')
2056
    self.assertEqual('started', period.getSimulationState())
2057 2058 2059
    self.tic()
    self.portal.portal_workflow.doActionFor(period, 'stop_action',
            profit_and_loss_account=pl_account.getRelativeUrl())
2060
    self.assertEqual('stopped', period.getSimulationState())
2061
    self.tic()
2062

2063
    self.portal.portal_workflow.doActionFor(period, 'deliver_action',)
2064 2065

    self.tic()
2066
    self.assertEqual('delivered', period.getSimulationState())
2067

2068 2069 2070
    # this created a balance transaction
    balance_transaction_list = self.accounting_module.contentValues(
                                  portal_type='Balance Transaction')
2071
    self.assertEqual(1, len(balance_transaction_list))
2072 2073 2074
    balance_transaction = balance_transaction_list[0]

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

2079 2080 2081 2082 2083
  def test_MultipleSection(self):
    period = self.main_section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    period.start()
2084

2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118
    transaction_main = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        destination_section_value=self.main_section,
        source_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=30),
               dict(destination_value=self.account_module.payable,
                    destination_credit=30)))

    transaction_section = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        destination_section_value=self.section,
        source_section_value=self.organisation_module.client_1,
        simulation_state='stopped',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=20),
               dict(destination_value=self.account_module.payable,
                    destination_credit=20)))

    # transaction_section is just stopped, so stopping the period is refused.
    self.assertRaises(ValidationFailed,
                      self.portal.portal_workflow.doActionFor,
                      period,
                      'stop_action')

    transaction_section.deliver()
    self.tic()

    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
2119 2120
    self.portal.portal_workflow.doActionFor(period, 'stop_action',
              profit_and_loss_account=pl.getRelativeUrl())
2121

2122

2123
    self.tic()
2124

2125 2126
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
2127
    self.assertEqual(2, len(created_balance_transaction_list))
2128 2129 2130 2131

    main_section_balance_transaction = [bt for bt in
        created_balance_transaction_list if bt.getDestinationSectionValue() ==
        self.main_section][0]
2132 2133
    self.assertEqual(2, len(main_section_balance_transaction.getMovementList()))
    self.assertEqual([], main_section_balance_transaction.checkConsistency())
2134 2135 2136 2137

    section_balance_transaction = [bt for bt in
        created_balance_transaction_list if bt.getDestinationSectionValue() ==
        self.section][0]
2138 2139
    self.assertEqual(2, len(section_balance_transaction.getMovementList()))
    self.assertEqual([], section_balance_transaction.checkConsistency())
2140 2141

    self.tic()
Sebastien Robin's avatar
Sebastien Robin committed
2142 2143 2144 2145
    # we can reindex again
    main_section_balance_transaction.reindexObject()
    section_balance_transaction.reindexObject()
    self.tic()
2146

2147 2148 2149 2150 2151 2152
  def test_MultipleSectionIndependant(self):
    stool = self.portal.portal_simulation
    period_main_section = self.main_section.newContent(portal_type='Accounting Period')
    period_main_section.setStartDate(DateTime(2006, 1, 1))
    period_main_section.setStopDate(DateTime(2006, 12, 31))
    period_main_section.start()
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
    period_section = self.section.newContent(portal_type='Accounting Period')
    period_section.setStartDate(DateTime(2006, 1, 1))
    period_section.setStopDate(DateTime(2006, 12, 31))
    period_section.start()

    transaction_main = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        destination_section_value=self.main_section,
        source_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=30),
               dict(destination_value=self.account_module.payable,
                    destination_credit=30)))

    transaction_section = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        destination_section_value=self.section,
        source_section_value=self.organisation_module.client_1,
        simulation_state='stopped',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=20),
               dict(destination_value=self.account_module.payable,
                    destination_credit=20)))

    transaction_section.deliver()
    self.tic()

    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
    self.portal.portal_workflow.doActionFor(period_main_section, 'stop_action',
              profit_and_loss_account=pl.getRelativeUrl())
2189

2190
    self.tic()
2191

2192 2193
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
2194
    self.assertEqual(1, len(created_balance_transaction_list))
2195

2196
    self.assertEqual(30, stool.getInventory(
2197 2198
                              section_uid=self.main_section.getUid(),
                              node_uid=pl.getUid()))
2199
    self.assertEqual(-30, stool.getInventory(
2200 2201 2202 2203
                              section_uid=self.main_section.getUid(),
                              node_uid=self.portal.account_module.payable.getUid()))

    # Section is not impacted at the moment
2204
    self.assertEqual(0, stool.getInventory(
2205 2206
                              section_uid=self.section.getUid(),
                              node_uid=pl.getUid()))
2207
    self.assertEqual(-20, stool.getInventory(
2208 2209 2210 2211 2212 2213
                              section_uid=self.section.getUid(),
                              node_uid=self.portal.account_module.payable.getUid()))

    # Close section's period
    self.portal.portal_workflow.doActionFor(period_section, 'stop_action',
              profit_and_loss_account=pl.getRelativeUrl())
2214

2215
    self.tic()
2216

2217 2218
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
2219
    self.assertEqual(2, len(created_balance_transaction_list))
2220

2221
    # section is now impacted
2222
    self.assertEqual(20, stool.getInventory(
2223 2224
                              section_uid=self.section.getUid(),
                              node_uid=pl.getUid()))
2225
    self.assertEqual(-20, stool.getInventory(
2226 2227
                              section_uid=self.section.getUid(),
                              node_uid=self.portal.account_module.payable.getUid()))
2228

2229
    self.assertEqual(30, stool.getInventory(
2230 2231
                              section_uid=self.main_section.getUid(),
                              node_uid=pl.getUid()))
2232
    self.assertEqual(-30, stool.getInventory(
2233 2234 2235 2236 2237 2238 2239 2240
                              section_uid=self.main_section.getUid(),
                              node_uid=self.portal.account_module.payable.getUid()))

  def test_MultipleSectionEmpty(self):
    period = self.main_section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    period.start()
2241

2242 2243 2244 2245 2246 2247 2248 2249 2250 2251
    transaction_main = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Purchase Invoice Transaction',
        destination_section_value=self.main_section,
        source_section_value=self.organisation_module.client_1,
        simulation_state='delivered',
        lines=(dict(destination_value=self.account_module.goods_purchase,
                    destination_debit=30),
               dict(destination_value=self.account_module.payable,
                    destination_credit=30)))
2252

2253 2254 2255 2256 2257 2258 2259
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')
    self.portal.portal_workflow.doActionFor(period, 'stop_action',
              profit_and_loss_account=pl.getRelativeUrl())

    self.tic()
2260

2261 2262
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
2263
    self.assertEqual(1, len(created_balance_transaction_list))
2264
    # no balance transaction has been created for section
2265 2266 2267 2268 2269 2270

  def test_SecondAccountingPeriod(self):
    """Tests having two accounting periods.
    """
    period1 = self.section.newContent(portal_type='Accounting Period')
    period1.setStartDate(DateTime(2006, 1, 1))
2271
    period1.setStopDate(DateTime(2006, 12, 31))
2272
    period1.start()
2273

2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289
    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)))
    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(
2290
            period1, 'stop_action',
2291
            profit_and_loss_account=pl_account.getRelativeUrl())
2292 2293
    self.tic()

2294 2295
    balance_transaction_list = self.accounting_module.contentValues(
                                  portal_type='Balance Transaction')
2296
    self.assertEqual(1, len(balance_transaction_list))
2297
    balance_transaction1 = balance_transaction_list[0]
2298

2299 2300
    period2 = self.section.newContent(portal_type='Accounting Period')
    period2.setStartDate(DateTime(2007, 1, 1))
2301
    period2.setStopDate(DateTime(2007, 12, 31))
2302 2303 2304 2305 2306 2307
    period2.start()

    transaction2 = self._makeOne(
        start_date=DateTime(2007, 1, 2),
        portal_type='Accounting Transaction',
        simulation_state='delivered',
2308 2309 2310 2311
        lines=(dict(source_value=self.account_module.equity,
                    source_debit=100),
               dict(source_value=pl_account,
                    source_credit=100)))
2312 2313 2314 2315 2316 2317 2318 2319 2320
    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)))
2321

2322 2323
    period2.AccountingPeriod_createBalanceTransaction(
                profit_and_loss_account=pl_account.getRelativeUrl())
2324
    balance_transaction_list = [tr for tr in
2325 2326 2327
                          self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
                          if tr != balance_transaction1]
2328
    self.assertEqual(1, len(balance_transaction_list))
2329
    balance_transaction2 = balance_transaction_list[0]
2330

2331
    self.assertEqual(DateTime(2008, 1, 1),
2332 2333 2334 2335
                      balance_transaction2.getStartDate())
    # this should create a balance with 3 lines,
    #   equity          = 100 D
    #   payable/client1 =       100 + 300 C
2336
    #   pl              = 300 D
2337
    movement_list = balance_transaction2.getMovementList()
2338
    self.assertEqual(3, len(movement_list))
2339 2340 2341

    equity_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.equity]
2342
    self.assertEqual(1, len(equity_movement_list))
2343
    equity_movement = equity_movement_list[0]
2344
    self.assertEqual(100., equity_movement.getDestinationDebit())
2345

2346 2347
    payable_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.payable]
2348
    self.assertEqual(1, len(payable_movement_list))
2349
    payable_movement = payable_movement_list[0]
2350
    self.assertEqual(400., payable_movement.getDestinationCredit())
2351

2352 2353
    pl_movement_list = [m for m in movement_list
          if m.getDestinationValue() == pl_account]
2354
    self.assertEqual(1, len(pl_movement_list))
2355
    pl_movement = pl_movement_list[0]
2356
    self.assertEqual(300., pl_movement.getDestinationDebit())
2357 2358 2359 2360 2361 2362 2363 2364 2365


  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))
2366
    period.setStopDate(DateTime(2006, 12, 31))
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386
    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())
2387

2388 2389
    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
2390
    self.assertEqual(1, len(balance_transaction_list))
2391
    balance_transaction = balance_transaction_list[0]
2392
    balance_transaction.alternateReindexObject()
2393
    movement_list = balance_transaction.getMovementList()
2394
    self.assertEqual(2, len(movement_list))
2395 2396 2397

    pl_movement_list = [m for m in movement_list
                      if m.getDestinationValue() == pl_account]
2398 2399
    self.assertEqual(1, len(pl_movement_list))
    self.assertEqual(500, pl_movement_list[0].getDestinationDebit())
2400

2401 2402
    stock_movement_list = [m for m in movement_list
          if m.getDestinationValue() == self.account_module.stocks]
2403 2404
    self.assertEqual(1, len(stock_movement_list))
    self.assertEqual(500, stock_movement_list[0].getDestinationCredit())
Sebastien Robin's avatar
Sebastien Robin committed
2405 2406 2407 2408

    self.tic()
    balance_transaction.reindexObject()
    self.tic()
2409

2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485
  def test_ProfitAndLossUsedInPeriodWithMultipleCurrency(self):
    """When the profit and loss account has a non zero balance at the end of
    the period, AccountingPeriod_createBalanceTransaction script should add
    a line for each currency used.
    """
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    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)))
    self.assertEqual([], transaction1.checkConsistency())

    transaction2 = self._makeOne(
        start_date=DateTime(2006, 1, 2),
        portal_type='Accounting Transaction',
        resource_value=self.portal.currency_module.yen,
        simulation_state='delivered',
        lines=(dict(source_value=self.account_module.goods_purchase,
                    source_debit=9000,
                    source_asset_debit=90),
               dict(source_value=pl_account,
                    source_debit=1000,
                    source_asset_debit=10),
               dict(source_value=self.account_module.stocks,
                    source_credit=10000,
                    source_asset_credit=100)))
    self.assertEqual([], transaction2.checkConsistency())

    period.AccountingPeriod_createBalanceTransaction(
                  profit_and_loss_account=pl_account.getRelativeUrl())

    balance_transaction_list = self.accounting_module.contentValues(
                              portal_type='Balance Transaction')
    self.assertEqual(1, len(balance_transaction_list))
    balance_transaction = balance_transaction_list[0]
    balance_transaction.alternateReindexObject()
    movement_list = balance_transaction.getMovementList()

    pl_movement_list = [m for m in movement_list
                      if m.getDestinationValue() == pl_account]
    self.assertEqual(2, len(pl_movement_list))
    # This is a 400 + 90 loss, plus the 100 using EUR
    self.assertEqual(sorted([
        (
         100 + 490.,
         None,
         self.portal.currency_module.euro, ),
        (
         1000.,
         10.,
         self.portal.currency_module.yen, ),
        ]), sorted([(
            m.getQuantity(),
            m.getDestinationTotalAssetPrice(),
            m.getResourceValue(),
            ) for m in pl_movement_list]))

    self.tic()
    balance_transaction.reindexObject()
    self.tic()

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 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541
  def test_BalanceTransactionWhenProfitAndLossBalanceIsZero(self):
    # The case of a balance transaction after all accounts have a 0 balance.
    period1 = self.section.newContent(portal_type='Accounting Period')
    period1.setStartDate(DateTime(2006, 1, 1))
    period1.setStopDate(DateTime(2006, 12, 31))
    period2 = self.section.newContent(portal_type='Accounting Period')
    period2.setStartDate(DateTime(2007, 1, 1))
    period2.setStopDate(DateTime(2007, 12, 31))
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')

    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)))
    self.tic()

    period1.AccountingPeriod_createBalanceTransaction(
                             profit_and_loss_account=pl.getRelativeUrl())
    year_1_accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEqual(2, len(year_1_accounting_transaction_list))
    self.tic()

    transaction2 = self._makeOne(
        start_date=DateTime(2007, 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)))
    self.tic()

    period2.AccountingPeriod_createBalanceTransaction(
                             profit_and_loss_account=pl.getRelativeUrl())
    accounting_transaction_list = self.accounting_module.contentValues()
    self.assertEqual(4, len(accounting_transaction_list))
    self.tic()

    balance_transaction, = [t for t in accounting_transaction_list if t not in
        year_1_accounting_transaction_list and t != transaction2]
    # Maybe we want to add line for each account in that case ?
    line, = balance_transaction.contentValues()

    self.assertEquals(line.getDestinationValue(), pl)
    self.assertEquals(line.getQuantity(), 0)
    self.assertEquals(line.getDestinationTotalAssetPrice(), None)


2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569
  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()
Sebastien Robin's avatar
Sebastien Robin committed
2570
    self.tic()
2571 2572 2573 2574 2575

    # now check inventory
    stool = self.getSimulationTool()
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
2576
    self.assertEqual(100, stool.getInventory(
2577 2578
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2579
    self.assertEqual(100, stool.getInventory(
2580 2581 2582
                    section_uid=self.section.getUid(),
                    mirror_section_uid=self.organisation_module.client_1.getUid(),
                    node_uid=node_uid))
2583
    self.assertEqual(100, stool.getInventoryAssetPrice(
2584 2585 2586
                    section_uid=self.section.getUid(),
                    node_uid=node_uid))
    # and only one movement is returned by getMovementHistoryList
2587
    movement_history_list = stool.getMovementHistoryList(
2588
                    section_uid=self.section.getUid(),
2589
                    node_uid=node_uid)
2590 2591
    self.assertEqual(1, len(movement_history_list))
    self.assertEqual([100], [x.total_price  for x in movement_history_list])
2592

2593 2594
    # the account 'goods_sales' has a balance of -100
    node_uid = self.account_module.goods_sales.getUid()
2595
    self.assertEqual(-100, stool.getInventory(
2596 2597 2598 2599 2600
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))

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

Sebastien Robin's avatar
Sebastien Robin committed
2605 2606 2607 2608 2609
    # we can reindex again
    balance.reindexObject()
    self.tic()
    # the account 'receivable' still has a balance of 100
    node_uid = self.account_module.receivable.getUid()
2610
    self.assertEqual(100, stool.getInventory(
Sebastien Robin's avatar
Sebastien Robin committed
2611 2612 2613
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))

2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624
    # Now check that even if we change the old movement and we
    # reindex the balance, the stock will still be the same
    getInventoryList = self.portal.portal_simulation.getInventoryList
    def getInventoryQuantityList():
      quantity_list = [x.inventory for x in getInventoryList(
         section_uid=self.section.getUid(),
         node_uid=node_uid)]
      quantity_list.sort()
      return quantity_list
    # 100 for the transaction, 0 for the balance
    # because in the balance we put exactly what we have in stock
2625
    self.assertEqual(getInventoryQuantityList(),
2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639
                      [100])
    def setQuantityOnTransaction1(quantity):
      for line in transaction1.objectValues():
        if line.getSourceDebit():
          line.setSourceDebit(quantity)
        if line.getSourceCredit():
          line.setSourceCredit(quantity)
      self.tic()
      balance.reindexObject()
      self.tic()
    setQuantityOnTransaction1(99)
    # 99 for the transaction, 1 for the balance
    # because in the balance we have 100, which is 1 more
    # than actual stock of 99
2640
    self.assertEqual(getInventoryQuantityList(),
2641 2642 2643 2644
                      [1, 99])
    setQuantityOnTransaction1(100)
    # Then finally we check that we have again same thing
    # as initial conditions
2645
    self.assertEqual(getInventoryQuantityList(),
2646 2647
                      [100])

2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
  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()
    self.tic()
2674

2675 2676 2677
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 150
    node_uid = self.account_module.receivable.getUid()
2678
    self.assertEqual(150, stool.getInventory(
2679 2680 2681 2682 2683 2684 2685
                              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()
2686
    self.assertEqual(-90, stool.getInventory(
2687 2688
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
Sebastien Robin's avatar
Sebastien Robin committed
2689 2690 2691
    # we can reindex again
    balance.reindexObject()
    self.tic()
2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714

  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()
    self.tic()
2715

2716 2717 2718
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 150 + 30
    node_uid = self.account_module.receivable.getUid()
2719
    self.assertEqual(180, stool.getInventory(
2720 2721
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2722
    self.assertEqual(150, stool.getInventory(
2723 2724 2725 2726
                              section_uid=self.section.getUid(),
                              mirror_section_uid=self.organisation_module\
                                                    .client_1.getUid(),
                              node_uid=node_uid))
2727
    self.assertEqual(30, stool.getInventory(
2728 2729 2730 2731
                              section_uid=self.section.getUid(),
                              mirror_section_uid=self.organisation_module\
                                                    .client_2.getUid(),
                              node_uid=node_uid))
Sebastien Robin's avatar
Sebastien Robin committed
2732 2733 2734
    # we can reindex again
    balance.reindexObject()
    self.tic()
2735

2736 2737
  def test_BalanceTransactionLineBrainGetObject(self):
    # Balance Transaction Line can be retrieved using Brain.getObject
Sebastien Robin's avatar
Sebastien Robin committed
2738 2739 2740 2741 2742 2743 2744 2745 2746
    existing_transaction = self._makeOne(
               start_date=DateTime(2006, 1, 31),
               portal_type='Sale Invoice Transaction',
               simulation_state='delivered',
               lines=(dict(source_value=self.account_module.receivable,
                           source_debit=30),
                      dict(source_value=self.account_module.goods_sales,
                           source_credit=30)))

2747 2748
    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
Sebastien Robin's avatar
Sebastien Robin committed
2749
                          id='different_from_line',
2750 2751 2752
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
Sebastien Robin's avatar
Sebastien Robin committed
2753 2754
    # this line already exists in stock table, only the difference will be
    # indexed
2755 2756 2757 2758
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                destination_debit=100,)
Sebastien Robin's avatar
Sebastien Robin committed
2759
    # this line does not already exist
2760 2761 2762 2763 2764 2765
    balance_line2 = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.payable,
                destination_credit=100,)
    balance.stop()
    self.tic()
2766

2767 2768 2769
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
2770
    self.assertEqual(100, stool.getInventory(
2771 2772 2773
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
    # there is one line in getMovementHistoryList:
Sebastien Robin's avatar
Sebastien Robin committed
2774 2775 2776 2777
    mvt_history_list = stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid,
                              sort_on=(('date', 'ASC'), ))
2778 2779
    self.assertEqual(2, len(mvt_history_list))
    self.assertEqual(mvt_history_list[1].getObject(),
Sebastien Robin's avatar
Sebastien Robin committed
2780
                      balance_line)
2781
    self.assertEqual([30, 70], [b.total_price for b in mvt_history_list])
Sebastien Robin's avatar
Sebastien Robin committed
2782 2783 2784

    # There is also one line on payable account
    node_uid = self.account_module.payable.getUid()
2785 2786 2787
    mvt_history_list = stool.getMovementHistoryList(
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)
2788 2789
    self.assertEqual(1, len(mvt_history_list))
    self.assertEqual(mvt_history_list[0].getObject(),
Sebastien Robin's avatar
Sebastien Robin committed
2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
                      balance_line2)

    # we can reindex again
    balance.reindexObject()
    self.tic()

  def test_BalanceTransactionLineBrainGetObjectDifferentThirdParties(self):
    # Balance Transaction Line can be retrieved using Brain.getObject, when
    # the balance is for different third parties
    existing_transaction = self._makeOne(
               start_date=DateTime(2006, 1, 30),
               portal_type='Sale Invoice Transaction',
               simulation_state='delivered',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
                           source_debit=30),
                      dict(source_value=self.account_module.goods_sales,
                           source_credit=30)))
    another_existing_transaction = self._makeOne(
               start_date=DateTime(2006, 1, 31),
               portal_type='Sale Invoice Transaction',
               simulation_state='delivered',
               destination_section_value=self.organisation_module.client_2,
               lines=(dict(source_value=self.account_module.receivable,
                           source_debit=40),
                      dict(source_value=self.account_module.goods_sales,
                           source_credit=40)))

    balance = self.accounting_module.newContent(
                          portal_type='Balance Transaction',
                          id='different_from_line',
                          destination_section_value=self.section,
                          start_date=DateTime(2006, 12, 31),
                          resource_value=self.currency_module.euro,)
2824

Sebastien Robin's avatar
Sebastien Robin committed
2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835
    balance_line = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.receivable,
                source_section_value=self.organisation_module.client_2,
                destination_debit=100,)
    balance_line2 = balance.newContent(
                portal_type='Balance Transaction Line',
                destination_value=self.account_module.payable,
                destination_credit=100,)
    balance.stop()
    self.tic()
2836

Sebastien Robin's avatar
Sebastien Robin committed
2837 2838 2839
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100 + 30
    node_uid = self.account_module.receivable.getUid()
2840
    self.assertEqual(130, stool.getInventory(
Sebastien Robin's avatar
Sebastien Robin committed
2841 2842 2843 2844 2845 2846 2847
                              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,
                              sort_on=(('date', 'ASC'), ))
2848 2849
    self.assertEqual(3, len(mvt_history_list))
    self.assertEqual(mvt_history_list[2].getObject(),
2850
                      balance_line)
2851
    self.assertEqual([30, 40, 60], [b.total_price for b in mvt_history_list])
2852 2853 2854 2855 2856 2857

    # 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)
2858 2859
    self.assertEqual(1, len(mvt_history_list))
    self.assertEqual(mvt_history_list[0].getObject(),
2860 2861
                      balance_line2)

Sebastien Robin's avatar
Sebastien Robin committed
2862 2863
    balance.reindexObject()
    self.tic()
2864

2865 2866
  def test_BalanceTransactionDate(self):
    # check that dates are correctly used for Balance Transaction indexing
2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899
    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()
    self.tic()

    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of -100
    node_uid = self.account_module.receivable.getUid()
2900
    self.assertEqual(-100, stool.getInventory(
2901 2902
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2903
    self.assertEqual(1, len(stool.getMovementHistoryList(
2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922
                              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)))
    self.tic()
    # let's try to reindex and check if values are still OK
    balance.reindexObject()
    self.tic()
2923

2924
    self.assertEqual(-150, stool.getInventory(
2925 2926
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2927
    movement_history_list = stool.getMovementHistoryList(
2928
                              section_uid=self.section.getUid(),
2929
                              node_uid=node_uid)
2930 2931
    self.assertEqual(2, len(movement_history_list))
    self.assertEqual(sorted([-50, -100]),
2932
      sorted([x.total_quantity for x in movement_history_list]))
2933 2934 2935 2936 2937


  def test_BalanceTransactionDateInInventoryAPI(self):
    # check that dates are correctly used for Balance Transaction when making
    # reports using inventory API
2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
    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()
    self.tic()
2949

2950 2951 2952
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100 after 2006/12/31
    node_uid = self.account_module.receivable.getUid()
2953
    self.assertEqual(100, stool.getInventory(
2954 2955 2956
                              at_date=DateTime(2006, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2957
    self.assertEqual(1, len(stool.getMovementHistoryList(
2958 2959 2960 2961
                              at_date=DateTime(2006, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid)))
    # and 0 before
2962
    self.assertEqual(0, stool.getInventory(
2963 2964 2965
                              at_date=DateTime(2005, 12, 31),
                              section_uid=self.section.getUid(),
                              node_uid=node_uid))
2966
    self.assertEqual(0, len(stool.getMovementHistoryList(
2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985
                              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()
    self.tic()
2986

2987 2988 2989
    stool = self.portal.portal_simulation
    # the account 'receivable' has a balance of 100
    node_uid = self.account_module.receivable.getUid()
2990
    self.assertEqual(100, stool.getInventory(
2991 2992 2993 2994 2995 2996 2997 2998
                              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)
2999
    self.assertEqual(1, len(mvt_history_list))
3000

3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027
  def test_TemporaryClosing(self):
    organisation_module = self.organisation_module
    stool = self.portal.portal_simulation
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    period.start()
    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')

    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_credit=100),
               dict(source_value=self.account_module.receivable,
                    source_debit=100)))

    self.portal.portal_workflow.doActionFor(
           period, 'stop_action',
           profit_and_loss_account=pl.getRelativeUrl())

    self.tic()

3028
    self.assertEqual(100, stool.getInventory(
3029 3030 3031
                              section_uid=self.section.getUid(),
                              node_uid=self.account_module.receivable.getUid()))

3032
    self.assertEqual(-100, stool.getInventory(
3033 3034 3035 3036 3037 3038
                              section_uid=self.section.getUid(),
                              node_uid=pl.getUid()))

    # when period is temporary stopped, a balance transaction is created
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
3039
    self.assertEqual(1, len(created_balance_transaction_list))
3040 3041 3042 3043 3044 3045 3046 3047 3048

    self.portal.portal_workflow.doActionFor(
           period, 'restart_action' )

    self.tic()

    # when we restart, then this balance transaction is deleted
    created_balance_transaction_list = self.portal.accounting_module.contentValues(
                                    portal_type='Balance Transaction')
3049
    self.assertEqual(0, len(created_balance_transaction_list))
3050

3051
    self.assertEqual(0, stool.getInventory(
3052 3053
                              section_uid=self.section.getUid(),
                              node_uid=pl.getUid()))
3054
    self.assertEqual(100, stool.getInventory(
3055 3056 3057
                              section_uid=self.section.getUid(),
                              node_uid=self.account_module.receivable.getUid()))

3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087
  def test_ParrallelClosingRefused(self):
    organisation_module = self.organisation_module
    stool = self.portal.portal_simulation
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    period.start()
    period2 = self.section.newContent(portal_type='Accounting Period')
    period2.setStartDate(DateTime(2007, 1, 1))
    period2.setStopDate(DateTime(2007, 12, 31))
    period2.start()

    pl = self.portal.account_module.newContent(
              portal_type='Account',
              account_type='equity')

    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_credit=100),
               dict(source_value=self.account_module.receivable,
                    source_debit=100)))

    self.portal.portal_workflow.doActionFor(
           period, 'stop_action',
           profit_and_loss_account=pl.getRelativeUrl())

3088 3089 3090 3091
    with self.assertRaisesRegexp(ValidationFailed,
        '.*Previous accounting periods has to be closed first.*'):
      self.getPortal().portal_workflow.doActionFor(
        period2, 'stop_action')
3092

3093 3094 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 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151
  def test_PeriodClosingRefusedWhenTransactionAreNotStopped(self):
    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))
    period.start()

    pl = self.portal.account_module.newContent(
      portal_type='Account',
      account_type='equity')

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

    with self.assertRaisesRegexp(
        ValidationFailed,
       'All Accounting Transactions for this organisation during'
       ' the period have to be closed first'):
      self.portal.portal_workflow.doActionFor(
        period,
        'stop_action')

  def test_PeriodClosingRefusedWhenTransactionAreNotStoppedIgnoreInternalLine(self):
    period = self.section.newContent(portal_type='Accounting Period')
    period.setStartDate(DateTime(2006, 1, 1))
    period.setStopDate(DateTime(2006, 12, 31))
    period.start()

    pl = self.portal.account_module.newContent(
      portal_type='Account',
      account_type='equity')

    # This transaction has lines that should block closing for `main_section`,
    # but not for `section` because from `section` side there are no accounting lines.
    transaction1 = self._makeOne(
      start_date=DateTime(2006, 1, 1),
      source_section_value=self.main_section,
      source_value=self.main_section,
      destination_section_value=self.section,
      destination_value=self.section,
      portal_type='Sale Invoice Transaction',
      simulation_state='stopped',
      lines=(dict(source_value=self.account_module.goods_sales,
                  source_credit=100),
             dict(source_value=self.account_module.receivable,
                  source_debit=100)))

    self.portal.portal_workflow.doActionFor(
      period,
      'stop_action',
      profit_and_loss_account=pl.getRelativeUrl())
    self.tic()
3152

3153 3154 3155 3156 3157 3158

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
3159
    accounting_transaction = self._makeOne(lines=(
3160 3161
              dict(source_value=self.account_module.payable,
                   quantity=200),))
3162
    ods_data = accounting_transaction.Base_viewAsODS(
3163 3164 3165 3166 3167 3168
                    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
3169
    self.assertEqual(
3170 3171 3172 3173 3174 3175 3176 3177
        '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)


3178 3179 3180
class TestTransactions(AccountingTestCase):
  """Test behaviours and utility scripts for Accounting Transactions.
  """
3181 3182 3183 3184 3185

  def getBusinessTemplateList(self):
    return AccountingTestCase.getBusinessTemplateList(self) + \
        ('erp5_invoicing', 'erp5_simplified_invoicing')

3186 3187
  def _resetIdGenerator(self):
    # clear all existing ids in portal ids
3188
      self.portal.portal_ids.clearGenerator(all=True)
3189

3190 3191 3192
  def test_SourceDestinationReference(self):
    # Check that source reference and destination reference are filled
    # automatically.
3193
    self._resetIdGenerator()
3194 3195 3196
    section_period_2001 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
3197
                        start_date=DateTime(2001, 1, 1),
3198 3199 3200 3201 3202
                        stop_date=DateTime(2001, 12, 31))
    section_period_2001.start()
    section_period_2002 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2002',
3203
                        start_date=DateTime(2002, 1, 1),
3204 3205 3206 3207 3208
                        stop_date=DateTime(2002, 12, 31))
    section_period_2002.start()

    accounting_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
3209 3210
              start_date=DateTime(2001, 1, 1),
              stop_date=DateTime(2001, 1, 1))
3211 3212 3213 3214
    self.portal.portal_workflow.doActionFor(
          accounting_transaction, 'stop_action')
    # The reference generated for the source section uses the short title from
    # the accounting period
3215
    self.assertEqual('code-2001-1', accounting_transaction.getSourceReference())
3216 3217
    # This works, because we use
    # 'AccountingTransaction_getAccountingPeriodForSourceSection' script
3218
    self.assertEqual(section_period_2001, accounting_transaction\
3219 3220 3221
              .AccountingTransaction_getAccountingPeriodForSourceSection())
    # If no accounting period exists on this side, the transaction date is
    # used.
3222
    self.assertEqual('2001-1', accounting_transaction.getDestinationReference())
3223 3224 3225

    other_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_2,
3226 3227
              start_date=DateTime(2001, 1, 1),
              stop_date=DateTime(2001, 1, 1))
3228
    self.portal.portal_workflow.doActionFor(other_transaction, 'stop_action')
3229 3230
    self.assertEqual('code-2001-2', other_transaction.getSourceReference())
    self.assertEqual('2001-1', other_transaction.getDestinationReference())
3231 3232 3233

    next_year_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
3234 3235
              start_date=DateTime(2002, 1, 1),
              stop_date=DateTime(2002, 1, 1))
3236
    self.portal.portal_workflow.doActionFor(next_year_transaction, 'stop_action')
3237 3238
    self.assertEqual('code-2002-1', next_year_transaction.getSourceReference())
    self.assertEqual('2002-1', next_year_transaction.getDestinationReference())
3239

3240 3241 3242 3243 3244 3245 3246
  def test_SourceDestinationReferenceGroupAccounting(self):
    # Check that source reference and destination reference are filled
    # automatically when using multiple sections
    self._resetIdGenerator()
    section_period_2001 = self.main_section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
3247
                        start_date=DateTime(2001, 1, 1),
3248 3249 3250 3251 3252
                        stop_date=DateTime(2001, 12, 31))
    section_period_2001.start()
    section_period_2002 = self.main_section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2002',
3253
                        start_date=DateTime(2002, 1, 1),
3254 3255 3256 3257 3258 3259
                        stop_date=DateTime(2002, 12, 31))
    section_period_2002.start()

    accounting_transaction = self._makeOne(
              source_section_value=self.main_section,
              destination_section_value=self.organisation_module.client_1,
3260 3261
              start_date=DateTime(2001, 1, 1),
              stop_date=DateTime(2001, 1, 1))
3262 3263 3264 3265
    self.portal.portal_workflow.doActionFor(
          accounting_transaction, 'stop_action')
    # The reference generated for the source section uses the short title from
    # the accounting period
3266
    self.assertEqual('code-2001-1', accounting_transaction.getSourceReference())
3267 3268
    # This works, because we use
    # 'AccountingTransaction_getAccountingPeriodForSourceSection' script
3269
    self.assertEqual(section_period_2001, accounting_transaction\
3270 3271 3272
              .AccountingTransaction_getAccountingPeriodForSourceSection())
    # If no accounting period exists on this side, the transaction date is
    # used.
3273
    self.assertEqual('2001-1', accounting_transaction.getDestinationReference())
3274 3275 3276

    other_section_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_2,
3277 3278
              start_date=DateTime(2001, 1, 1),
              stop_date=DateTime(2001, 1, 1))
3279 3280
    self.portal.portal_workflow.doActionFor(other_section_transaction, 'stop_action')
    # The numbering is shared by all the sections
3281 3282
    self.assertEqual('code-2001-2', other_section_transaction.getSourceReference())
    self.assertEqual('2001-1', other_section_transaction.getDestinationReference())
3283

3284 3285 3286
  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
3287
    self._resetIdGenerator()
3288 3289 3290
    section_period_2001 = self.section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
3291
                        start_date=DateTime(2001, 1, 1),
3292 3293 3294 3295 3296
                        stop_date=DateTime(2001, 12, 31))
    section_period_2001.start()

    accounting_transaction = self._makeOne(
              destination_section_value=self.organisation_module.client_1,
3297 3298
              start_date=DateTime(2001, 1, 1),
              stop_date=DateTime(2001, 1, 1))
3299 3300
    accounting_transaction.manage_permission('Modify portal content',
                                             roles=['Manager'], acquire=0)
3301 3302
    self.assertFalse(_checkPermission('Modify portal content',
                                      accounting_transaction))
3303
    accounting_transaction.stop()
3304
    self.assertEqual('code-2001-1', accounting_transaction.getSourceReference())
3305

3306 3307 3308 3309 3310 3311
  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()
3312

3313 3314 3315 3316
    accounting_period_2007.AccountingPeriod_createSecondaryPeriod(
          frequency='monthly', open_periods=1)
    sub_period_list = sorted(accounting_period_2007.contentValues(),
                              key=lambda x:x.getStartDate())
3317
    self.assertEqual(12, len(sub_period_list))
3318
    first_period = sub_period_list[0]
3319 3320 3321 3322
    self.assertEqual(DateTime(2007, 1, 1), first_period.getStartDate())
    self.assertEqual(DateTime(2007, 1, 31), first_period.getStopDate())
    self.assertEqual('2007-01', first_period.getShortTitle())
    self.assertEqual('January', first_period.getTitle())
3323 3324


3325
  def test_SearchableText(self):
3326
    accounting_transaction = self._makeOne(title='A new Transaction',
3327 3328
                                description="A description",
                                comment="Some comments")
3329
    searchable_text = accounting_transaction.SearchableText()
3330 3331 3332 3333
    self.assertTrue('A new Transaction' in searchable_text)
    self.assertTrue('A description' in searchable_text)
    self.assertTrue('Some comments' in searchable_text)

3334 3335 3336 3337 3338 3339 3340

  def test_Organisation_getMappingRelatedOrganisation(self):
    # the main section needs an accounting period to be treated as mapping
    # related by Organisation_getMappingRelatedOrganisation
    section_period_2001 = self.main_section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
3341
                        start_date=DateTime(2001, 1, 1),
3342 3343
                        stop_date=DateTime(2001, 12, 31))

3344
    self.assertEqual(self.main_section,
3345
        self.section.Organisation_getMappingRelatedOrganisation())
3346
    self.assertEqual(self.main_section,
3347 3348
        self.main_section.Organisation_getMappingRelatedOrganisation())

Sebastien Robin's avatar
Sebastien Robin committed
3349
    client = self.organisation_module.client_2
3350 3351
    self.assertEqual(None, client.getGroupValue())
    self.assertEqual(client,
3352 3353
        client.Organisation_getMappingRelatedOrganisation())

3354

3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
  # 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'),))
3410

3411 3412 3413 3414 3415 3416
    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)
3417

3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430
  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),))
3431

3432 3433 3434 3435 3436 3437
    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)
3438

3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459
  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')
3460
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
3461
    self.tic()
3462

3463 3464 3465 3466 3467 3468
    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)
3469

3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
  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')
3490
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
3491 3492 3493 3494 3495 3496 3497 3498
    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)
3499

3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535
  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()
    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)

3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546
  def test_Invoice_createRelatedPaymentTransactionDifferentCurrency(self):
    payment_node = self.section.newContent(portal_type='Bank Account')
    invoice = self._makeOne(
               destination_section_value=self.organisation_module.client_1,
               resource_value=self.portal.currency_module.usd,
               lines=(dict(source_value=self.account_module.goods_purchase,
                           source_debit=100,
                           source_asset_debit=150),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100,
                           source_asset_credit=150),))
3547

3548 3549 3550 3551 3552
    payment = invoice.Invoice_createRelatedPaymentTransaction(
                                  node=self.account_module.bank.getRelativeUrl(),
                                  payment=payment_node.getRelativeUrl(),
                                  payment_mode='check',
                                  batch_mode=1)
3553
    self.assertEqual(self.portal.currency_module.usd,
3554 3555
                      payment.getResourceValue())
    line_list = payment.getMovementList()
3556
    self.assertEqual(2, len(line_list))
3557 3558
    for line in line_list:
      if line.getSourceValue() == self.account_module.receivable:
3559
        self.assertEqual(100, line.getSourceDebit())
3560
        # there's no asset price
3561
        self.assertEqual(None, line.getSourceTotalAssetPrice())
3562
      else:
3563 3564 3565
        self.assertEqual(self.account_module.bank, line.getSourceValue())
        self.assertEqual(100, line.getSourceCredit())
        self.assertEqual(None, line.getSourceTotalAssetPrice())
3566

Sebastien Robin's avatar
Sebastien Robin committed
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589
  # tests for Invoice_getRemainingTotalPayablePrice
  def test_Invoice_getRemainingTotalPayablePriceDeletedPayment(self):
    """Checks in case of deleted Payments related to invoice"""
    # 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.tic()
    remaining_price = invoice.Invoice_getRemainingTotalPayablePrice()
    self.assertEqual(-100, remaining_price)
    payment.delete()
    self.tic()
    remaining_price = invoice.Invoice_getRemainingTotalPayablePrice()
    self.assertEqual(-100, remaining_price)
3590

3591 3592 3593
  # tests for Grouping References
  def test_GroupingReferenceResetedOnCopyPaste(self):
    accounting_module = self.portal.accounting_module
Sebastien Robin's avatar
Sebastien Robin committed
3594
    for portal_type in accounting_module.getVisibleAllowedContentTypeList():
3595
      accounting_transaction = accounting_module.newContent(
3596
                            portal_type=portal_type)
3597
      line = accounting_transaction.newContent(
3598 3599
                  id = 'line_with_grouping_reference',
                  grouping_reference='A',
3600
                  grouping_date=DateTime(),
3601 3602
                  portal_type=transaction_to_line_mapping[portal_type])

3603
      cp = accounting_module.manage_copyObjects(ids=[accounting_transaction.getId()])
3604
      copy_id = accounting_module.manage_pasteObjects(cp)[0]['new_id']
3605
      self.assertFalse(accounting_module[copy_id]\
3606
          .line_with_grouping_reference.getGroupingReference())
3607
      self.assertFalse(accounting_module[copy_id]\
3608
          .line_with_grouping_reference.getGroupingDate())
3609 3610 3611 3612 3613 3614 3615 3616 3617 3618

  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',
3619
                           grouping_date=DateTime(),
3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630
                           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',
3631
                           grouping_date=DateTime(),
3632 3633
                           grouping_reference='A'),))
    other_account_line = other_account_invoice.line_with_grouping_reference
3634

3635 3636 3637 3638 3639 3640 3641 3642
    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',
3643
                           grouping_date=DateTime(),
3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654
                           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',
3655
                           grouping_date=DateTime(),
3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667
                           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',
3668
                           grouping_date=DateTime(),
3669 3670 3671 3672
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
    payment_line = payment.line_with_grouping_reference
3673

3674 3675 3676
    # reset from the payment line, the invoice line from the same group will be
    # ungrouped
    payment_line.AccountingTransactionLine_resetGroupingReference()
3677 3678 3679 3680
    self.assertFalse(payment_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingDate())
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(invoice_line.getGroupingDate())
3681 3682

    # other lines are not touched:
3683 3684 3685 3686 3687
    self.assertTrue(other_account_line.getGroupingReference())
    self.assertTrue(other_account_line.getGroupingDate())
    self.assertTrue(other_section_line.getGroupingReference())
    self.assertTrue(other_section_line.getGroupingDate())
    self.assertTrue(other_letter_line.getGroupingDate())
3688

3689
  def test_automatically_setting_grouping_reference(self):
3690 3691
    invoice = self._makeOne(
               title='First Invoice',
3692
               start_date=DateTime(2012, 1, 2),
3693 3694 3695 3696 3697
               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,
3698 3699
                           id='line_for_grouping_reference',)))
    invoice_line = invoice.line_for_grouping_reference
3700 3701 3702 3703 3704

    payment = self._makeOne(
               title='First Invoice Payment',
               portal_type='Payment Transaction',
               simulation_state='delivered',
3705
               start_date=DateTime(2012, 1, 3),
3706
               causality_value=invoice,
3707 3708 3709 3710
               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,
3711
                           id='line_for_grouping_reference',
3712 3713 3714
                           source_debit=100),
                      dict(source_value=self.account_module.bank,
                           source_credit=100,)))
3715
    payment_line = payment.line_for_grouping_reference
3716

3717 3718 3719 3720
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(invoice_line.getGroupingDate())
    self.assertFalse(payment_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingDate())
3721

3722 3723
    # lines match, they are automatically grouped
    invoice.stop()
3724 3725
    self.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3726 3727
    self.assertEqual(invoice_line.getGroupingReference(),
                     payment_line.getGroupingReference())
3728
    # the grouping date is set to the latest date of all grouped lines
3729 3730
    self.assertEqual(DateTime(2012, 1, 3), invoice_line.getGroupingDate())
    self.assertEqual(DateTime(2012, 1, 3), payment_line.getGroupingDate())
3731

3732 3733 3734
    # when restarting, grouping is removed
    invoice.restart()
    self.tic()
3735 3736 3737 3738
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(invoice_line.getGroupingDate())
    self.assertFalse(payment_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingDate())
3739 3740

    # when stopping again, grouping is set again
3741
    invoice.stop()
3742 3743
    self.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3744 3745
    self.assertEqual(invoice_line.getGroupingReference(),
                     payment_line.getGroupingReference())
3746 3747
    self.assertEqual(DateTime(2012, 1, 3), invoice_line.getGroupingDate())
    self.assertEqual(DateTime(2012, 1, 3), payment_line.getGroupingDate())
3748 3749 3750 3751 3752 3753 3754 3755 3756

  def test_automatically_setting_grouping_reference_same_group(self):
    # invoice is for section, payment is for main_section

    # the main section needs an accounting period to be treated as mapping
    # related by Organisation_getMappingRelatedOrganisation
    section_period_2001 = self.main_section.newContent(
                        portal_type='Accounting Period',
                        short_title='code-2001',
3757
                        start_date=DateTime(2001, 1, 1),
3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784
                        stop_date=DateTime(2001, 12, 31))

    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_section_value=self.main_section,
               source_payment_value=self.main_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
3785

3786 3787
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3788

3789 3790
    # lines match, they are automatically grouped
    invoice.stop()
3791 3792
    self.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3793 3794
    self.assertEqual(invoice_line.getGroupingReference(),
                     payment_line.getGroupingReference())
3795

3796 3797
    # when restarting, grouping is removed
    invoice.restart()
3798
    self.tic()
3799 3800
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3801
    invoice.stop()
3802 3803
    self.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3804 3805
    self.assertEqual(invoice_line.getGroupingReference(),
                     payment_line.getGroupingReference())
3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832

  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
3833

3834 3835
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3836

3837
    invoice.stop()
3838 3839
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850

  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
3851

3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865
    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
3866

3867 3868
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3869

3870 3871
    # different sections, no grouping
    invoice.stop()
3872 3873
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3874

3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901
  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()
3902 3903
    self.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3904 3905 3906

    invoice.cancel()
    self.tic()
3907 3908
    self.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())
3909

3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933
  def test_automatically_setting_grouping_reference_in_one_invoice(self):
    # this invoice will group it itself
    invoice = self._makeOne(
               title='One Invoice',
               simulation_state='stopped',
               destination_section_value=self.organisation_module.client_1,
               lines=(dict(source_value=self.account_module.receivable,
                           source_debit=100),
                      dict(source_value=self.account_module.receivable,
                           source_credit=100, )))
    self.tic()
    for line in invoice.contentValues():
      self.assertTrue(line.getGroupingReference())

    invoice.restart()
    self.tic()
    for line in invoice.contentValues():
      self.assertFalse(line.getGroupingReference())

    invoice.stop()
    self.tic()
    for line in invoice.contentValues():
      self.assertTrue(line.getGroupingReference())

3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965
  def test_automatically_setting_grouping_reference_when_same_ledger(self):
    self.setUpLedger()
    invoice = self._makeOne(
               title='First Invoice',
               ledger_value=self.portal.portal_categories.ledger.accounting.general,
               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,
               ledger_value=self.portal.portal_categories.ledger.accounting.general,
               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.assertTrue(invoice_line.getGroupingReference())
    self.assertTrue(payment_line.getGroupingReference())
3966 3967
    self.assertEqual(invoice_line.getGroupingReference(),
                     payment_line.getGroupingReference())
3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001

  def test_not_automatically_setting_grouping_reference_when_different_ledger(self):
    self.setUpLedger()
    invoice = self._makeOne(
               title='First Invoice',
               ledger_value=self.portal.portal_categories.ledger.accounting.general,
               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,
               ledger_value=self.portal.portal_categories.ledger.accounting.detailed,
               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.assertFalse(invoice_line.getGroupingReference())
    self.assertFalse(payment_line.getGroupingReference())

4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119
  def test_roundDebitCredit_raises_if_big_difference(self):
    invoice = self._makeOne(
      portal_type='Sale Invoice Transaction',
      lines=(dict(source_value=self.account_module.goods_sales,
                source_debit=100.032345),
           dict(source_value=self.account_module.receivable,
                source_credit=100.000001)))
    precision = invoice.getQuantityPrecisionFromResource(invoice.getResource())
    invoice.newContent(portal_type='Invoice Line', quantity=1, price=100)
    self.assertRaises(invoice.AccountingTransaction_roundDebitCredit)

  def test_roundDebitCredit_when_payable_is_different_total_price(self):
    invoice = self._makeOne(
      portal_type='Purchase Invoice Transaction',
      stop_date=DateTime(),
      destination_section_value=self.section,
      source_section_value=self.organisation_module.supplier,
      lines=(dict(source_value=self.account_module.goods_purchase,
                id="expense",
                destination_debit=100.000001),
           dict(source_value=self.account_module.payable,
                id="payable",
                destination_credit=100.012345)))
    precision = invoice.getQuantityPrecisionFromResource(invoice.getResource())
    invoice.newContent(portal_type='Invoice Line', quantity=1, price=100)
    line_list = invoice.getMovementList(
                    portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertNotEqual(0.0,
      sum([round(g.getQuantity(), precision) for g in line_list]))
    invoice.AccountingTransaction_roundDebitCredit()
    line_list = invoice.getMovementList(
                 portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertEqual(0.0,
      sum([round(g.getQuantity(), precision) for g in line_list]))
    self.assertEqual(100.00, invoice.payable.getDestinationCredit())
    self.assertEqual(100.00, invoice.expense.getDestinationDebit())
    self.assertEqual([], invoice.checkConsistency())

  def test_roundDebitCredit_when_payable_is_equal_total_price(self):
    invoice = self._makeOne(
      portal_type='Purchase Invoice Transaction',
      stop_date=DateTime(),
      destination_section_value=self.section,
      source_section_value=self.organisation_module.supplier,
      lines=(dict(source_value=self.account_module.goods_purchase,
                id="expense",
                destination_debit=100.012345),
           dict(source_value=self.account_module.payable,
                id="payable",
               destination_credit=100.000001)))
    precision = invoice.getQuantityPrecisionFromResource(invoice.getResource())
    invoice.newContent(portal_type='Invoice Line', quantity=1, price=100)
    line_list = invoice.getMovementList(
                    portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertNotEqual(0.0,
      sum([round(g.getQuantity(), precision) for g in line_list]))
    invoice.AccountingTransaction_roundDebitCredit()
    line_list = invoice.getMovementList(
                 portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertEqual(0.0,
      sum([round(g.getQuantity(), precision) for g in line_list]))
    self.assertEqual(100.00, invoice.payable.getDestinationCredit())
    self.assertEqual(100.00, invoice.expense.getDestinationDebit())
    self.assertEqual([], invoice.checkConsistency())

  def test_roundDebitCredit_when_receivable_is_equal_total_price(self):
    invoice = self._makeOne(
      portal_type='Sale Invoice Transaction',
      stop_date=DateTime(),
      destination_section_value=self.section,
      source_section_value=self.section,
      lines=(dict(source_value=self.account_module.goods_sales,
                id="income",
                source_credit=100.012345),
           dict(source_value=self.account_module.receivable,
                id="receivable",
                source_debit=100.000001)))
    precision = invoice.getQuantityPrecisionFromResource(invoice.getResource())
    invoice.newContent(portal_type='Invoice Line', quantity=1, price=100)
    line_list = invoice.getMovementList(
                    portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertNotEqual(sum([round(g.getQuantity(), precision) for g in line_list]),
      0.0)
    invoice.AccountingTransaction_roundDebitCredit()
    line_list = invoice.getMovementList(
                 portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertEqual(sum([round(g.getQuantity(), precision) for g in line_list]),
      0.0)
    self.assertEqual(100.00, invoice.income.getSourceCredit())
    self.assertEqual(100.00, invoice.receivable.getSourceDebit())
    self.assertEqual([], invoice.checkConsistency())

  def test_roundDebitCredit_when_receivable_is_different_total_price(self):
    invoice = self._makeOne(
      portal_type='Sale Invoice Transaction',
      stop_date=DateTime(),
      destination_section_value=self.section,
      source_section_value=self.section,
      lines=(dict(source_value=self.account_module.goods_sales,
                id="income",
                source_credit=100.000001),
           dict(source_value=self.account_module.receivable,
                id="receivable",
                source_debit=100.012345)))
    precision = invoice.getQuantityPrecisionFromResource(invoice.getResource())
    invoice.newContent(portal_type='Invoice Line', quantity=1, price=100)
    line_list = invoice.getMovementList(
                    portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertNotEqual(sum([round(g.getQuantity(), precision) for g in line_list]),
      0.0)
    invoice.AccountingTransaction_roundDebitCredit()
    line_list = invoice.getMovementList(
                 portal_type=invoice.getPortalAccountingMovementTypeList())
    self.assertEqual(sum([round(g.getQuantity(), precision) for g in line_list]),
      0.0)
    self.assertEqual(100.00, invoice.income.getSourceCredit())
    self.assertEqual(100.00, invoice.receivable.getSourceDebit())
    self.assertEqual([], invoice.checkConsistency())
4120

4121 4122
  def test_AccountingTransaction_getTotalDebitCredit(self):
    # source view
4123
    accounting_transaction = self._makeOne(
4124 4125 4126 4127 4128 4129 4130 4131 4132
               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)))
4133
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
4134 4135
    self.assertEqual(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(400, accounting_transaction.AccountingTransaction_getTotalCredit())
4136 4137

    # destination view
4138
    accounting_transaction = self._makeOne(
4139 4140 4141 4142 4143 4144 4145 4146 4147 4148
               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)))
4149
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
4150 4151
    self.assertEqual(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(400, accounting_transaction.AccountingTransaction_getTotalCredit())
4152 4153

    # source view, with conversion on our side
4154
    accounting_transaction = self._makeOne(
4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
               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)))
4166
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
4167 4168
    self.assertEqual(50, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(40, accounting_transaction.AccountingTransaction_getTotalCredit())
4169 4170

    # destination view, with conversion on our side
4171
    accounting_transaction = self._makeOne(
4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183
               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)))
4184
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
4185 4186
    self.assertEqual(50, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(40, accounting_transaction.AccountingTransaction_getTotalCredit())
4187 4188

    # source view, with conversion on other side
4189
    accounting_transaction = self._makeOne(
4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200
               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)))
4201
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
4202 4203
    self.assertEqual(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(400, accounting_transaction.AccountingTransaction_getTotalCredit())
4204

4205
    # destination view, with conversion on other side
4206
    accounting_transaction = self._makeOne(
4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218
               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)))
4219
    self.assertFalse(accounting_transaction.AccountingTransaction_isSourceView())
4220 4221
    self.assertEqual(500, accounting_transaction.AccountingTransaction_getTotalDebit())
    self.assertEqual(400, accounting_transaction.AccountingTransaction_getTotalCredit())
4222

4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318
  def test_AccountingTransaction_getListBoxColumnList_does_not_enable_section_column_when_only_two_sections(self):
    # AccountingTransaction_getListBoxColumnList is the script returning the
    # columns to display in AccountingTransaction_view.
    at = self._makeOne(
      portal_type='Accounting Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  source_credit=500)))
    self.assertNotIn(
      ('getDestinationSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=True))
    self.assertNotIn(
      ('getSourceSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=False))

  def test_AccountingTransaction_getListBoxColumnList_enables_destination_section_column_when_more_than_two_sections(self):
    # AccountingTransaction_getListBoxColumnList is the script returning the
    # columns to display in AccountingTransaction_view.
    at = self._makeOne(
      portal_type='Accounting Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  destination_section_value=self.organisation_module.client_2,
                  source_credit=500)))
    # Only the source view have one extra column, because from destination point
    # of view, there is only one mirror section
    self.assertIn(
      ('getDestinationSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=True))
    self.assertNotIn(
      ('getSourceSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=False))

  def test_AccountingTransaction_getListBoxColumnList_enables_source_section_column_when_more_than_two_sections(self):
    at = self._makeOne(
      portal_type='Accounting Transaction',
      destination_section_value=self.section,
      source_section_value=self.organisation_module.client_1,
      lines=(dict(destination_value=self.account_module.goods_purchase,
                  destination_debit=500),
             dict(destination_value=self.account_module.receivable,
                  source_section_value=self.organisation_module.client_2,
                  destination_credit=500)))
    # Only the destination view have one extra column, because from source point
    # of view, there is only one mirror section
    self.assertNotIn(
      ('getDestinationSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=True))
    self.assertIn(
      ('getSourceSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=False))

  def test_AccountingTransaction_getListBoxColumnList_enables_source_section_column_when_same_section_both_sides(self):
    # Edge case, source section from the transaction is also used as destination section on a line
    # does not make much sense, but have to be visible when looking at transaction
    at = self._makeOne(
      portal_type='Accounting Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  destination_section_value=self.section, # Source section is also destination section here
                  source_credit=500)))
    self.assertIn(
      ('getDestinationSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=True))
    self.assertNotIn(
      ('getSourceSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=False))

  def test_AccountingTransaction_getListBoxColumnList_enables_destination_section_column_when_same_section_both_sides(self):
    # Edge case, destination section from the transaction is also used as source section on a line
    # does not make much sense, but have to be visible when looking at transaction
    at = self._makeOne(
      portal_type='Accounting Transaction',
      destination_section_value=self.section,
      source_section_value=self.organisation_module.client_1,
      lines=(dict(destination_value=self.account_module.goods_purchase,
                  destination_debit=500),
             dict(destination_value=self.account_module.receivable,
                  source_section_value=self.section, # Destination section is also here section here
                  destination_credit=500)))
    self.assertNotIn(
      ('getDestinationSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=True))
    self.assertIn(
      ('getSourceSectionTitle', 'Third Party'),
      at.AccountingTransaction_getListBoxColumnList(source=False))

4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374
  def test_AccountingTransaction_getSourcePaymentItemList(self):
    # AccountingTransaction_getSourcePaymentItemList allows to select bank accounts
    # from section
    bank_account = self.section.newContent(
      portal_type='Bank Account',
      reference='BA-1'
    )
    bank_account.validate()
    self.tic()

    at = self._makeOne(
      portal_type='Payment Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  source_credit=500)))
    self.assertIn(
      ('BA-1', bank_account.getRelativeUrl()),
      at.AccountingTransaction_getSourcePaymentItemList())

  def test_AccountingTransaction_getDestinationPaymentItemList(self):
    # AccountingTransaction_getDestinationPaymentItemList allows to select bank accounts
    # from destination section
    bank_account = self.section.newContent(
      portal_type='Bank Account',
      reference='BA-1'
    )
    bank_account.validate()
    self.tic()

    at = self._makeOne(
      portal_type='Payment Transaction',
      destination_section_value=self.section,
      source_section_value=self.organisation_module.client_1,
      lines=(dict(destination_value=self.account_module.goods_purchase,
                  destination_debit=500),
             dict(destination_value=self.account_module.receivable,
                  destination_credit=500)))
    self.assertIn(
      ('BA-1', bank_account.getRelativeUrl()),
      at.AccountingTransaction_getDestinationPaymentItemList())

  def test_AccountingTransaction_getSourcePaymentItemList_parent_section(self):
    # AccountingTransaction_getSourcePaymentItemList and AccountingTransaction_getDestinationPaymentItemList
    # allows to select bank accounts from parent groups of source section
    parent_bank_account = self.main_section.newContent(
      portal_type='Bank Account',
      reference='from main section'
    )
    parent_bank_account.validate()
    main_section_accounting_period = self.main_section.newContent(
      portal_type='Accounting Period',
    )
    main_section_accounting_period.start()
4375 4376 4377 4378 4379
    bank_account = self.section.newContent(
      portal_type='Bank Account',
      reference='from section'
    )
    bank_account.validate()
4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392
    self.tic()

    source_transaction = self._makeOne(
      portal_type='Payment Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  source_credit=500)))
    self.assertIn(
      ('from main section', parent_bank_account.getRelativeUrl()),
      source_transaction.AccountingTransaction_getSourcePaymentItemList())
4393 4394 4395
    self.assertIn(
      ('from section', bank_account.getRelativeUrl()),
      source_transaction.AccountingTransaction_getSourcePaymentItemList())
4396

4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407
    # We include non selectable elements in the drop down to show which to which organisation
    # the bank account belongs to.
    self.assertEqual(
      [('', ''),
       (self.main_section.getTitle(), None),
       ('from main section', parent_bank_account.getRelativeUrl()),
       (self.section.getTitle(), None),
       ('from section', bank_account.getRelativeUrl()),
      ],
      source_transaction.AccountingTransaction_getSourcePaymentItemList())

4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418
    destination_transaction = self._makeOne(
      portal_type='Payment Transaction',
      destination_section_value=self.section,
      source_section_value=self.organisation_module.client_1,
      lines=(dict(destination_value=self.account_module.goods_purchase,
                  destination_debit=500),
             dict(destination_value=self.account_module.receivable,
                  destination_credit=500)))
    self.assertIn(
      ('from main section', parent_bank_account.getRelativeUrl()),
      destination_transaction.AccountingTransaction_getDestinationPaymentItemList())
4419 4420 4421 4422
    self.assertIn(
      ('from section', bank_account.getRelativeUrl()),
      destination_transaction.AccountingTransaction_getDestinationPaymentItemList())

4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445
    main_section_transaction = self._makeOne(
      portal_type='Payment Transaction',
      source_section_value=self.main_section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  source_credit=500)))
    self.assertIn(
      ('from main section', parent_bank_account.getRelativeUrl()),
      main_section_transaction.AccountingTransaction_getSourcePaymentItemList())
    self.assertNotIn(
      ('from section', bank_account.getRelativeUrl()),
      main_section_transaction.AccountingTransaction_getSourcePaymentItemList())

    # We don't have this non selectable element when all bank accounts are from
    # the same organisation
    self.assertEqual(
      [('', ''),
       ('from main section', parent_bank_account.getRelativeUrl()),
      ],
      main_section_transaction.AccountingTransaction_getSourcePaymentItemList())

4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500
  def test_AccountingTransaction_getSourcePaymentItemList_parent_section_with_accounting_period(self):
    # AccountingTransaction_getSourcePaymentItemList and AccountingTransaction_getDestinationPaymentItemList
    # allows to select bank accounts from parent groups of source section, but not if
    # the organisation has accounting periods, in this case it acts as an independant section.
    parent_bank_account = self.main_section.newContent(
      portal_type='Bank Account',
      reference='from main section'
    )
    parent_bank_account.validate()
    main_section_accounting_period = self.main_section.newContent(
      portal_type='Accounting Period',
    )
    main_section_accounting_period.start()
    bank_account = self.section.newContent(
      portal_type='Bank Account',
      reference='from section'
    )
    bank_account.validate()
    # open an accounting periods in this section, it will act as an independant section
    # and will not allow bank accounts from parent sections.
    section_accounting_period = self.section.newContent(
      portal_type='Accounting Period',
    )
    section_accounting_period.start()
    self.tic()

    source_transaction = self._makeOne(
      portal_type='Payment Transaction',
      source_section_value=self.section,
      destination_section_value=self.organisation_module.client_1,
      lines=(dict(source_value=self.account_module.goods_purchase,
                  source_debit=500),
             dict(source_value=self.account_module.receivable,
                  source_credit=500)))
    self.assertNotIn(
      ('from main section', parent_bank_account.getRelativeUrl()),
      source_transaction.AccountingTransaction_getSourcePaymentItemList())
    self.assertIn(
      ('from section', bank_account.getRelativeUrl()),
      source_transaction.AccountingTransaction_getSourcePaymentItemList())

    destination_transaction = self._makeOne(
      portal_type='Payment Transaction',
      destination_section_value=self.section,
      source_section_value=self.organisation_module.client_1,
      lines=(dict(destination_value=self.account_module.goods_purchase,
                  destination_debit=500),
             dict(destination_value=self.account_module.receivable,
                  destination_credit=500)))
    self.assertNotIn(
      ('from main section', parent_bank_account.getRelativeUrl()),
      destination_transaction.AccountingTransaction_getDestinationPaymentItemList())
    self.assertIn(
      ('from section', bank_account.getRelativeUrl()),
      destination_transaction.AccountingTransaction_getDestinationPaymentItemList())
4501

4502

4503
class TestAccountingWithSequences(ERP5TypeTestCase):
4504 4505
  """The first test for Accounting
  """
4506 4507 4508

  def getBusinessTemplateList(self):
    """Returns list of BT to be installed."""
4509 4510 4511
    return ('erp5_core_proxy_field_legacy', 'erp5_base', 'erp5_pdm',
            'erp5_simulation', 'erp5_trade', 'erp5_accounting',
            'erp5_simulation_test')
4512

4513
  # XXX
Jérome Perrin's avatar
Jérome Perrin committed
4514
  def playSequence(self, sequence_string, quiet=1) :
4515 4516
    sequence_list = SequenceList()
    sequence_list.addSequenceString(sequence_string)
Jérome Perrin's avatar
Jérome Perrin committed
4517
    sequence_list.play(self, quiet=quiet)
4518

4519
  account_portal_type           = 'Account'
4520
  accounting_period_portal_type = 'Accounting Period'
4521 4522
  accounting_transaction_portal_type = 'Accounting Transaction'
  accounting_transaction_line_portal_type = 'Accounting Transaction Line'
4523 4524 4525 4526 4527 4528 4529 4530
  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'

4531
  start_date = DateTime(2004, 1, 1)
4532 4533
  stop_date  = DateTime(2004, 12, 31)

4534 4535
  default_region = 'europe/west/france'

4536 4537
  def getTitle(self):
    return "Accounting"
4538

4539 4540
  def afterSetUp(self):
    """Prepare the test."""
4541 4542 4543 4544
    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
4545
    self.createCategories()
4546 4547 4548
    self.createCurrencies()
    self.createEntities()
    self.createAccounts()
Jérome Perrin's avatar
Jérome Perrin committed
4549
    self.validateRules()
4550 4551 4552 4553 4554

    # 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',
4555
         priority=Priority.USER )
4556 4557
    self.workflow_tool.doActionFor(self.pref, 'enable_action')

4558 4559
  def beforeTearDown(self):
    """Cleanup for next test.
4560
    """
4561
    self.abort()
4562 4563
    for folder in (self.accounting_module, self.portal.portal_simulation):
      folder.manage_delObjects([i for i in folder.objectIds()])
4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576

    # Some tests commits transaction, some other does not, so accounts and
    # organisations created in this tests will not always be present at this
    # point
    folder = self.portal.account_module
    for account in self.account_list:
      if account.getId() in folder.objectIds():
        folder.manage_delObjects([account.getId()])
    folder = self.portal.organisation_module
    for entity in (self.client, self.vendor, self.other_vendor):
      if entity.getId() in folder.objectIds():
        folder.manage_delObjects([entity.getId()])

4577
    self.tic()
4578

4579 4580 4581
  def createCategories(self):
    """Create the categories for our test. """
    # create categories
4582
    for cat_string in self.getNeededCategoryList():
4583 4584
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
4585 4586
      for cat in cat_string.split("/")[1:]:
        if not cat in path.objectIds():
4587
          path = path.newContent(
4588
            portal_type='Category',
4589
            id=cat,)
4590 4591
        else:
          path = path[cat]
4592

4593 4594 4595 4596 4597
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)
4598

4599
  def getNeededCategoryList(self):
4600
    """Returns a list of categories that should be created."""
4601
    return ('group/client', 'group/vendor/sub1', 'group/vendor/sub2',
4602
            'payment_mode/check', 'region/%s' % self.default_region, )
4603

4604 4605 4606
  def createEntities(self):
    """Create entities. """
    self.client = self.getOrganisationModule().newContent(
4607
        title = 'Client',
4608
        portal_type = self.organisation_portal_type,
4609
        group = "client",
4610
        price_currency = "currency_module/USD")
4611
    self.section = self.vendor = self.getOrganisationModule().newContent(
4612
        title = 'Vendor',
4613
        portal_type = self.organisation_portal_type,
4614
        group = "vendor/sub1",
4615 4616
        price_currency = "currency_module/EUR")
    self.other_vendor = self.getOrganisationModule().newContent(
4617
        title = 'Other Vendor',
4618
        portal_type = self.organisation_portal_type,
4619
        group = "vendor/sub2",
4620
        price_currency = "currency_module/EUR")
4621
    # validate entities
4622
    for entity in (self.client, self.vendor, self.other_vendor):
4623 4624
      entity.setRegion(self.default_region)
      self.getWorkflowTool().doActionFor(entity, 'validate_action')
4625
    self.tic()
4626

4627 4628 4629 4630 4631 4632 4633
  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 )
4634

4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645
  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] )
4646

4647 4648 4649
  def stepUseValidDates(self, sequence, **kw):
    """Puts some valid dates in sequence."""
    sequence.edit(date_list = sequence.get('valid_date_list'))
4650

4651 4652 4653
  def stepUseInvalidDates(self, sequence, **kw):
    """Puts some invalid dates in sequence."""
    sequence.edit(date_list = sequence.get('invalid_date_list'))
4654

4655 4656 4657 4658 4659
  def stepOpenAccountingPeriod(self, sequence, **kw):
    """Opens the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
    self.getPortal().portal_workflow.doActionFor(
                        accounting_period,
4660
                        'start_action' )
4661
    self.assertEqual(accounting_period.getSimulationState(),
4662
                      'started')
4663

4664 4665
  def stepStopAccountingPeriod(self, sequence, **kw):
    """Stops the Accounting Period."""
4666
    accounting_period = sequence.get('accounting_period')
4667 4668
    # take any account for profit and loss account, here we don't care
    profit_and_loss_account = self.portal.account_module.contentValues()[0]
4669
    self.getPortal().portal_workflow.doActionFor(
4670 4671
           accounting_period, 'stop_action',
           profit_and_loss_account=profit_and_loss_account.getRelativeUrl())
4672
    self.assertEqual(accounting_period.getSimulationState(),
4673
                      'stopped')
4674

4675 4676 4677 4678 4679
  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,
4680
          accounting_period, 'stop_action' )
4681

4682 4683 4684
  def stepDeliverAccountingPeriod(self, sequence, **kw):
    """Deliver the Accounting Period."""
    accounting_period = sequence.get('accounting_period')
4685 4686
    self.portal.portal_workflow.doActionFor(
           accounting_period, 'deliver_action', )
4687
    self.assertEqual(accounting_period.getSimulationState(),
4688
                      'delivered')
4689

4690 4691 4692
  def stepCheckAccountingPeriodDelivered(self, sequence, **kw):
    """Check the Accounting Period is delivered."""
    accounting_period = sequence.get('accounting_period')
4693
    self.assertEqual(accounting_period.getSimulationState(),
4694
                      'delivered')
4695

4696 4697 4698 4699 4700 4701 4702 4703
  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(
4704
          portal_type = self.currency_portal_type,
4705 4706
          reference = "EUR", id = "EUR" )
      self.USD = currency_module.newContent(
4707
          portal_type = self.currency_portal_type,
4708 4709
          reference = "USD", id = "USD" )
      self.YEN = currency_module.newContent(
4710
          portal_type = self.currency_portal_type,
4711 4712 4713 4714 4715 4716 4717 4718 4719 4720
          reference = "YEN", id = "YEN" )
      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. """
    sequence.edit(EUR=self.EUR, USD=self.USD, YEN=self.YEN)
4721

4722 4723 4724
  def createAccounts(self):
    """Create some accounts.
    """
Jérome Perrin's avatar
Jérome Perrin committed
4725 4726
    account_module = self.portal.account_module
    receivable = self.receivable_account = account_module.newContent(
4727 4728 4729
          title = 'receivable',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable' )
Jérome Perrin's avatar
Jérome Perrin committed
4730
    payable = self.payable_account = account_module.newContent(
4731 4732 4733
          title = 'payable',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable' )
Jérome Perrin's avatar
Jérome Perrin committed
4734
    expense = self.expense_account = account_module.newContent(
4735 4736 4737
          title = 'expense',
          portal_type = self.account_portal_type,
          account_type = 'expense' )
Jérome Perrin's avatar
Jérome Perrin committed
4738
    income = self.income_account = account_module.newContent(
4739 4740 4741
          title = 'income',
          portal_type = self.account_portal_type,
          account_type = 'income' )
Jérome Perrin's avatar
Jérome Perrin committed
4742
    collected_vat = self.collected_vat_account = account_module.newContent(
4743 4744 4745
          title = 'collected_vat',
          portal_type = self.account_portal_type,
          account_type = 'liability/payable/collected_vat' )
Jérome Perrin's avatar
Jérome Perrin committed
4746
    refundable_vat = self.refundable_vat_account = account_module.newContent(
4747 4748 4749
          title = 'refundable_vat',
          portal_type = self.account_portal_type,
          account_type = 'asset/receivable/refundable_vat' )
Jérome Perrin's avatar
Jérome Perrin committed
4750
    bank = self.bank_account = self.account_module.newContent(
4751 4752 4753
          title = 'bank',
          portal_type = self.account_portal_type,
          account_type = 'asset/cash/bank')
4754

4755 4756 4757 4758 4759 4760 4761 4762
    # 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)
4763

4764 4765 4766 4767 4768 4769 4770
    self.account_list = [ receivable,
                          payable,
                          expense,
                          income,
                          collected_vat,
                          refundable_vat,
                          bank ]
4771

4772
    for account in self.account_list :
4773
      account.validate()
4774 4775
      self.assertTrue('Site Error' not in account.view())
      self.assertEqual(account.getValidationState(), 'validated')
4776
    self.tic()
4777

4778 4779 4780 4781 4782 4783 4784 4785 4786 4787
  def stepCreateAccounts(self, sequence, **kw) :
    """Create necessary accounts. """
    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 )
4788 4789


4790
  def getInvoicePropertyList(self):
4791
    """Returns the list of properties for invoices, stored as
4792 4793 4794 4795 4796 4797 4798 4799 4800
      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' },
4801

4802 4803
      # in currency of source, converted for destination
      { 'income' : -100,        'destination_converted_expense' : -200,
4804
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
4805 4806
        'receivable' : 90,      'destination_converted_payable' : 100,
        'currency' : 'currency_module/EUR' },
4807

4808
      { 'income' : -100,        'destination_converted_expense' : -200,
4809
        'collected_vat' : 10,   'destination_converted_refundable_vat' : 100,
4810 4811
        'receivable' : 90,      'destination_converted_payable' : 100,
        'currency' : 'currency_module/EUR' },
4812

4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823
      # 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' },
4824

4825 4826 4827 4828 4829
      # currency of source, not converted for destination -> 0
      { 'income' : -100,
        'collected_vat' : -20,
        'receivable' : 120,
        'currency' : 'currency_module/EUR' },
4830

4831
    ]
4832

4833 4834 4835 4836
  def stepCreateInvoices(self, sequence, **kw) :
    """Create invoices with properties from getInvoicePropertyList. """
    invoice_prop_list = self.getInvoicePropertyList()
    invoice_list = []
4837 4838 4839
    date_list = sequence.get('date_list')
    if not date_list : date_list = [ DateTime(2004, 12, 31) ]
    i = 0
4840
    for invoice_prop in invoice_prop_list :
4841 4842
      i += 1
      date = date_list[i % len(date_list)]
Jérome Perrin's avatar
Jérome Perrin committed
4843
      invoice = self.portal.accounting_module.newContent(
4844 4845 4846 4847 4848 4849
          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'],
4850
          start_date = date, stop_date = date,
4851
          created_by_builder = 0,
4852
      )
4853

4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864
      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)
4865

4866 4867 4868 4869 4870 4871 4872
        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)
4873

4874 4875
      invoice_list.append(invoice)
    sequence.edit( invoice_list = invoice_list )
4876

4877 4878 4879 4880 4881 4882
  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' )
Jérome Perrin's avatar
Jérome Perrin committed
4883
    invoice = self.portal.accounting_module.newContent(
4884 4885 4886 4887 4888 4889 4890 4891
        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,
4892
        created_by_builder = 0,
4893
    )
4894

4895 4896 4897 4898 4899 4900 4901
    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])
4902

4903 4904 4905 4906 4907 4908
  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')
4909

4910 4911 4912 4913 4914 4915 4916
  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')
4917 4918 4919 4920 4921

  def stepCheckInvoicesAreDraft(self, sequence, **kw) :
    """Checks invoices are in draft state."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
4922
      self.assertEqual(invoice.getSimulationState(), 'draft')
4923 4924 4925 4926 4927

  def stepCheckInvoicesAreStopped(self, sequence, **kw) :
    """Checks invoices are in stopped state."""
    invoice_list = sequence.get('invoice_list')
    for invoice in invoice_list:
4928
      self.assertEqual(invoice.getSimulationState(), 'stopped')
4929

4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943
  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() :
4944
            calculated_balance += (
4945 4946 4947
                    line.getSourceDebit() - line.getSourceCredit())
          # dest.
          elif line.getDestinationValue() == account and\
4948 4949 4950
            line.getResourceValue() == currency and\
            section == line.getDestinationSectionValue() :
            calculated_balance += (
4951
                    line.getDestinationDebit() - line.getDestinationCredit())
4952

4953
      self.assertEqual(calculated_balance,
4954 4955 4956
          self.getPortal().portal_simulation.getInventory(
            node_uid = account.getUid(),
            section_uid = section.getUid(),
4957
            resource_uid = currency.getUid(),
4958
          ))
4959

4960 4961 4962 4963 4964
  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)
4965

4966 4967 4968 4969 4970
  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)
4971

4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987
  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()
4988
      self.assertEqual(calculated_balance,
4989 4990 4991 4992
          self.getPortal().portal_simulation.getInventoryAssetPrice(
            node_uid = account.getUid(),
            section_uid = section.getUid(),
          ))
4993

4994 4995 4996 4997 4998
  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)
4999

5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014
  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")
5015

5016 5017
    portal = self.getPortal()
    accounting_module = portal.accounting_module
5018
    self.assertTrue('Site Error' not in accounting_module.view())
5019 5020 5021 5022
    self.assertNotEquals(
          len(portal.getPortalAccountingMovementTypeList()), 0)
    self.assertNotEquals(
          len(portal.getPortalAccountingTransactionTypeList()), 0)
Sebastien Robin's avatar
Sebastien Robin committed
5023
    for accounting_portal_type in accounting_module.allowedContentTypes():
5024
      accounting_transaction = accounting_module.newContent(
Sebastien Robin's avatar
Sebastien Robin committed
5025
            portal_type = accounting_portal_type.getId(),
5026 5027 5028
            source_section_value = source_section_value,
            destination_section_value = destination_section_value,
            resource_value = resource_value )
5029 5030
      self.assertTrue('Site Error' not in accounting_transaction.view())
      self.assertEqual( accounting_transaction.getSourceSectionValue(),
5031
                         source_section_value )
5032
      self.assertEqual( accounting_transaction.getDestinationSectionValue(),
5033
                         destination_section_value )
5034
      self.assertEqual( accounting_transaction.getResourceValue(),
5035 5036 5037 5038 5039 5040 5041 5042 5043 5044
                         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, )
5045
          self.assertTrue('Site Error' not in line.view())
5046
          # section and resource is acquired from parent transaction.
5047
          self.assertEqual( line.getDestinationSectionValue(),
5048
                             destination_section_value )
5049
          self.assertEqual( line.getDestinationSectionTitle(),
5050
                             destination_section_title )
5051
          self.assertEqual( line.getSourceSectionValue(),
5052
                             source_section_value )
5053
          self.assertEqual( line.getSourceSectionTitle(),
5054
                             source_section_title )
5055
          self.assertEqual( line.getResourceValue(),
5056 5057 5058 5059 5060 5061 5062 5063
                             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 ))
5064

5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079
  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:
5080
      start_date = DateTime(2000, 1, 1)
5081 5082 5083 5084 5085 5086 5087 5088 5089 5090
      # 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
5091
      stop_date = DateTime(2000, 2, 2)
5092 5093 5094 5095 5096 5097
      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
5098

5099
    # create the transaction.
Jérome Perrin's avatar
Jérome Perrin committed
5100
    accounting_transaction = self.portal.accounting_module.newContent(
5101 5102 5103 5104 5105 5106 5107
      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
5108 5109
                             # creating lines.
    )
5110
    income = accounting_transaction.newContent(
5111 5112
                  id='income',
                  portal_type=line_portal_type,
5113
                  quantity=-quantity,
5114 5115 5116
                  source_value=kw.get('income_account', self.income_account),
                  destination_value=kw.get('expense_account',
                                              self.expense_account), )
5117 5118
    self.assertTrue(income.getSource() != None)
    self.assertTrue(income.getDestination() != None)
5119

5120
    receivable = accounting_transaction.newContent(
5121 5122
                  id='receivable',
                  portal_type=line_portal_type,
5123
                  quantity=quantity,
5124 5125 5126 5127
                  source_value=kw.get('receivable_account',
                                          self.receivable_account),
                  destination_value=kw.get('payable_account',
                                            self.payable_account), )
5128 5129
    self.assertTrue(receivable.getSource() != None)
    self.assertTrue(receivable.getDestination() != None)
5130 5131 5132
    if reindex:
      self.tic()
    if check_consistency:
5133
      self.assertTrue(len(accounting_transaction.checkConsistency()) == 0,
5134 5135
         "Check consistency failed : %s" % accounting_transaction.checkConsistency())
    return accounting_transaction
5136

5137 5138 5139 5140
  def test_createAccountingTransaction(self):
    """Make sure acounting transactions created by createAccountingTransaction
    method are valid.
    """
5141
    accounting_transaction = self.createAccountingTransaction()
5142 5143 5144 5145
    self.assertEqual(self.vendor, accounting_transaction.getSourceSectionValue())
    self.assertEqual(self.client, accounting_transaction.getDestinationSectionValue())
    self.assertEqual(self.EUR, accounting_transaction.getResourceValue())
    self.assertTrue(accounting_transaction.AccountingTransaction_isSourceView())
5146

5147
    self.workflow_tool.doActionFor(accounting_transaction, 'stop_action')
5148 5149
    self.assertEqual('stopped', accounting_transaction.getSimulationState())
    self.assertEqual([] , accounting_transaction.checkConsistency())
5150

5151 5152 5153 5154
  def stepCreateValidAccountingTransaction(self, sequence,
                                          sequence_list=None, **kw) :
    """Creates a valid accounting transaction and put it in
    the sequence as `transaction` key. """
5155
    accounting_transaction = self.createAccountingTransaction(
5156 5157 5158 5159 5160 5161 5162
                            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'), )
5163
    sequence.edit(
5164 5165 5166
      transaction = accounting_transaction,
      income = accounting_transaction.income,
      receivable = accounting_transaction.receivable
5167
    )
5168

5169 5170
  def stepValidateNoDate(self, sequence, sequence_list=None, **kw) :
    """When no date is defined, validation should be impossible.
5171

5172 5173 5174 5175 5176 5177
    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.
    """
5178 5179 5180 5181 5182 5183 5184
    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)
5185 5186
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5187
        accounting_transaction,
5188
        'stop_action')
5189 5190 5191
    accounting_transaction.setStartDate(old_start_date)
    accounting_transaction.setStopDate(old_stop_date)
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5192
    self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5193

5194 5195 5196
  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
5197
    cases :
5198 5199 5200 5201 5202
      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.
    """
5203 5204 5205
    accounting_transaction = sequence.get('transaction')
    old_source_section = accounting_transaction.getSourceSection()
    old_destination_section = accounting_transaction.getDestinationSection()
5206 5207
    # default transaction uses payable accounts, so validating without
    # source section is refused.
5208
    accounting_transaction.setSourceSection(None)
5209 5210
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5211
        accounting_transaction,
5212 5213
        'stop_action')
    # ... as well as validation without destination section
5214 5215
    accounting_transaction.setSourceSection(old_source_section)
    accounting_transaction.setDestinationSection(None)
5216 5217
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5218
        accounting_transaction,
5219 5220
        'stop_action')
    # mirror section can be set only on the line
5221
    for line in accounting_transaction.getMovementList() :
5222
      line.setDestinationSection(old_destination_section)
5223
    try:
5224
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5225
      self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5226
    except ValidationFailed as err:
5227
      self.assert_(0, "Validation failed : %s" % err.msg)
5228

5229 5230
    # if we do not use any payable / receivable account, then we can
    # validate the transaction without setting the mirror section.
5231 5232 5233 5234
    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.

5235
      # get a new valid transaction
5236
      accounting_transaction = self.createAccountingTransaction()
5237
      expense_account = sequence.get('expense_account')
5238
      for line in accounting_transaction.getMovementList() :
5239 5240 5241
        line.edit( source_value = expense_account,
                   destination_value = expense_account )
      if side == SOURCE :
5242
        accounting_transaction.setDestinationSection(None)
5243
      else :
5244
        accounting_transaction.setSourceSection(None)
5245
      try:
5246
        self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5247
        self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5248
      except ValidationFailed as err:
5249
        self.assert_(0, "Validation failed : %s" % err.msg)
5250

5251 5252 5253
  def stepValidateNoCurrency(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour related to currency.
    """
5254 5255 5256
    accounting_transaction = sequence.get('transaction')
    old_resource = accounting_transaction.getResource()
    accounting_transaction.setResource(None)
5257 5258
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5259
        accounting_transaction,
5260 5261 5262
        'stop_action')
    # setting a dummy relationship is not enough, resource must be a
    # currency
5263
    accounting_transaction.setResourceValue(
5264
         self.portal.product_module.newContent(portal_type='Product'))
5265 5266
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5267
        accounting_transaction,
5268
        'stop_action')
5269

5270 5271 5272 5273 5274
  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.
    """
5275 5276
    accounting_transaction = sequence.get('transaction')
    account = accounting_transaction.getMovementList()[0].getSourceValue()
5277
    self.getWorkflowTool().doActionFor(account, 'invalidate_action')
5278
    self.assertEqual(account.getValidationState(), 'invalidated')
5279 5280
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5281
        accounting_transaction,
5282 5283 5284
        'stop_action')
    # reopen the account for other tests
    account.validate()
5285
    self.assertEqual(account.getValidationState(), 'validated')
5286

5287 5288 5289 5290
  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.
    """
5291
    accounting_transaction = sequence.get('transaction')
5292
    # no account at all is refused
5293
    for line in accounting_transaction.getMovementList():
5294 5295 5296 5297
      line.setSource(None)
      line.setDestination(None)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5298
        accounting_transaction,
5299
        'stop_action')
5300

5301
    # only one line without account and with a quantity is also refused
5302 5303 5304
    accounting_transaction = self.createAccountingTransaction()
    accounting_transaction.getMovementList()[0].setSource(None)
    accounting_transaction.getMovementList()[0].setDestination(None)
5305 5306
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5307
        accounting_transaction,
5308
        'stop_action')
5309

5310 5311
    # but if we have a line with 0 quantity on both sides, we can
    # validate the transaction and delete this line.
5312 5313 5314
    accounting_transaction = self.createAccountingTransaction()
    line_count = len(accounting_transaction.getMovementList())
    accounting_transaction.newContent(
5315
        portal_type = self.accounting_transaction_line_portal_type)
5316
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5317 5318
    self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
    self.assertEqual(line_count, len(accounting_transaction.getMovementList()))
5319

5320 5321
    # 0 quantity, but a destination asset price => do not delete the
    # line
5322 5323
    accounting_transaction = self.createAccountingTransaction()
    new_line = accounting_transaction.newContent(
5324
        portal_type = self.accounting_transaction_line_portal_type)
5325
    self.assertEqual(len(accounting_transaction.getMovementList()), 3)
5326
    line_list = accounting_transaction.getMovementList()
5327
    line_list[0].setDestinationTotalAssetPrice(100)
5328 5329
    line_list[0]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
5330
    line_list[1].setDestinationTotalAssetPrice(- 50)
5331 5332
    line_list[1]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
5333
    line_list[2].setDestinationTotalAssetPrice(- 50)
5334 5335
    line_list[2]._setCategoryMembership(
          'destination', sequence.get('expense_account').getRelativeUrl())
5336
    try:
5337
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5338
      self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5339
    except ValidationFailed as err:
5340
      self.assert_(0, "Validation failed : %s" % err.msg)
5341

5342 5343 5344
  def stepValidateNotBalanced(self, sequence, sequence_list=None, **kw) :
    """Check validation behaviour when transaction is not balanced.
    """
5345 5346
    accounting_transaction = sequence.get('transaction')
    accounting_transaction.getMovementList()[0].setQuantity(4325)
5347 5348
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5349
        accounting_transaction,
5350
        'stop_action')
5351

5352 5353
    # asset price have priority (ie. if asset price is not balanced,
    # refuses validation even if quantity is balanced)
5354 5355
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
5356 5357 5358 5359
    line_list[0].setDestinationTotalAssetPrice(10)
    line_list[1].setDestinationTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5360
        accounting_transaction,
5361
        'stop_action')
5362

5363 5364
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
5365 5366 5367 5368
    line_list[0].setSourceTotalAssetPrice(10)
    line_list[1].setSourceTotalAssetPrice(100)
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5369
        accounting_transaction,
5370
        'stop_action')
5371

5372
    # only asset price needs to be balanced
5373 5374
    accounting_transaction = self.createAccountingTransaction(resource_value=self.YEN)
    line_list = accounting_transaction.getMovementList()
5375 5376 5377 5378 5379 5380 5381
    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:
5382
      self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5383
      self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5384
    except ValidationFailed as err:
5385
      self.assert_(0, "Validation failed : %s" % err.msg)
5386

5387 5388 5389 5390 5391 5392 5393 5394
  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.
    """
5395
    def useBankAccount(accounting_transaction):
5396 5397 5398 5399 5400
      """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
5401
      for line in accounting_transaction.getMovementList() :
5402 5403 5404 5405 5406
        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') )
5407
      self.assertTrue(income_account_found)
5408
    # XXX
5409 5410
    accounting_transaction = sequence.get('transaction')
    useBankAccount(accounting_transaction)
5411 5412
    self.assertRaises(ValidationFailed,
        self.getWorkflowTool().doActionFor,
5413
        accounting_transaction,
5414
        'stop_action')
5415

5416 5417
    source_section_value = accounting_transaction.getSourceSectionValue()
    destination_section_value = accounting_transaction.getDestinationSectionValue()
5418 5419 5420 5421 5422
    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, )
5423
      accounting_transaction = self.createAccountingTransaction(
5424
                      destination_section_value=self.other_vendor)
5425
      useBankAccount(accounting_transaction)
5426

5427 5428
      # payment node have to be set on both sides if both sides have accounting
      # lines
5429 5430
      accounting_transaction.setSourcePaymentValue(source_payment_value)
      accounting_transaction.setDestinationPaymentValue(None)
5431 5432
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
5433
          accounting_transaction,
5434
          'stop_action')
5435 5436
      accounting_transaction.setSourcePaymentValue(None)
      accounting_transaction.setDestinationPaymentValue(destination_payment_value)
5437 5438
      self.assertRaises(ValidationFailed,
          self.getWorkflowTool().doActionFor,
5439
          accounting_transaction,
5440
          'stop_action')
5441 5442
      accounting_transaction.setSourcePaymentValue(source_payment_value)
      accounting_transaction.setDestinationPaymentValue(destination_payment_value)
5443
      try:
5444
        self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5445
        self.assertEqual(accounting_transaction.getSimulationState(), 'stopped')
5446
      except ValidationFailed as err:
5447
        self.fail("Validation failed : %s" % err.msg)
5448

5449 5450
  def stepValidateRemoveEmptyLines(self, sequence, sequence_list=None, **kw):
    """Check validating a transaction remove empty lines. """
5451 5452
    accounting_transaction = sequence.get('transaction')
    lines_count = len(accounting_transaction.getMovementList())
5453
    empty_lines_count = 0
5454
    for line in accounting_transaction.getMovementList():
5455 5456 5457 5458
      if line.getSourceTotalAssetPrice() ==  \
         line.getDestinationTotalAssetPrice() == 0:
        empty_lines_count += 1
    if empty_lines_count == 0:
5459
      accounting_transaction.newContent(
5460
            portal_type=self.accounting_transaction_line_portal_type)
5461

5462
    self.getWorkflowTool().doActionFor(accounting_transaction, 'stop_action')
5463
    self.assertEqual(len(accounting_transaction.getMovementList()),
5464
                      lines_count - empty_lines_count)
5465

5466
    # we don't remove empty lines if there is only empty lines
5467
    another_accounting_transaction = self.portal.accounting_module.newContent(
5468
                      portal_type=self.accounting_transaction_portal_type,
5469 5470 5471 5472
                      start_date=accounting_transaction.getStartDate(),
                      resource=accounting_transaction.getResource(),
                      source_section=accounting_transaction.getSourceSection(),
                      destination_section=accounting_transaction.getDestinationSection(),
5473 5474
                      created_by_builder=1)
    for i in range(3):
5475
      another_accounting_transaction.newContent(
5476
            portal_type=self.accounting_transaction_line_portal_type)
5477 5478
    lines_count = len(another_accounting_transaction.getMovementList())
    self.getWorkflowTool().doActionFor(another_accounting_transaction, 'stop_action')
5479
    self.assertEqual(len(another_accounting_transaction.getMovementList()), lines_count)
5480

5481 5482 5483
  ############################################################################
  ## Test Methods ############################################################
  ############################################################################
5484

Jérome Perrin's avatar
Jérome Perrin committed
5485
  def test_MultiCurrencyInvoice(self, quiet=QUIET, run=RUN_ALL_TESTS):
5486
    """Basic test for multi currency accounting"""
5487
    if not run : return
5488 5489 5490 5491 5492 5493 5494 5495 5496
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateInvoices
      stepTic
      stepCheckAccountBalanceLocalCurrency
      stepCheckAccountBalanceExternalCurrency
      stepCheckAccountBalanceConvertedCurrency
Jérome Perrin's avatar
Jérome Perrin committed
5497
    """, quiet=quiet)
5498 5499

  def test_AccountingPeriodRefusesWrongDateTransactionValidation(
Jérome Perrin's avatar
Jérome Perrin committed
5500
        self, quiet=QUIET, run=RUN_ALL_TESTS):
5501 5502
    """Accounting Periods prevents transactions from being validated when there
    is no oppened accounting period"""
5503
    if not run : return
5504 5505 5506 5507 5508 5509 5510 5511 5512
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepUseInvalidDates
      stepCreateInvoices
5513
      stepCheckStopInvoicesRefused
5514 5515
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
5516
    """, quiet=quiet)
5517

Jérome Perrin's avatar
Jérome Perrin committed
5518
  def test_AccountingPeriodNotStoppedTransactions(self, quiet=QUIET,
5519 5520 5521
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods refuse to close when some transactions are
      not stopped"""
5522
    if not run : return
5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateInvoices
      stepTic
      stepCheckAccountingPeriodRefusesClosing
      stepTic
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
5535
    """, quiet=quiet)
5536

Jérome Perrin's avatar
Jérome Perrin committed
5537
  def test_AccountingPeriodOtherSections(self, quiet=QUIET,
5538 5539
                                                  run=RUN_ALL_TESTS):
    """Accounting Periods does not change other section transactions."""
5540
    if not run : return
5541 5542 5543 5544 5545 5546 5547 5548 5549
    self.playSequence("""
      stepCreateCurrencies
      stepCreateEntities
      stepCreateAccounts
      stepCreateAccountingPeriod
      stepOpenAccountingPeriod
      stepTic
      stepCreateOtherSectionInvoices
      stepTic
5550
      stepStopAccountingPeriod
5551 5552 5553
      stepTic
      stepDeliverAccountingPeriod
      stepTic
5554
      stepCheckAccountingPeriodDelivered
5555
      stepCheckInvoicesAreDraft
Jérome Perrin's avatar
Jérome Perrin committed
5556
    """, quiet=quiet)
5557

Jérome Perrin's avatar
Jérome Perrin committed
5558
  def test_Acquisition(self, quiet=QUIET, run=RUN_ALL_TESTS):
5559 5560 5561 5562 5563 5564
    """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
5565
      """, quiet=quiet)
5566

Jérome Perrin's avatar
Jérome Perrin committed
5567
  def test_AccountingTransactionValidationDate(self, quiet=QUIET,
5568 5569 5570 5571 5572 5573 5574 5575
                                            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
5576
      stepValidateNoDate""", quiet=quiet)
5577

5578

Jérome Perrin's avatar
Jérome Perrin committed
5579
  def test_AccountingTransactionValidationSection(self, quiet=QUIET,
5580 5581 5582 5583 5584 5585 5586 5587
                                             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
5588
      stepValidateNoSection""", quiet=quiet)
5589

Jérome Perrin's avatar
Jérome Perrin committed
5590
  def test_AccountingTransactionValidationCurrency(self, quiet=QUIET,
5591 5592 5593 5594 5595 5596 5597 5598
                                           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
5599
      stepValidateNoCurrency""", quiet=quiet)
5600

Jérome Perrin's avatar
Jérome Perrin committed
5601
  def test_AccountingTransactionValidationAccounts(self, quiet=QUIET,
5602 5603 5604 5605 5606 5607 5608 5609 5610 5611
                                           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
5612
      stepValidateNoAccounts""", quiet=quiet)
5613

Jérome Perrin's avatar
Jérome Perrin committed
5614
  def test_AccountingTransactionValidationBalanced(self, quiet=QUIET,
5615 5616 5617 5618 5619 5620 5621 5622
                                              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
5623
      stepValidateNotBalanced""", quiet=quiet)
5624

Jérome Perrin's avatar
Jérome Perrin committed
5625
  def test_AccountingTransactionValidationPayment(self, quiet=QUIET,
5626 5627 5628 5629 5630 5631 5632 5633 5634
                                             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
5635
    """, quiet=quiet)
5636

Jérome Perrin's avatar
Jérome Perrin committed
5637
  def test_AccountingTransactionValidationRemoveEmptyLines(self, quiet=QUIET,
5638 5639 5640 5641 5642 5643 5644 5645 5646
                                             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
5647
    """, quiet=quiet)
5648

5649

5650 5651 5652 5653 5654 5655 5656
class TestAccountingTransactionTemplate(AccountingTestCase):
  """A test for Accounting Transaction Template
  """

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

5657 5658 5659 5660 5661 5662
  def disableUserPreferenceList(self):
    """Disable existing User preferences."""
    for preference in self.portal.portal_preferences.objectValues():
      if preference.getPriority() == Priority.USER:
        preference.disable()

5663
  def test_Template(self):
5664
    self.disableUserPreferenceList()
5665
    self.createUserAndlogin('claudie')
5666 5667 5668 5669 5670 5671
    preference = self.portal.portal_preferences.newContent('Preference')
    preference.priority = Priority.USER
    preference.enable()

    self.tic()

Jérome Perrin's avatar
Jérome Perrin committed
5672 5673
    document = self.accounting_module.newContent(
                    portal_type='Accounting Transaction')
5674 5675 5676 5677 5678 5679 5680
    document.edit(title='My Accounting Transaction')
    document.Base_makeTemplateFromDocument(form_id=None)

    self.tic()

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

Yusei Tahara's avatar
Yusei Tahara committed
5681 5682 5683 5684
    # 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)

5685 5686 5687 5688 5689 5690
    self.accounting_module.manage_delObjects(ids=[document.getId()])

    self.tic()

    template = preference.objectValues()[0]

Jérome Perrin's avatar
Jérome Perrin committed
5691 5692
    cp = preference.manage_copyObjects(ids=[template.getId()],
                                       REQUEST=None, RESPONSE=None)
5693 5694 5695 5696 5697 5698 5699 5700 5701
    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()

    self.tic()

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

5702 5703 5704
  def test_Base_doAction(self):
    # test creating a template using Base_doAction script (this is what
    # erp5_xhtml_style does)
5705
    self.disableUserPreferenceList()
5706
    self.createUserAndlogin('claudie')
5707 5708 5709 5710 5711 5712 5713 5714 5715 5716
    preference = self.portal.portal_preferences.newContent('Preference')
    preference.priority = Priority.USER
    preference.enable()

    self.tic()

    document = self.accounting_module.newContent(
                              portal_type='Accounting Transaction')
    document.edit(title='My Accounting Transaction')
    document.Base_makeTemplateFromDocument(form_id=None)
5717

5718 5719 5720 5721
    template = preference.objectValues()[0]
    ret = self.accounting_module.Base_doAction(
        select_action='template %s' % template.getRelativeUrl(),
        form_id='', cancel_url='')
5722 5723
    self.assertTrue('Template%20created.' in ret, ret)
    self.assertEqual(2, len(self.accounting_module.contentValues()))
5724

5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843
class TestInternalInvoiceTransaction(AccountingTestCase):
  def afterSetUp(self):
    AccountingTestCase.afterSetUp(self)
    # Allow internal invoice in accounting module
    module_allowed_type_list = self.portal.portal_types[
        'Accounting Transaction Module'].getTypeAllowedContentTypeList()
    self.portal.portal_types[
        'Accounting Transaction Module'].setTypeAllowedContentTypeList(
          module_allowed_type_list + ['Internal Invoice Transaction',])
    # configure mirror accounts
    self.portal.account_module.receivable.setDestinationValue(
      self.portal.account_module.payable)

  def test_internal_invoice_transaction(self):
    # source accountant create internal invoice and set values for source side
    internal_invoice = self.portal.accounting_module.newContent(
      portal_type='Internal Invoice Transaction',
      title='test invoice',
      source_section_value=self.section,
      destination_section_value=self.main_section,
      start_date=DateTime(2015, 1, 1),
    )
    line_1, line_2 = internal_invoice.getMovementList()
    line_1.edit(
      source_value=self.portal.account_module.receivable,
      source_debit=100)
    line_2.edit(
      source_value=self.portal.account_module.goods_sales,
      source_credit=100)
    self.commit()
    internal_invoice.view() # no error on view..

    self.portal.portal_workflow.doActionFor(
        internal_invoice, 'start_action')
    self.assertEqual('started', internal_invoice.getSimulationState())

    # mirror accounts are initialised
    self.assertEqual(self.portal.account_module.payable, line_1.getDestinationValue())
    self.assertEqual(None, line_2.getDestinationValue())

    # destination accountant set values for source side
    internal_invoice.edit(
      stop_date=DateTime(2015, 1, 2),
    )
    # the amounts can be split over multiple accounts
    internal_invoice.newContent(
      portal_type='Internal Invoice Transaction Line',
      destination_value=self.portal.account_module.refundable_vat,
      destination_debit=30)
    internal_invoice.newContent(
      portal_type='Internal Invoice Transaction Line',
      destination_value=self.portal.account_module.goods_purchase,
      destination_debit=70)

    self.portal.portal_workflow.doActionFor(
        internal_invoice, 'stop_action')
    self.assertEqual('stopped', internal_invoice.getSimulationState())

    # the lines are different on source and destination views
    source_line_list = internal_invoice.InternalInvoiceTransaction_viewSource.listbox.get_value(
      'default',
      render_format='list',
      REQUEST=self.portal.REQUEST)
    self.assertEqual(2, len([l for l in source_line_list if l.isDataLine()]))
    stat_line, = [l for l in source_line_list if l.isStatLine()]
    self.assertEqual(100, stat_line.getColumnProperty('source_debit'))
    self.assertEqual(100, stat_line.getColumnProperty('source_credit'))

    destination_line_list = internal_invoice.InternalInvoiceTransaction_viewDestination.listbox.get_value(
      'default',
      render_format='list',
      REQUEST=self.portal.REQUEST)
    self.assertEqual(3, len([l for l in destination_line_list if l.isDataLine()]))
    stat_line, = [l for l in destination_line_list if l.isStatLine()]
    self.assertEqual(100, stat_line.getColumnProperty('destination_debit'))
    self.assertEqual(100, stat_line.getColumnProperty('destination_credit'))

  def test_internal_invoice_transaction_balanced_constraint(self):
    internal_invoice = self.portal.accounting_module.newContent(
      portal_type='Internal Invoice Transaction',
      title='test invoice',
      source_section_value=self.section,
      destination_section_value=self.main_section,
      start_date=DateTime(2015, 1, 1),
    )
    line_1, line_2 = internal_invoice.getMovementList()
    line_1.edit(
      source_value=self.portal.account_module.receivable,
      source_debit=100)
    line_2.edit(
      source_value=self.portal.account_module.goods_sales,
      source_credit=101)

    with self.assertRaisesRegexp(ValidationFailed,
        '.*Transaction is not balanced.*'):
      self.portal.portal_workflow.doActionFor(
        internal_invoice, 'start_action')

    line_2.setSourceCredit(100)
    self.portal.portal_workflow.doActionFor(
      internal_invoice, 'start_action')

    self.assertEqual('started', internal_invoice.getSimulationState())

    self.assertEqual(self.portal.account_module.payable, line_1.getDestinationValue())
    line_3 = internal_invoice.newContent(
      portal_type='Internal Invoice Transaction Line',
      destination_value=self.portal.account_module.refundable_vat,
      destination_debit=101)

    with self.assertRaisesRegexp(ValidationFailed,
        '.*Transaction is not balanced.*'):
      self.portal.portal_workflow.doActionFor(
        internal_invoice, 'stop_action')

    line_3.setDestinationDebit(100)
    self.portal.portal_workflow.doActionFor(
        internal_invoice, 'stop_action')
    self.assertEqual('stopped', internal_invoice.getSimulationState())
5844

5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885
  def test_internal_invoice_create_related_payment(self):
    # 'Create Related Payment' is available on internal invoice transaction
    internal_invoice = self.portal.accounting_module.newContent(
        portal_type='Internal Invoice Transaction',
        title='test invoice',
        source_section_value=self.section,
        destination_section_value=self.main_section,
        start_date=DateTime(2015, 1, 1),
    )
    line_1, line_2 = internal_invoice.getMovementList()
    line_1.edit(
        source_value=self.portal.account_module.receivable,
        source_debit=100)
    line_2.edit(
        source_value=self.portal.account_module.goods_sales,
        source_credit=100)
    self.commit()

    self.portal.portal_workflow.doActionFor(
        internal_invoice, 'start_action')
    self.assertEqual('started', internal_invoice.getSimulationState())

    payment_node = self.section.newContent(portal_type='Bank Account')

    payment = internal_invoice.Invoice_createRelatedPaymentTransaction(
        node=self.account_module.bank.getRelativeUrl(),
        payment=payment_node.getRelativeUrl(),
        payment_mode='check',
        batch_mode=True)
    # on internal invoice transaction, we create a payment transaction
    self.assertEqual(
        'Internal Invoice Transaction',
        payment.getPortalType())
    self.assertEqual(internal_invoice, payment.getCausalityValue())
    self.assertItemsEqual(
        [ (self.portal.account_module.bank, 100, 0),
          (self.portal.account_module.receivable, 0, 100), ],
        [ (line.getSourceValue(), line.getSourceDebit(), line.getSourceCredit())
          for line in payment.getMovementList(
              portal_type='Internal Invoice Transaction Line')])

5886

5887
class TestAccountingCodingStyle(CodingStyleTestCase.CodingStyleTestCase, AccountingTestCase):
5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901
  """Runs CodingStyleTestCase checks on erp5_accounting
  """
  def getBusinessTemplateList(self):
    # include administration for test_PythonSourceCode
    return AccountingTestCase.getBusinessTemplateList(self) + (
        'erp5_administration', )

  def getTestedBusinessTemplateList(self):
    return ('erp5_accounting', )

  def beforeTearDown(self):
    # we don't want to run AccountingTestCase.tearDown
    pass