testInvoice.py 153 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
##############################################################################
#
# Copyright (c) 2004-2008 Nexedi SA and Contributors. All Rights Reserved.
#          Sebastien Robin <seb@nexedi.com>
#          Jerome Perrin <jerome@nexedi.com>
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsibility 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
# guarantees 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.
#
##############################################################################
"""
  Tests invoice creation from simulation.

"""
33 34
import xml.dom.minidom
import zipfile
35

36
from Products.DCWorkflow.DCWorkflow import ValidationFailed
37
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
38
from Products.ERP5Type.tests.utils import FileUpload
39 40 41 42 43 44 45 46
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
from Products.ERP5OOo.OOoUtils import OOoParser
from AccessControl.SecurityManagement import newSecurityManager
from DateTime import DateTime
from Acquisition import aq_parent
from zLOG import LOG
from Products.ERP5Type.tests.Sequence import SequenceList
from testPackingList import TestPackingListMixin
47
from Products.ERP5.tests.utils import newSimulationExpectedFailure
48

49
class TestInvoiceMixin(TestPackingListMixin):
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
  """Test methods for invoices
  """
  default_region = "europe/west/france"
  vat_gap = 'fr/pcg/4/44/445/4457/44571'
  vat_rate = 0.196
  sale_gap = 'fr/pcg/7/70/707/7071/70712'
  customer_gap = 'fr/pcg/4/41/411'
  bank_gap = 'fr/pcg/5/51/512'
  mail_delivery_mode = 'by_mail'
  cpt_incoterm = 'cpt'
  unit_piece_quantity_unit = 'unit/piece'
  mass_quantity_unit = 'mass/kg'
  oldMailhost = None

  # (account_id, account_gap, account_type)
  account_definition_list = (
      ('receivable_vat', vat_gap, 'liability/payable/collected_vat',),
      ('sale', sale_gap, 'income'),
      ('customer', customer_gap, 'asset/receivable'),
      ('refundable_vat', vat_gap, 'asset/receivable/refundable_vat'),
      ('purchase', sale_gap, 'expense'),
      ('supplier', customer_gap, 'liability/payable'),
      ('bank', bank_gap, 'asset/cash/bank'),
      )
  # (line_id, source_account_id, destination_account_id, line_quantity)
  transaction_line_definition_list = (
      ('income', 'sale', 'purchase', 1.0),
      ('receivable', 'customer', 'supplier', -1.0 - vat_rate),
      ('collected_vat', 'receivable_vat', 'refundable_vat', vat_rate),
      )

  def getTitle(self):
    return "Invoices"

  def getBusinessTemplateList(self):
85
    return super(TestInvoiceMixin, self).getBusinessTemplateList() + (
86 87 88
      'erp5_accounting', 'erp5_invoicing', 'erp5_simplified_invoicing',
      'erp5_configurator_standard_accounting_template',
      'erp5_configurator_standard_invoicing_template')
89 90 91 92

  @UnrestrictedMethod
  def createCategories(self):
    """Create the categories for our test. """
93 94
    # pull in the TestOrderMixin categories first
    super(TestInvoiceMixin, self).createCategories()
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
    for cat_string in self.getNeededCategoryList() :
      base_cat = cat_string.split("/")[0]
      path = self.getPortal().portal_categories[base_cat]
      for cat in cat_string.split("/")[1:] :
        if not cat in path.objectIds() :
          path = path.newContent(
                    portal_type='Category',
                    id=cat,)
        else:
          path = path[cat]
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)

  def getNeededCategoryList(self):
    """return a list of categories that should be created."""
    return ('region/%s' % self.default_region,
            'gap/%s' % self.vat_gap,
            'gap/%s' % self.sale_gap,
            'gap/%s' % self.customer_gap,
            'gap/%s' % self.bank_gap,
            'delivery_mode/%s' % self.mail_delivery_mode,
            'incoterm/%s' % self.cpt_incoterm,
            'quantity_unit/%s' % self.unit_piece_quantity_unit,
            'quantity_unit/%s' % self.mass_quantity_unit,
122 123 124 125
            'base_amount/tax1',
            'base_amount/tax2',
            'base_amount/tax3',
            'use/trade/tax',
126 127 128
        )

  def afterSetUp(self):
129 130 131 132
    self.createUser('test_user',
                    ['Assignee', 'Assignor', 'Member',
                     'Associate', 'Auditor', 'Author'])
    self.createUser('manager', ['Manager'])
133
    self.loginByUserName('manager')
134 135
    self.createCategories()
    self.validateRules()
136
    self.createBusinessProcess()
137
    self.loginByUserName('test_user')
138 139

  def beforeTearDown(self):
140
    self.abort()
141
    self.loginByUserName('manager')
142
    super(TestInvoiceMixin, self).beforeTearDown()
143 144 145 146 147 148 149 150 151 152
    for folder in (self.portal.accounting_module,
                   self.portal.organisation_module,
                   self.portal.sale_order_module,
                   self.portal.purchase_order_module,
                   self.portal.sale_packing_list_module,
                   self.portal.purchase_packing_list_module,
                   self.portal.portal_simulation,):
      folder.manage_delObjects([x for x in folder.objectIds() if x not in ('organisation_1','organisation_2','ppl_1','ppl_2')])
    self.tic()

153 154 155
  def stepCreateSaleInvoiceTransactionRule(self, sequence, **kw) :
    pass # see createBusinessProcess

156 157 158 159 160
  ## XXX move this to "Sequence class"
  def playSequence(self, sequence_string, quiet=0) :
    sequence_list = SequenceList()
    sequence_list.addSequenceString(sequence_string)
    sequence_list.play(self, quiet=quiet)
161

162
  def createBusinessProcess(self):
163
    portal = self.portal
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
    business_process_id = self.__class__.__name__
    try:
      business_process = portal.business_process_module[business_process_id]
    except KeyError:
      business_process = portal.business_process_module.newContent(
        business_process_id, 'Business Process',
        specialise=self.__class__.business_process)
      kw = dict(portal_type='Trade Model Path',
                trade_phase='default/accounting',
                trade_date='trade_phase/default/invoicing',
                membership_criterion_base_category_list=('destination_region',
                                                         'product_line'),
                membership_criterion_category=(
                  'destination_region/region/' + self.default_region,
                  'product_line/apparel'))
      account_module = portal.account_module
      for account_id, account_gap, account_type in self.account_definition_list:
        if not account_module.has_key(account_id):
          account = account_module.newContent(account_id, gap=account_gap,
                                              account_type=account_type)
184
          account.validate()
185 186
      for line_id, line_source_id, line_destination_id, line_ratio in \
          self.transaction_line_definition_list:
187
        trade_model_path = business_process.newContent(
188 189
          reference='accounting_' + line_id,
          efficiency=line_ratio,
190
          source_value=account_module[line_source_id],
191 192
          destination_value=account_module[line_destination_id],
          **kw)
193 194 195 196 197
        # A trade model path already exist for root simulation movements
        # (Accounting Transaction Root Simulation Rule).
        # The ones we are creating are for Invoice Transaction Simulation Rule.
        trade_model_path._setCriterionPropertyList(('portal_type',))
        trade_model_path.setCriterion('portal_type', 'Simulation Movement')
198
    self.business_process = business_process.getRelativeUrl()
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

  def stepCreateEntities(self, sequence, **kw) :
    """Create a vendor and two clients. """
    self.stepCreateOrganisation1(sequence, **kw)
    self.stepCreateOrganisation2(sequence, **kw)
    self.stepCreateOrganisation3(sequence, **kw)
    self.stepCreateProject1(sequence, **kw)
    self.stepCreateProject2(sequence, **kw)
    vendor = sequence.get('organisation1')
    vendor.setRegion(self.default_region)
    vendor.validate()
    sequence.edit(vendor=vendor)
    client1 = sequence.get('organisation2')
    client1.setRegion(self.default_region)
    self.assertNotEquals(client1.getRegionValue(), None)
    client1.validate()
    sequence.edit(client1=client1)
    client2 = sequence.get('organisation3')
217
    self.assertEqual(client2.getRegionValue(), None)
218 219 220 221 222 223 224 225 226 227 228 229 230
    client2.validate()
    sequence.edit(client2=client2)

  def stepCheckOrderRule(self, sequence=None, sequence_list=None, **kw):
    """Check we have a related Order Rule"""
    order = sequence.get('order')
    simulation_tool = self.getSimulationTool()
    # Check that there is an applied rule for our packing list
    rule_list = [x for x in simulation_tool.objectValues()
                            if x.getCausalityValue()==order]
    self.assertNotEquals(len(rule_list), 0)
    sequence.edit(order_rule_list = rule_list)

231
    self.assertEqual(len(order.getMovementList()),
232 233 234 235 236 237 238 239 240 241 242 243 244
                  sum([len(rule.objectIds()) for rule in rule_list]))

  def stepCheckInvoicingRule(self, sequence=None, sequence_list=None, **kw):
    """
    Checks that the invoicing rule is applied and its values are correct.
    """
    order_rule_list = sequence.get('order_rule_list')
    invoicing_rule_list = []
    invoice_transaction_rule_list = []
    for order_rule in order_rule_list :
      for order_simulation_movement in order_rule.objectValues() :
        temp_invoicing_rule_list = [ar for ar in order_simulation_movement.objectValues()[0].objectValues()[0].objectValues()
          if ar.getSpecialiseValue().getPortalType() == 'Invoice Simulation Rule']
245
        self.assertEqual(len(temp_invoicing_rule_list), 1)
246 247 248 249 250
        invoicing_rule_list.extend(temp_invoicing_rule_list)
    sequence.edit(invoicing_rule_list=invoicing_rule_list)
    invoicing_rule = invoicing_rule_list[0]
    sequence.edit(invoicing_rule = invoicing_rule)
    for invoicing_rule in invoicing_rule_list:
251
      self.assertEqual(invoicing_rule.getSpecialiseReference(),
252
          'default_invoicing_rule')
253
      self.assertEqual(invoicing_rule.getPortalType(),
254 255 256 257 258 259 260 261 262
          'Applied Rule')
      simulation_movement_list = invoicing_rule.objectValues()
      self.assertNotEquals(len(simulation_movement_list), 0)
      for simulation_movement in simulation_movement_list :
        invoice_transaction_rule_list.extend([applied_rule for applied_rule
          in simulation_movement.objectValues() if applied_rule \
              .getSpecialiseValue().getPortalType()
              == 'Invoice Transaction Simulation Rule'])
        resource_list = sequence.get('resource_list')
263
        self.assertEqual(simulation_movement.getPortalType(),
264 265 266 267 268 269
                          'Simulation Movement')
        self.assertTrue(simulation_movement.getResourceValue() in
            resource_list)
        self.assertTrue(simulation_movement.isConvergent())
        # TODO: What is the invoice dates supposed to be ?
        # is this done through profiles ?
270
        #self.assertEqual(simulation_movement.getStartDate(),
271
        #           sequence.get('order').getStartDate())
272
        #self.assertEqual(simulation_movement.getStopDate(),
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        #            sequence.get('order').getStopDate())
    sequence.edit(invoice_transaction_rule_list=invoice_transaction_rule_list)

  def stepCheckInvoiceTransactionRule(self, sequence=None, sequence_list=None,
      **kw):
    """
    Checks that the applied invoice_transaction_rule is expanded and its movements are
    consistent with its parent movement
    """
    invoice_transaction_rule_list = \
        sequence.get('invoice_transaction_rule_list')
    for applied_invoice_transaction_rule in invoice_transaction_rule_list:
      parent_movement = aq_parent(applied_invoice_transaction_rule)
      invoice_transaction_rule = \
        applied_invoice_transaction_rule.getSpecialiseValue()
288
      self.assertEqual(3, len(applied_invoice_transaction_rule.objectValues()))
289 290 291 292 293 294 295 296 297 298 299
      for line_id, line_source_id, line_destination_id, line_ratio in \
                                            self.transaction_line_definition_list:
        movement = None
        for simulation_movement in \
                applied_invoice_transaction_rule.objectValues():
          if simulation_movement.getSourceId() == line_source_id and\
              simulation_movement.getDestinationId() == line_destination_id:
            movement = simulation_movement
            break

        self.assertTrue(movement is not None)
300
        self.assertEqual(movement.getCorrectedQuantity(), parent_movement.getPrice() *
301
            parent_movement.getCorrectedQuantity() * line_ratio)
302
        self.assertEqual(movement.getStartDate(),
303
            parent_movement.getStartDate())
304
        self.assertEqual(movement.getStopDate(),
305 306 307 308 309 310 311 312 313 314 315 316 317
            parent_movement.getStopDate())

  def modifyPackingListState(self, transition_name,
                             sequence,packing_list=None):
    """ calls the workflow for the packing list """
    if packing_list is None:
      packing_list = sequence.get('packing_list')
    packing_list.portal_workflow.doActionFor(packing_list, transition_name)

  def stepSetReadyPackingList(self, sequence=None, sequence_list=None, **kw):
    """ set the Packing List as Ready. This must build the invoice. """
    self.modifyPackingListState('set_ready_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
318
    self.assertEqual(packing_list.getSimulationState(), 'ready')
319 320 321 322 323 324 325

  def stepSetReadyNewPackingList(self, sequence=None,
                                 sequence_list=None, **kw):
    """ set the Packing List as Ready. This must build the invoice. """
    packing_list = sequence.get('new_packing_list')
    self.modifyPackingListState('set_ready_action', sequence=sequence,
                                packing_list=packing_list)
326
    self.assertEqual(packing_list.getSimulationState(), 'ready')
327 328 329 330

  def stepStartPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('start_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
331
    self.assertEqual(packing_list.getSimulationState(), 'started')
332 333 334 335 336

  def stepStartNewPackingList(self, sequence=None, sequence_list=None, **kw):
    packing_list = sequence.get('new_packing_list')
    self.modifyPackingListState('start_action', sequence=sequence,
                                packing_list=packing_list)
337
    self.assertEqual(packing_list.getSimulationState(), 'started')
338 339 340 341

  def stepStopPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('stop_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
342
    self.assertEqual(packing_list.getSimulationState(), 'stopped')
343 344 345 346

  def stepDeliverPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('deliver_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
347
    self.assertEqual(packing_list.getSimulationState(), 'delivered')
348 349 350 351

  def stepCancelPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('cancel_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
352
    self.assertEqual(packing_list.getSimulationState(), 'cancelled')
353 354 355 356 357 358 359 360 361 362 363

  def modifyInvoiceState(self, transition_name,
                             sequence,invoice=None):
    """ calls the workflow for the invoice """
    if invoice is None:
      invoice = sequence.get('invoice')
    invoice.portal_workflow.doActionFor(invoice, transition_name)

  def stepStartInvoice(self, sequence=None, sequence_list=None, **kw):
    self.modifyInvoiceState('start_action', sequence=sequence)
    invoice = sequence.get('invoice')
364
    self.assertEqual(invoice.getSimulationState(), 'started')
365 366 367 368 369

  def stepStartNewInvoice(self, sequence=None, sequence_list=None, **kw):
    invoice = sequence.get('new_invoice')
    self.modifyInvoiceState('start_action', sequence=sequence,
                                invoice=invoice)
370
    self.assertEqual(invoice.getSimulationState(), 'started')
371 372 373 374

  def stepStopInvoice(self, sequence=None, sequence_list=None, **kw):
    self.modifyInvoiceState('stop_action', sequence=sequence)
    invoice = sequence.get('invoice')
375
    self.assertEqual(invoice.getSimulationState(), 'stopped')
376 377 378 379

  def stepDeliverInvoice(self, sequence=None, sequence_list=None, **kw):
    self.modifyInvoiceState('deliver_action', sequence=sequence)
    invoice = sequence.get('invoice')
380
    self.assertEqual(invoice.getSimulationState(), 'delivered')
381 382 383 384

  def stepCancelInvoice(self, sequence=None, sequence_list=None, **kw):
    self.modifyInvoiceState('cancel_action', sequence=sequence)
    invoice = sequence.get('invoice')
385
    self.assertEqual(invoice.getSimulationState(), 'cancelled')
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415


  def stepSwitchPackingLists(self, sequence=None, sequence_list=None, **kw):
    packing_list = sequence.get('packing_list')
    new_packing_list = sequence.get('new_packing_list')
    #invoice = new_packing_list.getDefaultCausalityRelatedValue(
        #portal_type=self.invoice_portal_type)
    sequence.edit(packing_list=new_packing_list,
        new_packing_list=packing_list)#, invoice=invoice)

  def stepSwitchInvoices(self, sequence=None, sequence_list=None, **kw):
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
    sequence.edit(invoice=new_invoice, new_invoice=invoice)

  def stepCheckPackingListSimulation(self, sequence=None, sequence_list=None, **kw):
    """ checks that simulation movements related to the packing list are OK """
    packing_list = sequence.get('packing_list')
    order = sequence.get('order')
    order_root_applied_rule = order.getCausalityRelatedValueList(
                                  portal_type = 'Applied Rule')[0]
    # check simulation movements from this packing list
    for movement in packing_list.getMovementList() :
      simulation_movement_list = movement.getOrderRelatedValueList()
      self.assertNotEquals(len(simulation_movement_list), 0)
      total_quantity = 0
      for simulation_movement in simulation_movement_list :
        total_quantity += simulation_movement.getQuantity()
        # check that those movements come from the same root applied
        # rule than the order.
416
        self.assertEqual( simulation_movement.getRootAppliedRule(),
417
                           order_root_applied_rule)
418
      self.assertEqual(total_quantity, movement.getQuantity())
419 420 421 422 423 424 425

  def checkMirrorAcquisition(self, object, acquired_object):
    """
      Check if properties are well acquired for mirrored case
    """
    # packing_list_movement, simulation_movement

426 427 428
    self.assertEqual(acquired_object.getStartDate(), object.getStopDate())
    self.assertEqual(acquired_object.getStopDate(), object.getStartDate())
    self.assertEqual(acquired_object.getSourceValue(), \
429
                      object.getDestinationValue())
430
    self.assertEqual(acquired_object.getDestinationValue(), \
431 432
                      object.getSourceValue())

433
    self.assertEqual(acquired_object.getSourceSectionValue(), \
434
                      object.getDestinationSectionValue())
435
    self.assertEqual(acquired_object.getDestinationSectionValue(), \
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
                      object.getSourceSectionValue())

  def stepCheckInvoiceBuilding(self, sequence=None, sequence_list=None, **kw):
    """
    checks that the invoice is built with the default_invoice_builder
    """
    packing_list = sequence.get('packing_list')
    related_invoice_list = packing_list.getCausalityRelatedValueList(
                     portal_type=self.invoice_portal_type)

    if packing_list.getPortalType() == 'Purchase Packing List':
      packing_list_building_state = 'stopped'
    else:
      packing_list_building_state = 'started'
    packing_list_state = packing_list.getSimulationState()
    if packing_list_state != packing_list_building_state :
452
      self.assertEqual(0, len(related_invoice_list))
453
    else:
454
      self.assertEqual(1, len(related_invoice_list))
455 456

      invoice = related_invoice_list[0].getObject()
457
      self.assertTrue(invoice is not None)
458
      # Invoices created by Delivery Builder are in confirmed state
459
      self.assertEqual(invoice.getSimulationState(), 'confirmed')
460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

      # Get the list of simulation movements of packing list ...
      packing_list_simulation_movement_list = []
      for packing_list_movement in packing_list.getMovementList():
           packing_list_simulation_movement_list.extend(
                packing_list_movement.getDeliveryRelatedValueList())
      # ... invoice simulation movement are their childrens.
      simulation_movement_list = []
      for p_l_simulation_movement in packing_list_simulation_movement_list :
        for applied_rule in p_l_simulation_movement.objectValues() :
          simulation_movement_list.extend(applied_rule.objectValues())

      # First, test if each Simulation Movement is related to an
      # Invoice Movement
      invoice_relative_url = invoice.getRelativeUrl()
      for simulation_movement in simulation_movement_list:
        invoice_movement_list = simulation_movement.getDeliveryValueList()
477
        self.assertEqual(len(invoice_movement_list), 1)
478
        invoice_movement = invoice_movement_list[0]
479
        self.assertTrue(invoice_movement is not None)
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
        self.assert_(invoice_movement.getRelativeUrl().\
                              startswith(invoice_relative_url))

      # Then, test if each Invoice movement is equals to the sum of somes
      # Simulation Movements
      for invoice_movement in invoice.getMovementList(portal_type = [
                          self.invoice_cell_portal_type,
                          self.invoice_line_portal_type]) :
        related_simulation_movement_list = invoice_movement.\
                 getDeliveryRelatedValueList(portal_type='Simulation Movement')
        quantity = 0
        total_price = 0
        invoice_movement_quantity = invoice_movement.getQuantity()
        for related_simulation_movement in related_simulation_movement_list:
          quantity += related_simulation_movement.getQuantity()
          total_price += related_simulation_movement.getPrice() *\
                         related_simulation_movement.getQuantity()
          # Test resource
498
          self.assertEqual(invoice_movement.getResource(), \
499 500
                            related_simulation_movement.getResource())
          # Test resource variation
501
          self.assertEqual(invoice_movement.getVariationText(), \
502
                            related_simulation_movement.getVariationText())
503
          self.assertEqual(invoice_movement.getVariationCategoryList(), \
504 505 506 507 508
                        related_simulation_movement.getVariationCategoryList())
          # Test acquisition
          self.checkAcquisition(invoice_movement,
                                related_simulation_movement)
          # Test delivery ratio
509
          self.assertEqual(related_simulation_movement.getQuantity() /\
510 511 512
                            invoice_movement_quantity, \
                            related_simulation_movement.getDeliveryRatio())

513
        self.assertEqual(quantity, invoice_movement.getQuantity())
514
        # Test price
515
        self.assertEqual(total_price / quantity, invoice_movement.getPrice())
516 517 518 519

      sequence.edit(invoice = invoice)

      # Test causality
520
      self.assertEqual(len(invoice.getCausalityValueList(
521
                      portal_type = self.packing_list_portal_type)), 1)
522
      self.assertEqual(invoice.getCausalityValue(), packing_list)
523 524

      # Finally, test getTotalQuantity and getTotalPrice on Invoice
525
      self.assertEqual(packing_list.getTotalQuantity(),
526
                        invoice.getTotalQuantity())
527
      self.assertEqual(packing_list.getTotalPrice(),
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546
                        invoice.getTotalPrice())

  def stepCheckInvoicesConsistency(self, sequence=None, sequence_list=None,
      **kw):
    """
    Checks that all invoices are consistent:
    - transaction lines match invoice lines
    - no movement is divergent
    """
    invoice_list = self.getPortal()['accounting_module'].objectValues()
    for invoice in invoice_list:
      accounting_state_list = \
          list(self.getPortal().getPortalCurrentInventoryStateList())
      accounting_state_list.append('cancelled')
      if invoice.getSimulationState() in accounting_state_list:
        invoice_line_list = invoice.contentValues(
            portal_type=self.invoice_line_portal_type)
        invoice_transaction_line_list = invoice.contentValues(
            portal_type=self.invoice_transaction_line_portal_type)
547
        self.assertEqual(3, len(invoice_transaction_line_list))
548 549 550 551 552 553 554 555 556 557 558 559 560
        expected_price = 0.0
        for line in invoice_line_list:
          expected_price += line.getTotalPrice()
        for line_id, line_source, line_dest, line_ratio in \
            self.transaction_line_definition_list:
          for line in invoice.contentValues(
              portal_type=self.invoice_transaction_line_portal_type):
            if line.getSource() == 'account_module/%s' % line_source and \
                line.getDestination() == 'account_module/%s' % line_dest:
              break
          else:
            self.fail('No line found that matches %s' % line_id)
          resource_precision = line.getResourceValue().getQuantityPrecision()
561
          self.assertEqual(round(line.getQuantity(), resource_precision),
562 563 564 565 566 567 568 569 570
              round(expected_price * line_ratio, resource_precision))

  def stepCheckInvoiceLineHasReferenceAndIntIndex(self, sequence=None, **kw):
    """Check that the unique invoice line in the invoice has reference and int
    index.
    """
    invoice = sequence.get('invoice')
    invoice_line_list = invoice.contentValues(
                            portal_type=self.invoice_line_portal_type)
571
    self.assertEqual(1, len(invoice_line_list))
572
    invoice_line = invoice_line_list[0]
573 574
    self.assertEqual(1, invoice_line.getIntIndex())
    self.assertEqual('1', invoice_line.getReference())
575 576 577 578 579 580 581 582

  def stepCheckPackingListInvoice(
                      self, sequence=None, sequence_list=None, **kw):
    """ Checks if the delivery builder is working as expected,
        coping the atributes from packing list to invoice."""
    packing_list = sequence.get('packing_list')
    related_invoice_list = packing_list.getCausalityRelatedValueList(
                     portal_type=self.invoice_portal_type)
583
    self.assertEqual(len(related_invoice_list), 1)
584
    invoice = related_invoice_list[0]
585 586 587
    self.assertEqual(packing_list.getSource(), invoice.getSource())
    self.assertEqual(packing_list.getDestination(), invoice.getDestination())
    self.assertEqual(packing_list.getDestinationSection(), \
588
                                       invoice.getDestinationSection())
589
    self.assertEqual(packing_list.getSourceSection(), \
590
                                       invoice.getSourceSection())
591
    self.assertEqual(packing_list.getDestinationDecision(), \
592
                                       invoice.getDestinationDecision())
593
    self.assertEqual(packing_list.getSourceDecision(), \
594
                                       invoice.getSourceDecision())
595
    self.assertEqual(packing_list.getDestinationAdministration(), \
596
                                       invoice.getDestinationAdministration())
597
    self.assertEqual(packing_list.getSourceAdministration(), \
598
                                       invoice.getSourceAdministration())
599
    self.assertEqual(packing_list.getDestinationProject(), \
600
                                       invoice.getDestinationProject())
601
    self.assertEqual(packing_list.getSourceProject(), \
602
                                       invoice.getSourceProject())
603
    self.assertEqual(packing_list.getPriceCurrency(), \
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
                                       invoice.getPriceCurrency())



  def stepCheckDeliveryRuleForDeferred(
                      self, sequence=None, sequence_list=None, **kw):
    """ Checks that a delivery rule has been created when we took 'split
        and defer' decision on the divergeant Packing List. """
    # TODO

  def stepCheckDeliveryRuleIsEmpty(
                      self, sequence=None, sequence_list=None, **kw):
    """ Checks that an empty delivery rule is created for the
        convergeant Packing List"""
    packing_list = sequence.get('packing_list')
619
    self.assertTrue(packing_list is not None)
620 621 622 623
    simulation_tool = self.getSimulationTool()
    # Check that there is an applied rule for our packing list
    rule_list = [x for x in simulation_tool.objectValues()
                          if x.getCausalityValue()==packing_list]
624
    self.assertEqual(len(rule_list),1)
625 626 627 628
    packing_list_rule = rule_list[0]
    sequence.edit(packing_list_rule=packing_list_rule)
    rule_line_list = packing_list_rule.objectValues()
    packing_list_line_list = packing_list.objectValues()
629
    self.assertEqual(len(packing_list_line_list),
630
                      len(rule_line_list))
631
    self.assertEqual(1, len(rule_line_list))
632 633
    rule_line = rule_line_list[0]
    packing_list_line = packing_list_line_list[0]
634 635 636
    self.assertEqual(rule_line.getQuantity(), 10)
    self.assertEqual(rule_line.getPrice(), 100)
    self.assertEqual(rule_line.getDeliveryValue(),
637
                      packing_list_line)
638
    self.assertEqual(rule_line.getStartDate(),
639
                      packing_list_line.getStartDate())
640
    self.assertEqual(rule_line.getStopDate(),
641
                      packing_list_line.getStopDate())
642
    self.assertEqual(rule_line.getPortalType(),
643 644 645 646 647 648 649 650 651 652 653 654
                      'Simulation Movement')


  def stepCheckPackingList(self,sequence=None, sequence_list=None,**kw):
    """  """
    packing_list_module = self.getSalePackingListModule()
    order_rule = sequence.get('order_rule')
    order = sequence.get('order')
    sale_packing_list_list = []
    for o in packing_list_module.objectValues():
      if o.getCausalityValue() == order:
        sale_packing_list_list.append(o)
655
    self.assertEqual(len(sale_packing_list_list), 1)
656 657
    sale_packing_list = sale_packing_list_list[0]
    sale_packing_list_line_list = sale_packing_list.objectValues()
658
    self.assertEqual(len(sale_packing_list_line_list),1)
659 660
    sale_packing_list_line = sale_packing_list_line_list[0]
    product = sequence.get('resource')
661
    self.assertEqual(sale_packing_list_line.getResourceValue(),
662
                      product)
663
    self.assertEqual(sale_packing_list_line.getPrice(),
664 665 666
                      self.price1)
    LOG('sale_packing_list_line.showDict()',0,
          sale_packing_list_line.showDict())
667
    self.assertEqual(sale_packing_list_line.getQuantity(),
668
                      self.quantity1)
669
    self.assertEqual(sale_packing_list_line.getTotalPrice(),
670 671 672 673 674 675
                      self.total_price1)
    sequence.edit(packing_list = sale_packing_list)

  def stepCheckTwoInvoices(self,sequence=None, sequence_list=None, **kw):
    """ checks invoice properties are well set. """
    # Now we will check that we have two invoices created
676 677 678 679 680 681
    for x in '', 'new_':
      packing_list = sequence.get(x + 'packing_list')
      invoice, = packing_list.getCausalityRelatedValueList(
          portal_type=self.invoice_portal_type)
      self.assertEqual(invoice.getSimulationState(), 'confirmed')
      sequence.set(x + 'invoice', invoice)
682 683 684 685 686 687 688 689 690 691 692 693 694 695

  def stepStartTwoInvoices(self,sequence=None, sequence_list=None, **kw):
    """ start both invoices. """
    portal = self.getPortal()
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
    portal.portal_workflow.doActionFor(invoice, 'start_action')
    portal.portal_workflow.doActionFor(new_invoice, 'start_action')

  def stepCheckTwoInvoicesTransactionLines(self,sequence=None,
                                           sequence_list=None, **kw):
    """ checks invoice properties are well set. """
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
696
    self.assertEqual(3,len(invoice.objectValues(
697
        portal_type=self.invoice_transaction_line_portal_type)))
698
    self.assertEqual(3,len(new_invoice.objectValues(
699
        portal_type=self.invoice_transaction_line_portal_type)))
700
    account_module = self.portal.account_module
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
    found_dict = {}
    for line in invoice.objectValues(
        portal_type=self.invoice_transaction_line_portal_type):
      source_id = line.getSourceId()
      found_dict[source_id] = line.getQuantity()
    total_price = (self.default_quantity-1) * self.default_price
    expected_dict = {
      'sale' : total_price,
      'receivable_vat' : total_price * self.vat_rate,
      'customer' : - (total_price + total_price * self.vat_rate)
      }
    self.failIfDifferentSet(expected_dict.keys(),found_dict.keys())
    for key in found_dict.keys():
      self.assertAlmostEquals(expected_dict[key],found_dict[key],places=2)
    found_dict = {}
    for line in new_invoice.objectValues(
        portal_type=self.invoice_transaction_line_portal_type):
      source_id = line.getSourceId()
      found_dict[source_id] = line.getQuantity()
    total_price = 1 * self.default_price
    expected_dict = {
      'sale' : total_price,
      'receivable_vat' : total_price * self.vat_rate,
      'customer' : - (total_price + total_price * self.vat_rate)
      }
    self.failIfDifferentSet(expected_dict.keys(), found_dict.keys())
    for key in found_dict.keys():
      self.assertAlmostEquals(expected_dict[key], found_dict[key], places=2)

  def stepRebuildAndCheckNothingIsCreated(self, sequence=None,
                                           sequence_list=None, **kw):
    """Rebuilds with sale_invoice_builder and checks nothing more is
    created. """
734
    accounting_module = self.portal.accounting_module
735 736 737 738 739
    portal_type_list = ('Sale Invoice Transaction', 'Purchase Invoice Transaction')
    sale_invoice_transaction_count = len(accounting_module.objectValues(
      portal_type=portal_type_list))
    for builder in self.getPortal().portal_deliveries.objectValues():
      builder.build()
740
    self.assertEqual(sale_invoice_transaction_count,
741 742 743 744 745 746 747 748 749 750 751 752 753 754
                      len(accounting_module.objectValues(
      portal_type=portal_type_list)))

  def stepModifyInvoicesDate(self, sequence=None,
                                           sequence_list=None, **kw):
    """Change invoice date"""
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
    invoice.edit(start_date=self.datetime,
                 stop_date=self.datetime+1)
    new_invoice.edit(start_date=self.datetime,
                 stop_date=self.datetime+1)

  def stepEditInvoice(self, sequence=None, sequence_list=None, **kw):
755
    """Edit the current invoice, to trigger updateSimulation."""
756
    invoice = sequence.get('invoice')
757
    invoice.edit(description='This invoice was edited!')
758 759 760 761 762 763

  def stepCheckInvoiceRuleNotAppliedOnInvoiceEdit(self,
                    sequence=None, sequence_list=None, **kw):
    """If we call edit on the invoice, invoice rule should not be
    applied on lines created by delivery builder."""
    invoice = sequence.get('invoice')
764
    self.assertEqual([], invoice.getCausalityRelatedValueList())
765 766

  def stepEditPackingList(self, sequence=None, sequence_list=None, **kw):
767
    """Edit the current packing list, to trigger updateSimulation."""
768
    packing_list = sequence.get('packing_list')
769
    packing_list.edit(description='This packing list was edited!')
770

771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  def stepAcceptDecisionDescriptionPackingList(self,sequence=None, sequence_list=None):
    packing_list = sequence.get('packing_list')
    self._solveDivergence(packing_list, 'description', 'Accept Solver')

  def stepAssertCausalityStateIsNotSolvedInConsistencyMessage(self,
                    sequence=None, sequence_list=None, **kw):
    packing_list = sequence.get('packing_list')
    self.assertEqual(
      ['Causality State is not "Solved". Please wait or take action'
        + ' for causality state to reach "Solved".'],
      [str(message.message) for message in packing_list.checkConsistency()])

  def stepSetReadyWorkflowTransitionIsBlockByConsistency(self,
                    sequence=None, sequence_list=None, **kw):
    packing_list = sequence.get('packing_list')
    with self.assertRaisesRegexp(ValidationFailed,
        '.*Causality State is not "Solved"*'):
      self.getPortal().portal_workflow.doActionFor(
        packing_list, 'set_ready_action')

791 792 793 794 795
  def stepCheckDeliveryRuleNotAppliedOnPackingListEdit(self,
                    sequence=None, sequence_list=None, **kw):
    """If we call edit on the packing list, delivery rule should not be
    applied on lines created by delivery builder."""
    packing_list = sequence.get('packing_list')
796
    self.assertEqual([], packing_list.getCausalityRelatedValueList())
797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852

  def stepDecreaseInvoiceLineQuantity(self, sequence=None, sequence_list=None,
      **kw):
    """
    Set a decreased quantity on invoice lines
    """
    invoice = sequence.get('invoice')
    quantity = sequence.get('line_quantity',default=self.default_quantity)
    quantity = quantity - 1
    sequence.edit(line_quantity=quantity)
    for invoice_line in invoice.objectValues(
        portal_type=self.invoice_line_portal_type):
      invoice_line.edit(quantity=quantity)
    sequence.edit(last_delta = sequence.get('last_delta', 0.0) - 1.0)

  def stepIncreaseInvoiceLineQuantity(self, sequence=None, sequence_list=None,
      **kw):
    """
    Set a Increased quantity on invoice lines
    """
    invoice = sequence.get('invoice')
    quantity = sequence.get('line_quantity',default=self.default_quantity)
    quantity = quantity + 1
    sequence.edit(line_quantity=quantity)
    for invoice_line in invoice.objectValues(
        portal_type=self.invoice_line_portal_type):
      invoice_line.edit(quantity=quantity)
    sequence.edit(last_delta = sequence.get('last_delta', 0.0) + 1.0)

  def stepSetInvoiceLineQuantityToZero(self, sequence=None, sequence_list=None,
      **kw):
    """
    Set the quantity on invoice lines to zero
    """
    invoice = sequence.get('invoice')
    #default_quantity = sequence.get('line_quantity',default_quantity)
    quantity = 0.0
    sequence.edit(line_quantity=quantity)
    for invoice_line in invoice.objectValues(
        portal_type=self.invoice_line_portal_type):
      invoice_line.edit(quantity=quantity)
    sequence.edit(last_delta = - self.default_quantity)

  def stepChangeInvoiceStartDate(self, sequence=None, sequence_list=None, **kw):
    """
      Change the start_date of the invoice.
    """
    invoice = sequence.get('invoice')
    invoice.edit(start_date=self.datetime + 15)

  def stepCheckInvoiceIsCalculating(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is calculating
    """
    invoice = sequence.get('invoice')
853
    self.assertEqual('calculating',invoice.getCausalityState())
854 855 856 857 858 859 860

  def stepCheckInvoiceIsDiverged(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is diverged
    """
    invoice = sequence.get('invoice')
861
    self.assertEqual('diverged',invoice.getCausalityState())
862 863 864 865 866 867 868

  def stepCheckInvoiceIsSolved(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is solved
    """
    invoice = sequence.get('invoice')
869
    self.assertEqual('solved', invoice.getCausalityState(),
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
                      invoice.getDivergenceList())

  def stepCheckInvoiceIsDivergent(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is divergent
    """
    invoice = sequence.get('invoice')
    self.assertTrue(invoice.isDivergent())

  def stepCheckInvoiceIsNotDivergent(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is not divergent
    """
    invoice = sequence.get('invoice')
    if invoice.isDivergent():
      self.fail(invoice.getDivergenceList())

  def stepSplitAndDeferInvoice(self, sequence=None, sequence_list=None,
      **kw):
    invoice = sequence.get('invoice')
892 893 894 895 896 897 898 899 900 901 902 903
    solver_process = self.portal.portal_solver_processes.newSolverProcess(invoice)
    quantity_solver_decision, = [x for x in solver_process.contentValues()
      if x.getCausalityValue().getTestedProperty() == 'quantity']
    # use Quantity Split Solver.
    quantity_solver_decision.setSolverValue(self.portal.portal_solvers['Quantity Split Solver'])
    # configure for Quantity Split Solver.
    kw = {'delivery_solver':'FIFO Delivery Solver',
          'start_date':self.datetime + 15,
          'stop_date':self.datetime + 25}
    quantity_solver_decision.updateConfiguration(**kw)
    solver_process.buildTargetSolverList()
    solver_process.solve()
904 905 906 907

  def stepUnifyStartDateWithDecisionInvoice(self, sequence=None,
                                            sequence_list=None):
    invoice = sequence.get('invoice')
908 909
    self._solveDivergence(invoice, 'start_date', 'Unify Solver',
                          value=invoice.getStartDate())
910

911 912 913 914
  def stepAdoptPrevisionQuantityInvoice(self,sequence=None, sequence_list=None):
    invoice = sequence.get('invoice')
    self._solveDivergence(invoice, 'quantity', 'Adopt Solver')

915 916
  def stepAcceptDecisionQuantityInvoice(self,sequence=None, sequence_list=None):
    invoice = sequence.get('invoice')
917
    self._solveDivergence(invoice, 'quantity', 'Accept Solver')
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933

  def stepAcceptDecisionInvoice(self, sequence=None, sequence_list=None,
      **kw):
    """
    accept decision at the invoice level
    """
    invoice = sequence.get('invoice')
    invoice.portal_workflow.doActionFor(invoice,'accept_decision_action')

  def stepCheckInvoiceSplitted(self, sequence=None, sequence_list=None, **kw):
    """
    Test if invoice was splitted
    """
    packing_list = sequence.get('packing_list')
    invoice_list = packing_list.getCausalityRelatedValueList(
        portal_type=self.invoice_portal_type)
934
    self.assertEqual(2,len(invoice_list))
935 936 937 938 939 940 941 942 943 944
    invoice1 = None
    invoice2 = None
    for invoice in invoice_list:
      if invoice.getUid() == sequence.get('invoice').getUid():
        invoice1 = invoice
      else:
        invoice2 = invoice
    sequence.edit(new_invoice=invoice2)
    for line in invoice1.objectValues(
          portal_type=self.invoice_line_portal_type):
945
      self.assertEqual(self.default_quantity-1,line.getQuantity())
946 947
    for line in invoice2.objectValues(
          portal_type=self.invoice_line_portal_type):
948
      self.assertEqual(1,line.getQuantity())
949 950 951 952 953 954 955 956

  def stepCheckInvoiceNotSplitted(self, sequence=None, sequence_list=None, **kw):
    """
    Test if invoice was not splitted
    """
    packing_list = sequence.get('packing_list')
    invoice_list = packing_list.getCausalityRelatedValueList(
        portal_type=self.invoice_portal_type)
957
    self.assertEqual(1,len(invoice_list))
958 959 960 961 962 963 964
    invoice1 = None
    for invoice in invoice_list:
      if invoice.getUid() == sequence.get('invoice').getUid():
        invoice1 = invoice
    last_delta = sequence.get('last_delta', 0.0)
    for line in invoice1.objectValues(
        portal_type=self.invoice_line_portal_type):
965
      self.assertEqual(self.default_quantity + last_delta,
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
          line.getQuantity())

  def stepAddInvoiceLines(self, sequence=None, sequence_list=[]):
    """
    add some invoice and accounting lines to the invoice
    """
    invoice = sequence.get('invoice')
    invoice.newContent(portal_type='Invoice Line',
        resource_value=sequence.get('resource'), quantity=3, price=555)
    invoice.newContent(portal_type='Sale Invoice Transaction Line',
        id ='receivable', source='account_module/customer',
        destination='account_module/supplier', quantity=-1665)
    invoice.newContent(portal_type='Sale Invoice Transaction Line',
        id='income', source='account_module/sale',
        destination='account_module/purchase', quantity=1665)

  def stepAddWrongInvoiceLines(self, sequence=None, sequence_list=[]):
    """
    add some wrong invoice and accounting lines to the invoice
    """
    invoice = sequence.get('invoice')
    invoice.newContent(portal_type='Sale Invoice Transaction Line',
        id='bad_movement', source='account_module/sale',
        destination='account_module/purchase', quantity=2, price=4)
    invoice.newContent(portal_type='Sale Invoice Transaction Line',
        id='counter_bad_movement', source='account_module/sale',
        destination='account_module/purchase', quantity=-2, price=4)
    for movement in invoice.getMovementList():
      movement.edit(resource_value=sequence.get('resource'))

  def stepCheckStartInvoiceFail(self, sequence=None, sequence_list=[]):
    """
    checks that it's not possible to start an invoice with really wrong
    lines
    """
    try:
      self.tic()
    except RuntimeError, exc:
      invoice = sequence.get('invoice')
      # check which activities are failing
      self.assertTrue(str(exc).startswith('tic is looping forever.'),
          '%s does not start with "tic is looping forever."' % str(exc))
1008 1009 1010
      msg_list = [('/'.join(x.object_path), x.method_id)
          for x in self.getActivityTool().getMessageList()]
      self.assertTrue((invoice.getPath(), '_localBuild') in msg_list, msg_list)
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
      # flush failing activities
      activity_tool = self.getActivityTool()
      activity_tool.manageClearActivities(keep=0)
    else:
      self.fail("Error: stepStartInvoice didn't fail, the builder script"
          + " InvoiceTransaction_postTransactionLineGeneration should have"
          + " complained that accounting movements use multiple resources")

  def stepCheckSimulationTrees(self, sequence=None, sequence_list=[]):
    """
    check that rules are created in the order we expect them
    """
    applied_rule_set = set()
    invoice = sequence.get('invoice')
    for movement in invoice.getMovementList():
      for sm in movement.getDeliveryRelatedValueList():
        applied_rule_set.add(sm.getRootAppliedRule())

    rule_dict = {
        'Order Root Simulation Rule': {
          'movement_type_list': ['Sale Order Line', 'Sale Order Cell'],
          'next_rule_list': ['Delivery Simulation Rule', ],
          },
        'Delivery Simulation Rule': {
          'movement_type_list': ['Sale Packing List Line', 'Sale Packing List Cell'],
          'next_rule_list': ['Invoice Simulation Rule', ],
          },
        'Invoice Simulation Rule': {
          'movement_type_list': invoice.getPortalInvoiceMovementTypeList(),
          'next_rule_list': ['Invoice Transaction Simulation Rule', 'Trade Model Simulation Rule'],
          },
        'Trade Model Simulation Rule': {
          'next_rule_list': ['Invoice Transaction Simulation Rule'],
          },
        'Invoice Simulation Rule': {
          'movement_type_list': invoice.getPortalInvoiceMovementTypeList() \
              + invoice.getPortalAccountingMovementTypeList(),
          'next_rule_list': ['Invoice Transaction Simulation Rule', 'Payment Simulation Rule',
            'Trade Model Simulation Rule'],
          },
        'Invoice Transaction Simulation Rule': {
          'parent_movement_type_list': invoice.getPortalInvoiceMovementTypeList(),
          'movement_type_list': invoice.getPortalAccountingMovementTypeList(),
          'next_rule_list': ['Payment Simulation Rule'],
          },
        'Payment Simulation Rule': {
          'parent_movement_type_list': invoice.getPortalAccountingMovementTypeList(),
          'next_rule_list': [],
          },
        }

    def checkTree(rule):
      """
      checks the tree recursively
      """
      rule_type = rule.getSpecialiseValue().getPortalType()
      rule_def = rule_dict.get(rule_type, {})
      for k, v in rule_def.iteritems():
        if k == 'movement_type_list':
          for movement in rule.objectValues():
            if movement.getDeliveryValue() is not None:
              self.assertTrue(movement.getDeliveryValue().getPortalType() in v,
                  'looking for %s in %s on %s' % (
                  movement.getDeliveryValue().getPortalType(), v,
                  movement.getPath()))
        elif k == 'next_rule_list':
          for movement in rule.objectValues():
            found_rule_dict = {}
            for next_rule in movement.objectValues():
              next_rule_type = next_rule.getSpecialiseValue().getPortalType()
              self.assertTrue(next_rule_type in v,
                  'looking for %s in %s on %s' % (
                  next_rule_type, v, next_rule.getPath()))
              n = found_rule_dict.get(next_rule_type, 0)
              found_rule_dict[next_rule_type] = n + 1
            # for each movement, we want to make sure that each rule is not
            # instanciated more than once
            if len(found_rule_dict):
1089
              self.assertEqual(set(found_rule_dict.itervalues()), {1})
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
        elif k == 'parent_movement_type_list':
          if rule.getParentValue().getDeliveryValue() is not None:
            parent_type = rule.getParentValue().getDeliveryValue().getPortalType()
            self.assertTrue(parent_type in v, 'looking for %s in %s on %s' % (
                parent_type, v, rule.getParentValue().getPath()))
        elif k == 'parent_id_list':
          self.assertTrue(rule.getParentId() in v, 'looking for %s in %s on %s'
              % (rule.getParentId(), v, rule.getPath()))
      for movement in rule.objectValues():
        for next_rule in movement.objectValues():
          checkTree(next_rule)

    for applied_rule in applied_rule_set:
      checkTree(applied_rule)

  def stepAddInvoiceLinesManyTransactions(self, sequence=None, sequence_list=[]):
    """
    add some invoice and accounting lines to the invoice
    """
    invoice = sequence.get('invoice')
    invoice_line = invoice.newContent(portal_type='Invoice Line')
    transaction_line_1 = invoice.newContent(portal_type='Sale Invoice Transaction Line')
    transaction_line_2 = invoice.newContent(portal_type='Sale Invoice Transaction Line')
    self.tic()
    invoice_line.edit(resource_value=sequence.get('resource'), quantity=3,
        price=555)
    transaction_line_1.edit(id ='receivable', source='account_module/customer',
        destination='account_module/supplier', quantity=-1665)
    transaction_line_2.edit(
        id='income', source='account_module/sale',
        destination='account_module/purchase', quantity=1665)

1122 1123 1124 1125
  def stepInvoiceBuilderAlarm(self, sequence=None,
                                  sequence_list=None, **kw):
    self.portal.portal_alarms.invoice_builder_alarm.activeSense()

1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156
class TestInvoice(TestInvoiceMixin):
  """Test methods for sale and purchase invoice.
  Subclasses must defines portal types to use.
  """
  quiet = 1
  def test_invoice_transaction_line_resource(self):
    """
    tests that simulation movements corresponding to accounting line have a
    good resource in the simulation
    """
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    product_line='apparel')
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency',
                                base_unit_quantity=0.01)
    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client',
                            price_currency= currency.getRelativeUrl(),
                            default_address_region=self.default_region)
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor',
                            price_currency= currency.getRelativeUrl(),
                            default_address_region=self.default_region)
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
1157
                              specialise=self.business_process,
1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')
    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                                  quantity=1,
                                  price=2)

    order.confirm()
    self.tic()
1172 1173
    self.stepPackingListBuilderAlarm()
    self.tic()
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184

    related_applied_rule = order.getCausalityRelatedValue(
                             portal_type='Applied Rule')
    order_movement = related_applied_rule.contentValues()[0]
    delivery_applied_rule = order_movement.contentValues()[0]
    delivery_movement = delivery_applied_rule.contentValues()[0]
    invoice_applied_rule = delivery_movement.contentValues()[0]
    invoice_movement = invoice_applied_rule.contentValues()[0]
    invoice_transaction_applied_rule = invoice_movement.contentValues()[0]
    invoice_transaction_movement =\
         invoice_transaction_applied_rule.contentValues()[0]
1185
    self.assertEqual(currency,
1186
          invoice_transaction_movement.getResourceValue())
1187
    self.assertEqual(currency,
1188 1189
          delivery_movement.getPriceCurrencyValue())

1190
  @newSimulationExpectedFailure
1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
  def test_modify_planned_order_invoicing_rule(self):
    """
    tests that modifying a planned order affects movements from invoicing
    rule
    """
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    product_line='apparel')
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency',
                                base_unit_quantity=0.01)

    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client',
                            price_currency= currency.getRelativeUrl())
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor',
                            price_currency= currency.getRelativeUrl())
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
1216
                              specialise=self.business_process,
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')
    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                                  quantity=1,
                                  price=2)

    other_entity = self.portal.organisation_module.newContent(
                                    portal_type='Organisation',
                                    title='Other Entity',
                                    price_currency=currency.getRelativeUrl())
    other_project = self.portal.project_module.newContent(
                                    portal_type='Project',
                                    title='Other Project')
    order.plan()
    self.tic()
1238
    self.assertEqual('planned', order.getSimulationState())
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248

    related_applied_rule = order.getCausalityRelatedValue(
                             portal_type='Applied Rule')
    delivery_movement = related_applied_rule.contentValues()[0]
    invoice_applied_rule = delivery_movement.contentValues()[0]
    invoice_movement = invoice_applied_rule.contentValues()[0]

    order_line.setSourceValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1249
    self.assertEqual(other_entity,
1250 1251 1252 1253 1254
                      invoice_movement.getSourceValue())

    order_line.setDestinationValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1255
    self.assertEqual(other_entity,
1256 1257 1258 1259 1260
                      invoice_movement.getDestinationValue())

    order_line.setSourceSectionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1261
    self.assertEqual(other_entity,
1262 1263 1264 1265 1266 1267 1268 1269 1270
                      invoice_movement.getSourceSectionValue())

    # make sure destination_section != source_section, this might be needed by
    # some rules
    order_line.setSourceSectionValue(order_line.getDestinationSectionValue())

    order_line.setDestinationSectionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1271
    self.assertEqual(other_entity,
1272 1273 1274 1275 1276
                 invoice_movement.getDestinationSectionValue())

    order_line.setSourceAdministrationValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1277
    self.assertEqual(other_entity,
1278 1279 1280 1281 1282
                 invoice_movement.getSourceAdministrationValue())

    order_line.setDestinationAdministrationValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1283
    self.assertEqual(other_entity,
1284 1285 1286 1287 1288
            invoice_movement.getDestinationAdministrationValue())

    order_line.setSourceDecisionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1289
    self.assertEqual(other_entity,
1290 1291 1292 1293 1294
                 invoice_movement.getSourceDecisionValue())

    order_line.setDestinationDecisionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1295
    self.assertEqual(other_entity,
1296 1297 1298 1299 1300
            invoice_movement.getDestinationDecisionValue())

    order_line.setSourceProjectValue(other_project)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1301
    self.assertEqual(other_project,
1302 1303 1304 1305 1306
                 invoice_movement.getSourceProjectValue())

    order_line.setDestinationProjectValue(other_project)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1307
    self.assertEqual(other_project,
1308 1309 1310 1311 1312
            invoice_movement.getDestinationProjectValue())

    order_line.setSourcePaymentValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1313
    self.assertEqual(other_entity,
1314 1315 1316 1317 1318
                 invoice_movement.getSourcePaymentValue())

    order_line.setDestinationPaymentValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1319
    self.assertEqual(other_entity,
1320 1321 1322 1323 1324
            invoice_movement.getDestinationPaymentValue())

    order_line.setSourceFunctionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1325
    self.assertEqual(other_entity,
1326 1327 1328 1329 1330
                 invoice_movement.getSourceFunctionValue())

    order_line.setDestinationFunctionValue(other_entity)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1331
    self.assertEqual(other_entity,
1332 1333 1334 1335 1336 1337
            invoice_movement.getDestinationFunctionValue())

    self.assertNotEquals(123, order_line.getPrice())
    order_line.setPrice(123)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1338
    self.assertEqual(123,
1339 1340 1341 1342 1343 1344
            invoice_movement.getPrice())

    self.assertNotEquals(456, order_line.getQuantity())
    order_line.setQuantity(456)
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1345
    self.assertEqual(456,
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
            invoice_movement.getQuantity())

    other_resource = self.portal.product_module.newContent(
                                        portal_type='Product',
                                        title='Other Resource')
    order_line.setResourceValue(other_resource)
    self.tic()
    # after changing 'resource', related simulation movement will be
    # replaced with another id, and we need to find the appropriate one
    # here.
    delivery_movement = related_applied_rule.contentValues()[0]
    invoice_applied_rule = delivery_movement.contentValues()[0]
    invoice_movement = invoice_applied_rule.contentValues()[0]
1359
    self.assertEqual(other_resource,
1360 1361 1362 1363 1364
            invoice_movement.getResourceValue())

    order_line.setStartDate(DateTime(2001, 02, 03))
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1365
    self.assertEqual(DateTime(2001, 02, 03),
1366 1367 1368 1369 1370
                 invoice_movement.getStartDate())

    order_line.setStopDate(DateTime(2002, 03, 04))
    self.tic()
    invoice_movement = invoice_applied_rule.contentValues()[0]
1371
    self.assertEqual(DateTime(2002, 03, 04),
1372 1373
                 invoice_movement.getStopDate())

1374
  @newSimulationExpectedFailure
1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
  def test_modify_planned_order_invoice_transaction_rule(self):
    """
    tests that modifying a planned order affects movements from invoice
    transaction rule
    """
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    product_line='apparel')
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency',
                                base_unit_quantity=0.01)
    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client',
                            default_address_region=self.default_region)
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor',
                            default_address_region=self.default_region)
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
1399
                              specialise=self.business_process,
1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')
    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                                  quantity=1,
                                  price=2)
    other_entity = self.portal.organisation_module.newContent(
                                      portal_type='Organisation',
                                      title='Other Entity',
                                      default_address_region=self.default_region)
    other_project = self.portal.project_module.newContent(
                                      portal_type='Project',
                                      title='Other Project')
    order.plan()
    self.tic()
1420
    self.assertEqual('planned', order.getSimulationState())
1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

    related_applied_rule = order.getCausalityRelatedValue(
                             portal_type='Applied Rule')
    order_movement = related_applied_rule.contentValues()[0]
    delivery_applied_rule = order_movement.contentValues()[0]
    delivery_movement = delivery_applied_rule.contentValues()[0]
    invoice_applied_rule = delivery_movement.contentValues()[0]
    invoice_movement = invoice_applied_rule.contentValues()[0]
    invoice_transaction_applied_rule = invoice_movement.contentValues()[0]

    # utility function to return the simulation movement that should be used
    # for "income" line
    def getIncomeSimulationMovement(applied_rule):
      for movement in applied_rule.contentValues():
        if movement.getDestination() == 'account_module/purchase'\
            and movement.getSource() == 'account_module/sale':
          return movement
      self.fail('Income movement not found')

1440
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1441 1442 1443 1444 1445
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)

    order_line.setSourceSectionValue(other_entity)
    self.tic()
1446
    self.assertEqual(other_entity,
1447 1448 1449 1450 1451 1452 1453 1454
                      invoice_transaction_movement.getSourceSectionValue())

    # make sure destination_section != source_section, this might be needed by
    # some rules
    order_line.setSourceSectionValue(order_line.getDestinationSectionValue())

    order_line.setDestinationSectionValue(other_entity)
    self.tic()
1455
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1456 1457
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1458
    self.assertEqual(other_entity,
1459 1460 1461 1462
                 invoice_transaction_movement.getDestinationSectionValue())

    order_line.setSourceAdministrationValue(other_entity)
    self.tic()
1463
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1464 1465
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1466
    self.assertEqual(other_entity,
1467 1468 1469 1470
                 invoice_transaction_movement.getSourceAdministrationValue())

    order_line.setDestinationAdministrationValue(other_entity)
    self.tic()
1471
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1472 1473
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1474
    self.assertEqual(other_entity,
1475 1476 1477 1478
            invoice_transaction_movement.getDestinationAdministrationValue())

    order_line.setSourceDecisionValue(other_entity)
    self.tic()
1479
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1480 1481
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1482
    self.assertEqual(other_entity,
1483 1484 1485 1486
                 invoice_transaction_movement.getSourceDecisionValue())

    order_line.setDestinationDecisionValue(other_entity)
    self.tic()
1487
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1488 1489
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1490
    self.assertEqual(other_entity,
1491 1492 1493 1494
            invoice_transaction_movement.getDestinationDecisionValue())

    order_line.setSourceProjectValue(other_project)
    self.tic()
1495
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1496 1497
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1498
    self.assertEqual(other_project,
1499 1500 1501 1502
                 invoice_transaction_movement.getSourceProjectValue())

    order_line.setDestinationProjectValue(other_project)
    self.tic()
1503
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1504 1505
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1506
    self.assertEqual(other_project,
1507 1508 1509 1510
            invoice_transaction_movement.getDestinationProjectValue())

    order_line.setSourceFunctionValue(other_entity)
    self.tic()
1511
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1512 1513
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1514
    self.assertEqual(other_entity,
1515 1516 1517 1518
                 invoice_transaction_movement.getSourceFunctionValue())

    order_line.setDestinationFunctionValue(other_entity)
    self.tic()
1519
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1520 1521
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1522
    self.assertEqual(other_entity,
1523 1524 1525 1526
            invoice_transaction_movement.getDestinationFunctionValue())

    order_line.setSourcePaymentValue(other_entity)
    self.tic()
1527
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1528 1529
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1530
    self.assertEqual(other_entity,
1531 1532 1533 1534
                 invoice_transaction_movement.getSourcePaymentValue())

    order_line.setDestinationPaymentValue(other_entity)
    self.tic()
1535
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1536 1537
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1538
    self.assertEqual(other_entity,
1539 1540 1541 1542 1543
            invoice_transaction_movement.getDestinationPaymentValue())

    order_line.setQuantity(1)
    order_line.setPrice(123)
    self.tic()
1544
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1545 1546
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1547
    self.assertEqual(123,
1548 1549 1550 1551 1552
            invoice_transaction_movement.getQuantity())

    order_line.setQuantity(456)
    order_line.setPrice(1)
    self.tic()
1553
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1554 1555
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1556
    self.assertEqual(456,
1557 1558 1559 1560
            invoice_transaction_movement.getQuantity())

    order_line.setStartDate(DateTime(2001, 02, 03))
    self.tic()
1561
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1562 1563
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1564
    self.assertEqual(DateTime(2001, 02, 03),
1565 1566 1567 1568
                 invoice_transaction_movement.getStartDate())

    order_line.setStopDate(DateTime(2002, 03, 04))
    self.tic()
1569
    self.assertEqual(3, len(invoice_transaction_applied_rule))
1570 1571
    invoice_transaction_movement = getIncomeSimulationMovement(
                                        invoice_transaction_applied_rule)
1572
    self.assertEqual(DateTime(2002, 03, 04),
1573 1574 1575 1576 1577 1578 1579
                 invoice_transaction_movement.getStopDate())

  def test_Invoice_viewAsODT(self):
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
1580 1581 1582 1583
    resource_tax = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource Tax',)
1584 1585 1586 1587 1588 1589 1590 1591
    client = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Client')
    vendor = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Vendor')
    invoice = self.portal.getDefaultModule(self.invoice_portal_type).newContent(
                              portal_type=self.invoice_portal_type,
                              start_date=DateTime(2008, 12, 31),
                              title='Invoice',
1592
                              specialise=self.business_process,
1593 1594 1595 1596
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client)
1597
    product_line1 = invoice.newContent(portal_type=self.invoice_line_portal_type,
1598 1599
                            resource_value=resource,
                            quantity=10,
1600
                            base_contribution='base_amount/tax1',
1601
                            price=3)
1602 1603 1604
    product_line2 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=20,
1605
                            base_contribution='base_amount/tax1',
1606 1607 1608 1609
                            price=5)
    product_line3 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=60,
1610
                            base_contribution='base_amount/tax2',
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
                            price=5)
    product_line4 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=60,
                            price=3)
    product_line5 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=7,
                            price=20)
    tax_line1 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource_tax,
                            use='trade/tax',
1623
                            base_contribution='base_amount/tax1',
1624 1625 1626 1627 1628
                            quantity=130,
                            price=0.2)
    tax_line2 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource_tax,
                            use='trade/tax',
1629
                            base_contribution='base_amount/tax2',
1630 1631 1632 1633 1634
                            quantity=300,
                            price=0.05)
    tax_line3 = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource_tax,
                            use='trade/tax',
1635
                            base_contribution='base_amount/tax3',
1636 1637
                            quantity=20,
                            price=0.1)
1638 1639 1640
    invoice.confirm()
    self.tic()
    odt = invoice.Invoice_viewAsODT()
1641 1642 1643 1644 1645 1646
    import cStringIO
    output = cStringIO.StringIO()
    output.write(odt)
    m = OpenDocumentTextFile(output)
    text_content=m.toString().encode('ascii','replace')
    if text_content.find('Resource Tax') != -1 :
1647 1648 1649
      self.fail('fail to delete the tax line in product line')
    if text_content.find('Tax Code') == -1 :
      self.fail('fail to add the tax code')
1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668
    if text_content.find('Amount') == -1 :
      self.fail('fail to add the amount for each tax')
    if text_content.find('Rate') == -1 :
      self.fail('fail to add the Rate for each tax')
    tax1_product_total_price=str(10*3+20*5)
    if text_content.find(tax1_product_total_price) == -1 :
      self.fail('fail to get the total price of products which tax1')
    tax2_product_total_price=str(60*5)
    if text_content.find(tax2_product_total_price) == -1 :
      self.fail('fail to get the total price of products which tax2')
    no_tax_product_total_price=str(60*3+7*20)
    if text_content.find(no_tax_product_total_price) == -1 :
      self.fail('fail to get the total price of products which have no tax')
    product_total_price_no_tax=str(10*3+20*5+60*5+60*3+7*20)
    if text_content.find(product_total_price_no_tax) == -1 :
      self.fail('fail to get the total price of the products without tax')
    product_total_price=str(10*3+20*5+60*5+60*3+7*20+130*0.2+300*0.05+20*0.1)
    if text_content.find(product_total_price) == -1 :
      self.fail('fail to get the total price of the products with tax')
1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))

  def test_Invoice_viewAsODT_empty_image(self):
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
    client = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Client')
1682
    client_logo = client.newContent(portal_type='Embedded File',
1683 1684 1685
                                    id='default_image')
    vendor = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Vendor')
1686
    vendor_logo = vendor.newContent(portal_type='Embedded File',
1687
                                    id='default_image')
1688 1689 1690
    self.assertEqual(0, vendor_logo.getSize())
    self.assertEqual(0, vendor.getDefaultImageWidth())
    self.assertEqual(0, vendor.getDefaultImageHeight())
1691 1692 1693 1694
    invoice = self.portal.getDefaultModule(self.invoice_portal_type).newContent(
                              portal_type=self.invoice_portal_type,
                              start_date=DateTime(2008, 12, 31),
                              title='Invoice',
1695
                              specialise=self.business_process,
1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client)
    line = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=10,
                            price=3)
    invoice.confirm()
    self.tic()

    odt = invoice.Invoice_viewAsODT()
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))

    # the <draw:image> should not be present, because there's no logo
    parser = OOoParser()
    parser.openFromString(odt)
    style_xml = parser.oo_files['styles.xml']
    self.assert_('<draw:image' not in style_xml)

  def test_Invoice_viewAsODT_invalid_image(self):
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
1725
    file_data = FileUpload(__file__)
1726 1727
    client = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Client')
1728
    client_logo = client.newContent(portal_type='Embedded File',
1729 1730 1731 1732
                                    id='default_image',
                                    file=file_data)
    vendor = self.portal.organisation_module.newContent(
                              portal_type='Organisation', title='Vendor')
1733
    vendor_logo = vendor.newContent(portal_type='Embedded File',
1734 1735 1736 1737 1738
                                    id='default_image',
                                    file=file_data)

    # width and height of an invalid image are -1 according to
    # OFS.Image.getImageInfo maybe this is not what we want here ?
1739 1740
    self.assertEqual(-1, vendor.getDefaultImageWidth())
    self.assertEqual(-1, vendor.getDefaultImageHeight())
1741 1742 1743 1744 1745

    invoice = self.portal.getDefaultModule(self.invoice_portal_type).newContent(
                              portal_type=self.invoice_portal_type,
                              start_date=DateTime(2008, 12, 31),
                              title='Invoice',
1746
                              specialise=self.business_process,
1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client)
    line = invoice.newContent(portal_type=self.invoice_line_portal_type,
                            resource_value=resource,
                            quantity=10,
                            price=3)
    invoice.confirm()
    self.tic()

    odt = invoice.Invoice_viewAsODT()
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))

1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811
  def test_Invoice_viewAsODT_date_before_1900(self):
    # Regression test for invoices with a date before 1900, which
    # python-2.7's strftime does not support.
    resource = self.portal.getDefaultModule(
        self.resource_portal_type
    ).newContent(
        portal_type=self.resource_portal_type,
        title='Resource',)
    file_data = FileUpload(__file__)
    client = self.portal.organisation_module.newContent(
        portal_type='Organisation',
        title='Client')
    vendor = self.portal.organisation_module.newContent(
        portal_type='Organisation',
        title='Vendor')

    invoice = self.portal.getDefaultModule(
        self.invoice_portal_type
    ).newContent(
        portal_type=self.invoice_portal_type,
        start_date=DateTime(102, 12, 31),
        stop_date=DateTime(103, 12, 31),
        title='Invoice',
        specialise=self.business_process,
        source_value=vendor,
        source_section_value=vendor,
        destination_value=client,
        destination_section_value=client)
    invoice.newContent(
        portal_type=self.invoice_line_portal_type,
        resource_value=resource,
        quantity=10,
        price=3)
    invoice.confirm()
    self.tic()

    data_dict = invoice.Invoice_getODTDataDict()
    self.assertEqual('0102/12/31', data_dict['start_date'])
    self.assertEqual('0103/12/31', data_dict['stop_date'])
    # rendering is valid odf
    odt = invoice.Invoice_viewAsODT()
    from Products.ERP5OOo.tests.utils import Validator
    odf_validator = Validator()
    err_list = odf_validator.validate(odt)
    if err_list:
      self.fail(''.join(err_list))

1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831
  def test_invoice_building_with_cells(self):
    # if the order has cells, the invoice built from that order must have
    # cells too
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    variation_base_category_list=['size'])
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency')

    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client')
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor')
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
1832
                              specialise=self.business_process,
1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')

    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,)
    order_line.setVariationBaseCategoryList(('size', ))
    order_line.setVariationCategoryList(['size/Baby', 'size/Child/32'])
    order_line.updateCellRange()

    cell_baby = order_line.newCell('size/Baby', base_id='movement',
                             portal_type=self.order_cell_portal_type)
    cell_baby.edit(quantity=10,
                   price=4,
                   variation_category_list=['size/Baby'],
                   mapped_value_property_list=['quantity', 'price'],)

    cell_child_32 = order_line.newCell('size/Child/32', base_id='movement',
                                 portal_type=self.order_cell_portal_type)
    cell_child_32.edit(quantity=20,
                       price=5,
                       variation_category_list=['size/Child/32'],
                       mapped_value_property_list=['quantity', 'price'],)
    order.confirm()
    self.tic()
1862 1863
    self.stepPackingListBuilderAlarm()
    self.tic()
1864 1865 1866 1867 1868 1869 1870 1871

    related_packing_list = order.getCausalityRelatedValue(
                                  portal_type=self.packing_list_portal_type)
    self.assertNotEquals(related_packing_list, None)

    related_packing_list.start()
    related_packing_list.stop()
    self.tic()
1872 1873
    self.stepInvoiceBuilderAlarm()
    self.tic()
1874 1875 1876 1877 1878 1879 1880

    related_invoice = related_packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)

    line_list = related_invoice.contentValues(
                     portal_type=self.invoice_line_portal_type)
1881
    self.assertEqual(1, len(line_list))
1882 1883
    invoice_line = line_list[0]

1884 1885 1886
    self.assertEqual(resource, invoice_line.getResourceValue())
    self.assertEqual(['size'], invoice_line.getVariationBaseCategoryList())
    self.assertEqual(2,
1887 1888 1889 1890
          len(invoice_line.getCellValueList(base_id='movement')))

    cell_baby = invoice_line.getCell('size/Baby', base_id='movement')
    self.assertNotEquals(cell_baby, None)
1891 1892 1893
    self.assertEqual(resource, cell_baby.getResourceValue())
    self.assertEqual(10, cell_baby.getQuantity())
    self.assertEqual(4, cell_baby.getPrice())
1894 1895 1896 1897 1898 1899
    self.assertTrue('size/Baby' in
                    cell_baby.getVariationCategoryList())
    self.assertTrue(cell_baby.isMemberOf('size/Baby'))

    cell_child_32 = invoice_line.getCell('size/Child/32', base_id='movement')
    self.assertNotEquals(cell_child_32, None)
1900 1901 1902
    self.assertEqual(resource, cell_child_32.getResourceValue())
    self.assertEqual(20, cell_child_32.getQuantity())
    self.assertEqual(5, cell_child_32.getPrice())
1903 1904 1905
    self.assertTrue('size/Child/32' in
                    cell_child_32.getVariationCategoryList())
    self.assertTrue(cell_child_32.isMemberOf('size/Child/32'))
1906 1907 1908



1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930
  def test_invoice_created_from_packing_list_with_no_order(self):
    # if the order has cells and an aggregate, the invoice built
    #from that order must have
    # cells too
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    variation_base_category_list=['size'])
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency')

    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client')
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor')
    no_order_packing_list = \
self.portal.getDefaultModule(self.packing_list_portal_type).newContent(
                              portal_type=self.packing_list_portal_type,
1931
                              specialise=self.business_process,
1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')

    packing_list_line = no_order_packing_list.newContent(
                        portal_type=self.packing_list_line_portal_type,
                                  resource_value=resource,)
    packing_list_line.setVariationBaseCategoryList(('size', ))
    packing_list_line.setVariationCategoryList(['size/Baby', 'size/Child/32'])
    packing_list_line.updateCellRange()

    cell_baby = packing_list_line.newCell('size/Baby', base_id='movement',
                             portal_type=self.packing_list_cell_portal_type)
    cell_baby.edit(quantity=10,
                   price=4,
                   variation_category_list=['size/Baby'],
                   mapped_value_property_list=['quantity', 'price'],)

    cell_child_32 = packing_list_line.newCell(
                                'size/Child/32',base_id='movement',
                                 portal_type=self.packing_list_cell_portal_type)
    cell_child_32.edit(quantity=20,
                       price=5,
                       variation_category_list=['size/Child/32'],
                       mapped_value_property_list=['quantity', 'price'],)
    no_order_packing_list.confirm()
    self.tic()
    self.assertNotEquals(no_order_packing_list, None)

    no_order_packing_list.start()
    no_order_packing_list.stop()
    self.tic()
1968 1969
    self.stepInvoiceBuilderAlarm()
    self.tic()
1970 1971 1972 1973 1974 1975 1976

    related_invoice = no_order_packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)

    line_list = related_invoice.contentValues(
                     portal_type=self.invoice_line_portal_type)
1977
    self.assertEqual(1, len(line_list))
1978 1979
    invoice_line = line_list[0]

1980 1981 1982
    self.assertEqual(resource, invoice_line.getResourceValue())
    self.assertEqual(['size'], invoice_line.getVariationBaseCategoryList())
    self.assertEqual(2,
1983 1984 1985 1986
          len(invoice_line.getCellValueList(base_id='movement')))

    cell_baby = invoice_line.getCell('size/Baby', base_id='movement')
    self.assertNotEquals(cell_baby, None)
1987 1988 1989
    self.assertEqual(resource, cell_baby.getResourceValue())
    self.assertEqual(10, cell_baby.getQuantity())
    self.assertEqual(4, cell_baby.getPrice())
1990 1991 1992 1993 1994 1995
    self.assertTrue('size/Baby' in
                    cell_baby.getVariationCategoryList())
    self.assertTrue(cell_baby.isMemberOf('size/Baby'))

    cell_child_32 = invoice_line.getCell('size/Child/32', base_id='movement')
    self.assertNotEquals(cell_child_32, None)
1996 1997 1998
    self.assertEqual(resource, cell_child_32.getResourceValue())
    self.assertEqual(20, cell_child_32.getQuantity())
    self.assertEqual(5, cell_child_32.getPrice())
1999 2000 2001
    self.assertTrue('size/Child/32' in
                    cell_child_32.getVariationCategoryList())
    self.assertTrue(cell_child_32.isMemberOf('size/Child/32'))
2002

2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023
  def test_invoice_building_with_cells_and_aggregate(self):
    # if the order has cells and an aggregate, the invoice built
    #from that order must have
    # cells too
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    variation_base_category_list=['size'])
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency')

    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client')
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor')
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
2024
                              specialise=self.business_process,
2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')

    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,)
    order_line.setVariationBaseCategoryList(('size', ))
    order_line.setVariationCategoryList(['size/Baby', 'size/Child/32'])
    order_line.updateCellRange()

    cell_baby = order_line.newCell('size/Baby', base_id='movement',
                             portal_type=self.order_cell_portal_type)
    cell_baby.edit(quantity=10,
                   price=4,
                   variation_category_list=['size/Baby'],
                   mapped_value_property_list=['quantity', 'price'],)

    cell_child_32 = order_line.newCell('size/Child/32', base_id='movement',
                                 portal_type=self.order_cell_portal_type)
    cell_child_32.edit(quantity=20,
                       price=5,
                       variation_category_list=['size/Child/32'],
                       mapped_value_property_list=['quantity', 'price'],)
    order.confirm()
    self.tic()
2054 2055
    self.stepPackingListBuilderAlarm()
    self.tic()
2056 2057 2058 2059 2060 2061 2062 2063

    related_packing_list = order.getCausalityRelatedValue(
                                  portal_type=self.packing_list_portal_type)
    self.assertNotEquals(related_packing_list, None)

    related_packing_list.start()
    related_packing_list.stop()
    self.tic()
2064 2065
    self.stepInvoiceBuilderAlarm()
    self.tic()
2066 2067 2068 2069 2070 2071 2072

    related_invoice = related_packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)

    line_list = related_invoice.contentValues(
                     portal_type=self.invoice_line_portal_type)
2073
    self.assertEqual(1, len(line_list))
2074 2075
    invoice_line = line_list[0]

2076 2077 2078
    self.assertEqual(resource, invoice_line.getResourceValue())
    self.assertEqual(['size'], invoice_line.getVariationBaseCategoryList())
    self.assertEqual(2,
2079 2080 2081 2082
          len(invoice_line.getCellValueList(base_id='movement')))

    cell_baby = invoice_line.getCell('size/Baby', base_id='movement')
    self.assertNotEquals(cell_baby, None)
2083 2084 2085
    self.assertEqual(resource, cell_baby.getResourceValue())
    self.assertEqual(10, cell_baby.getQuantity())
    self.assertEqual(4, cell_baby.getPrice())
2086 2087 2088 2089 2090 2091
    self.assertTrue('size/Baby' in
                    cell_baby.getVariationCategoryList())
    self.assertTrue(cell_baby.isMemberOf('size/Baby'))

    cell_child_32 = invoice_line.getCell('size/Child/32', base_id='movement')
    self.assertNotEquals(cell_child_32, None)
2092 2093 2094
    self.assertEqual(resource, cell_child_32.getResourceValue())
    self.assertEqual(20, cell_child_32.getQuantity())
    self.assertEqual(5, cell_child_32.getPrice())
2095 2096 2097
    self.assertTrue('size/Child/32' in
                    cell_child_32.getVariationCategoryList())
    self.assertTrue(cell_child_32.isMemberOf('size/Child/32'))
2098 2099


2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
  def test_description_copied_on_lines(self):
    # if the order lines have different descriptions, description must be
    # copied in the simulation and on created movements
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',)
    resource2 = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource2',)
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='Currency')

    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client')
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor')
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
2123
                              specialise=self.business_process,
2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008, 1, 1),
                              price_currency_value=currency,
                              title='Order')

    order.newContent(portal_type=self.order_line_portal_type,
                                  quantity=3,
                                  price=10,
                                  description='The first line',
                                  resource_value=resource,)
    order.newContent(portal_type=self.order_line_portal_type,
                                  quantity=5,
                                  price=10,
                                  description='The second line',
                                  resource_value=resource2,)

    order.confirm()
    self.tic()
2145 2146
    self.stepPackingListBuilderAlarm()
    self.tic()
2147 2148 2149 2150

    related_packing_list = order.getCausalityRelatedValue(
                                  portal_type=self.packing_list_portal_type)
    self.assertNotEquals(related_packing_list, None)
2151

2152
    movement_list = related_packing_list.getMovementList()
2153 2154
    self.assertEqual(2, len(movement_list))
    self.assertEqual(['The first line'],
2155
        [m.getDescription() for m in movement_list if m.getQuantity() == 3])
2156
    self.assertEqual(['The second line'],
2157 2158 2159 2160 2161
        [m.getDescription() for m in movement_list if m.getQuantity() == 5])

    related_packing_list.start()
    related_packing_list.stop()
    self.tic()
2162 2163
    self.stepInvoiceBuilderAlarm()
    self.tic()
2164 2165 2166 2167 2168 2169 2170

    related_invoice = related_packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)

    movement_list = related_invoice.getMovementList(
                              portal_type=self.invoice_line_portal_type)
2171 2172
    self.assertEqual(2, len(movement_list))
    self.assertEqual(['The first line'],
2173
        [m.getDescription() for m in movement_list if m.getQuantity() == 3])
2174
    self.assertEqual(['The second line'],
2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199
        [m.getDescription() for m in movement_list if m.getQuantity() == 5])


  def test_CopyAndPaste(self):
    """Test copy on paste on Invoice.
    When an invoice is copy/pasted, references should be resetted.
    """
    accounting_module = self.portal.accounting_module
    invoice = accounting_module.newContent(
                    portal_type=self.invoice_portal_type)
    invoice.edit(reference='reference',
                 source_reference='source_reference',
                 destination_reference='destination_reference',)
    cb_data = accounting_module.manage_copyObjects([invoice.getId()])
    copied, = accounting_module.manage_pasteObjects(cb_data)
    new_invoice = accounting_module[copied['new_id']]
    self.assertNotEquals(invoice.getReference(),
                         new_invoice.getReference())
    self.assertNotEquals(invoice.getSourceReference(),
                         new_invoice.getSourceReference())
    self.assertNotEquals(invoice.getDestinationReference(),
                         new_invoice.getDestinationReference())

  def test_delivery_mode_and_incoterm_on_invoice(self):
    """
2200
    test that categories delivery_mode and incoterm are copied on
2201
    the invoice by the delivery builder
2202
    """
2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221
    resource = self.portal.product_module.newContent(
                    portal_type='Product',
                    title='Resource',
                    product_line='apparel')
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='euro')
    currency.setBaseUnitQuantity(0.01)
    self.tic()#execute transaction
    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client',
                            default_address_region=self.default_region)
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor',
                            default_address_region=self.default_region)
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
2222
                              specialise=self.business_process,
2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008,10, 21),
                              price_currency_value=currency,
                              delivery_mode=self.mail_delivery_mode,
                              incoterm=self.cpt_incoterm,
                              title='Order')
    order_line = order.newContent(portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                                  quantity=5,
                                  price=2)
    order.confirm()
    self.tic()
2238 2239
    self.stepPackingListBuilderAlarm()
    self.tic()
2240 2241 2242
    related_packing_list = order.getCausalityRelatedValue(
                                portal_type=self.packing_list_portal_type)
    self.assertNotEquals(related_packing_list, None)
2243
    self.assertEqual(related_packing_list.getDeliveryMode(),
2244
                         order.getDeliveryMode())
2245
    self.assertEqual(related_packing_list.getIncoterm(),
2246 2247 2248 2249
                         order.getIncoterm())
    related_packing_list.start()
    related_packing_list.stop()
    self.tic()
2250 2251
    self.stepInvoiceBuilderAlarm()
    self.tic()
2252 2253 2254
    related_invoice = related_packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)
2255
    self.assertEqual(related_invoice.getDeliveryMode(),
2256
                         order.getDeliveryMode())
2257
    self.assertEqual(related_invoice.getIncoterm(),
2258
                         order.getIncoterm())
2259 2260


2261 2262 2263 2264 2265
  def test_01_quantity_unit_copied(self):
    """
    tests that when a resource uses different quantity unit that the
    quantity units are copied on the packing list line and then the invoice
    line using the delivery builers
2266
    """
2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
    resource = self.portal.product_module.newContent(
                    portal_type='Product',
                    title='Resource',
                    product_line='apparel')
    resource.setQuantityUnitList([self.unit_piece_quantity_unit,
                                 self.mass_quantity_unit])
    currency = self.portal.currency_module.newContent(
                                portal_type='Currency',
                                title='euro')
    currency.setBaseUnitQuantity(0.01)
    self.tic()#execute transaction
    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client',
                            default_address_region=self.default_region)
    vendor = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Vendor',
                            default_address_region=self.default_region)
    order = self.portal.getDefaultModule(self.order_portal_type).newContent(
                              portal_type=self.order_portal_type,
2288
                              specialise=self.business_process,
2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303
                              source_value=vendor,
                              source_section_value=vendor,
                              destination_value=client,
                              destination_section_value=client,
                              start_date=DateTime(2008,10, 21),
                              price_currency_value=currency,
                              delivery_mode=self.mail_delivery_mode,
                              incoterm=self.cpt_incoterm,
                              title='Order')
    first_order_line = order.newContent(
                          portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                             quantity_unit = self.unit_piece_quantity_unit,
                                  quantity=5,
                                  price=3)
2304
    second_order_line = order.newContent(
2305 2306 2307 2308 2309
                          portal_type=self.order_line_portal_type,
                                  resource_value=resource,
                             quantity_unit=self.mass_quantity_unit,
                                  quantity=1.5,
                                  price=2)
2310
    self.assertEqual(first_order_line.getQuantityUnit(),
2311
                      self.unit_piece_quantity_unit)
2312
    self.assertEqual(second_order_line.getQuantityUnit(),
2313 2314 2315 2316
                      self.mass_quantity_unit)

    order.confirm()
    self.tic()
2317 2318
    self.stepPackingListBuilderAlarm()
    self.tic()
2319 2320 2321 2322
    related_packing_list = order.getCausalityRelatedValue(
                                portal_type=self.packing_list_portal_type)
    self.assertNotEquals(related_packing_list, None)
    movement_list = related_packing_list.getMovementList()
2323
    self.assertEqual(len(movement_list),2)
2324
    movement_list = sorted(movement_list, key=lambda x: x.getQuantity())
2325
    self.assertEqual(movement_list[0].getQuantityUnit(),
2326
                      self.mass_quantity_unit)
2327 2328
    self.assertEqual(movement_list[0].getQuantity(), 1.5)
    self.assertEqual(movement_list[1].getQuantityUnit(),
2329
                      self.unit_piece_quantity_unit)
2330
    self.assertEqual(movement_list[1].getQuantity(), 5)
2331 2332 2333 2334 2335

    related_packing_list.start()
    related_packing_list.stop()
    related_packing_list.deliver()
    self.tic()
2336 2337
    self.stepInvoiceBuilderAlarm()
    self.tic()
2338 2339 2340 2341
    related_invoice = related_packing_list.getCausalityRelatedValue(
                                portal_type=self.invoice_portal_type)
    self.assertNotEquals(related_invoice, None)
    movement_list = related_invoice.getMovementList()
2342
    self.assertEqual(len(movement_list),2)
2343
    movement_list = sorted(movement_list, key=lambda x: x.getQuantity())
2344
    self.assertEqual(movement_list[0].getQuantityUnit(),
2345
                      self.mass_quantity_unit)
2346 2347
    self.assertEqual(movement_list[0].getQuantity(), 1.5)
    self.assertEqual(movement_list[1].getQuantityUnit(),
2348
                      self.unit_piece_quantity_unit)
2349
    self.assertEqual(movement_list[1].getQuantity(), 5)
2350

2351

2352 2353

  def _acceptDivergenceOnInvoice(self, invoice, divergence_list):
2354
    print invoice, divergence_list
2355
    self._solveDivergence(invoice, 'quantity', 'Accept Solver')
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365

  def test_accept_quantity_divergence_on_invoice_with_stopped_packing_list(
                self, quiet=quiet):
    sequence_list = SequenceList()
    sequence = sequence_list.addSequenceString(self.PACKING_LIST_DEFAULT_SEQUENCE)
    sequence_list.play(self, quiet=quiet)

    packing_list = sequence.get('packing_list')
    packing_list_line = packing_list.getMovementList()[0]
    previous_quantity = packing_list_line.getQuantity()
2366

2367 2368 2369
    packing_list.setReady()
    packing_list.start()
    packing_list.stop()
2370
    self.assertEqual('stopped', packing_list.getSimulationState())
2371
    self.tic()
2372 2373
    self.stepInvoiceBuilderAlarm()
    self.tic()
2374 2375 2376 2377 2378

    invoice = packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(invoice, None)
    invoice_line_list = invoice.getMovementList()
2379
    self.assertEqual(1, len(invoice_line_list))
2380 2381 2382 2383
    invoice_line = invoice_line_list[0]

    new_quantity = invoice_line.getQuantity() * 2
    invoice_line.setQuantity(new_quantity)
2384

2385 2386 2387 2388
    self.tic()

    self.assertTrue(invoice.isDivergent())
    divergence_list = invoice.getDivergenceList()
2389
    self.assertEqual(1, len(divergence_list))
2390 2391

    divergence = divergence_list[0]
2392
    self.assertEqual('quantity', divergence.tested_property)
2393 2394 2395 2396 2397

    # accept decision
    self._acceptDivergenceOnInvoice(invoice, divergence_list)

    self.tic()
2398
    self.assertEqual('solved', invoice.getCausalityState())
2399

2400 2401 2402
    self.assertEqual([], invoice.getDivergenceList())
    self.assertEqual(new_quantity, invoice_line.getQuantity())
    self.assertEqual(new_quantity,
2403 2404 2405
          invoice_line.getDeliveryRelatedValue(portal_type='Simulation Movement'
              ).getQuantity())

2406 2407
    self.assertEqual([], packing_list.getDivergenceList())
    self.assertEqual('solved', packing_list.getCausalityState())
2408

2409
  def _adoptDivergenceOnInvoice(self, invoice, divergence_list):
2410
    print invoice, divergence_list
2411
    self._solveDivergence(invoice, 'quantity', 'Adopt Solver')
2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424

  def test_adopt_quantity_divergence_on_invoice_line_with_stopped_packing_list(
                self, quiet=quiet):
    # #1053
    sequence_list = SequenceList()
    sequence = sequence_list.addSequenceString(self.PACKING_LIST_DEFAULT_SEQUENCE)
    sequence_list.play(self, quiet=quiet)

    packing_list = sequence.get('packing_list')
    packing_list_line = packing_list.getMovementList()[0]
    previous_quantity = packing_list_line.getQuantity()
    previous_resource = packing_list_line.getResource()
    previous_price = packing_list_line.getPrice()
2425

2426 2427 2428
    packing_list.setReady()
    packing_list.start()
    packing_list.stop()
2429
    self.assertEqual('stopped', packing_list.getSimulationState())
2430
    self.tic()
2431 2432
    self.stepInvoiceBuilderAlarm()
    self.tic()
2433 2434 2435 2436 2437

    invoice = packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(invoice, None)
    invoice_line_list = invoice.getMovementList()
2438
    self.assertEqual(1, len(invoice_line_list))
2439 2440 2441 2442
    invoice_line = invoice_line_list[0]

    new_quantity = invoice_line.getQuantity() * 2
    invoice_line.setQuantity(new_quantity)
2443

2444 2445 2446 2447
    self.tic()

    self.assertTrue(invoice.isDivergent())
    divergence_list = invoice.getDivergenceList()
2448
    self.assertEqual(1, len(divergence_list))
2449 2450

    divergence = divergence_list[0]
2451
    self.assertEqual('quantity', divergence.tested_property)
2452 2453 2454 2455 2456

    # adopt prevision
    self._adoptDivergenceOnInvoice(invoice, divergence_list)

    self.tic()
2457 2458
    self.assertEqual([], invoice.getDivergenceList())
    self.assertEqual('solved', invoice.getCausalityState())
2459

2460
    self.assertEqual(1,
2461
        len(invoice.getMovementList(portal_type=self.invoice_line_portal_type)))
2462
    self.assertEqual(0,
2463 2464
        len(invoice.getMovementList(portal_type=self.invoice_transaction_line_portal_type)))

2465 2466 2467 2468
    self.assertEqual(previous_resource, invoice_line.getResource())
    self.assertEqual(previous_quantity, invoice_line.getQuantity())
    self.assertEqual(previous_price, invoice_line.getPrice())
    self.assertEqual(previous_quantity,
2469 2470 2471
          invoice_line.getDeliveryRelatedValue(portal_type='Simulation Movement'
              ).getQuantity())

2472 2473
    self.assertEqual([], packing_list.getDivergenceList())
    self.assertEqual('solved', packing_list.getCausalityState())
2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 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
  
  def test_merge_accounting_invoice(
                self, quiet=quiet):
    sequence_list = SequenceList()
    sequence = sequence_list.addSequenceString(self.PACKING_LIST_DEFAULT_SEQUENCE)
    sequence_list.play(self, quiet=quiet)

    packing_list = sequence.get('packing_list')
    packing_list_line = packing_list.getMovementList()[0]
    quantity = packing_list_line.getQuantity()
    resource = packing_list_line.getResource()
    price = packing_list_line.getPrice()
    packing_list.setReady()
    packing_list.start()
    packing_list.stop()
    self.tic()
    self.default_quantity = self.default_quantity + 10
    self.default_price = self.default_price + 10
    self.tic()
    sequence_list.play(self, quiet=quiet)
    packing_list_2 = sequence.get('packing_list')
    packing_list_line = packing_list_2.getMovementList()[0]
    quantity_2 = packing_list_line.getQuantity()
    resource_2 = packing_list_line.getResource()
    price_2 = packing_list_line.getPrice()
    packing_list_2.setReady()
    packing_list_2.start()
    packing_list_2.stop()
    self.tic()
    self.stepInvoiceBuilderAlarm()
    self.tic()
    self.default_quantity = self.default_quantity - 10
    self.default_price = self.default_price - 10

    invoice = packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    invoice_2 = packing_list_2.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(invoice, None)
    self.assertNotEquals(invoice_2, None)
    self.tic()
    error_list = self.portal.portal_simulation.mergeDeliveryList([invoice, invoice_2])
    self.tic()
    self.assertEqual(0, len(error_list))
    self.assertEqual(invoice.getSimulationState(), 'confirmed')
    # MergeDeliveryList change the first delivery to diverged
    # Make sure it works as expected
    self.assertEqual(invoice.getCausalityState(), 'diverged')
    self.assertEqual(invoice_2.getSimulationState(), 'cancelled')
    self.assertEqual(len(invoice.getMovementList()), 2)
    expected_set = set([
        (resource,quantity,price),
        (resource_2, quantity_2,price_2)])
    result_set = set(sorted(
      [(x.getResource(), x.getQuantity(), x.getPrice()) for x in invoice.getMovementList()],
      key=lambda x: x[1]))
    self.assertEqual(expected_set, result_set)
2531

2532 2533 2534 2535 2536 2537
  def test_subcontent_reindexing(self):
    """Tests, that modification on Order are propagated to lines and cells
    during reindxation"""
    invoice = self.portal.getDefaultModule(self.invoice_portal_type
        ).newContent(portal_type=self.invoice_portal_type,
            created_by_builder=1)
2538
    self.tic()
2539 2540 2541 2542 2543 2544 2545 2546
    invoice_line = invoice.newContent(
        portal_type=self.invoice_line_portal_type)
    invoice_cell = invoice_line.newContent(
        portal_type=self.invoice_cell_portal_type)
    transaction_line = invoice.newContent(
        portal_type=self.invoice_transaction_line_portal_type)
    self._testSubContentReindexing(invoice, [invoice_line, transaction_line,
      invoice_cell])
2547

2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579
  def test_AccountingTransactionModuleListboxSaleTradeConditionColumn(self):
    """Check listbox Sale Trade Condition column displays the trade condition
    when there are multiple documents related by specialise category.
    """
    # test init
    accounting_module = self.portal.accounting_module
    whatever_object = accounting_module.newContent(
      portal_type=self.invoice_portal_type,
    )
    sale_trade_condition_title = "Sale Trade Condition from test_AccountingTransactionModuleListboxSaleTradeConditionColumn"
    sale_trade_condition = self.portal.sale_trade_condition_module.newContent(
      portal_type="Sale Trade Condition",
      title=sale_trade_condition_title,
    )
    sale_invoice = accounting_module.newContent(
      portal_type=self.invoice_portal_type,
    )

    # actual test
    # Check listbox Sale Trade Condition column displays the trade condition
    # when there are multiple documents related by specialise category.
    accounting_listbox = accounting_module.AccountingTransactionModule_viewAccountingTransactionList.listbox
    self.assertIn(("specialise_trade_condition_title", "Sale Trade Condition"), accounting_listbox.get_value("columns") + accounting_listbox.get_value("all_columns"))
    sale_invoice.setSpecialiseValueList([whatever_object])
    self.tic()
    sale_invoice_brain, = self.portal.portal_catalog(uid=sale_invoice.getUid(), select_list=["specialise_trade_condition_title"], limit=1)
    self.assertEqual(sale_invoice_brain.specialise_trade_condition_title, None)
    sale_invoice.setSpecialiseValueList([whatever_object, sale_trade_condition])
    self.tic()
    sale_invoice_brain, = self.portal.portal_catalog(uid=sale_invoice.getUid(), select_list=["specialise_trade_condition_title"], limit=1)
    self.assertEqual(sale_invoice_brain.specialise_trade_condition_title, sale_trade_condition_title)

2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610
class TestSaleInvoiceMixin(TestInvoiceMixin,
                           ERP5TypeTestCase):
  """Test sale invoice are created from orders then packing lists.

    Those tests methods only work for sale, because sale and purchase invoice
    are not built at the same time on packing list workflow.
  """
  quiet = 0
  invoice_portal_type = 'Sale Invoice Transaction'
  invoice_line_portal_type = 'Invoice Line'
  invoice_cell_portal_type = 'Invoice Cell'
  invoice_transaction_line_portal_type = 'Sale Invoice Transaction Line'
  payment_portal_type = 'Payment Transaction'

  # default sequence for one line of not varianted resource.
  PACKING_LIST_DEFAULT_SEQUENCE = """
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
2611 2612
      stepPackingListBuilderAlarm
      stepTic
2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepSetContainerLineFullQuantity
      stepTic
      stepCheckPackingListIsPacked
    """

  # default sequence for two lines of not varianted resource.
  PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE = """
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
2645 2646
      stepPackingListBuilderAlarm
      stepTic
2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepTic
      stepSetContainerFullQuantity
      stepTic
      stepCheckPackingListIsPacked
    """

  # default sequence for one line of not varianted resource.
  TWO_PACKING_LIST_DEFAULT_SEQUENCE = """
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
2675 2676
      stepPackingListBuilderAlarm
      stepTic
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepDecreasePackingListLineQuantity
      stepCheckPackingListIsCalculating
      stepTic
      stepCheckPackingListIsDiverged
      stepSplitAndDeferPackingList
      stepTic
      stepCheckPackingListIsSolved
      stepCheckPackingListSplitted
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepSetContainerLineFullQuantity
      stepTic
      stepCheckPackingListIsPacked
      stepDefineNewPackingListContainer
      stepTic
      stepCheckNewPackingListIsPacked
    """

class TestSaleInvoice(TestSaleInvoiceMixin, TestInvoice, ERP5TypeTestCase):
  """Tests for sale invoice.
  """
  quiet = 0

  @UnrestrictedMethod
  def createCategories(self):
    TestPackingListMixin.createCategories(self)
    TestInvoiceMixin.createCategories(self)

  getNeededCategoryList = TestInvoiceMixin.getNeededCategoryList

  def test_01_SimpleInvoice(self, quiet=quiet):
    """
    Checks that a Simple Invoice is created from a Packing List
    """
    if not quiet:
      self.logMessage('Simple Invoice')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
2726 2727
        stepInvoiceBuilderAlarm
        stepTic
2728 2729 2730 2731 2732 2733 2734
        stepCheckInvoiceBuilding
        stepRebuildAndCheckNothingIsCreated
        stepCheckInvoicesConsistency
        stepCheckInvoiceLineHasReferenceAndIntIndex
      """)
    sequence_list.play(self, quiet=quiet)

2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800
  def stepCreateCurrency(self, sequence):
    currency = self.portal.currency_module.newContent(
      portal_type="Currency", title="Currency",
      base_unit_quantity=0.01)
    sequence.edit(currency=currency)

  def stepCheckInvoiceWithBadPrecision(self, sequence):
    portal = self.portal
    vendor = sequence.get('vendor')
    invoice = portal.accounting_module.newContent(
      portal_type="Sale Invoice Transaction",
      specialise=self.business_process,
      source_section_value=vendor,
      start_date=self.datetime,
      price_currency_value=sequence.get('currency'),
      destination_section_value=sequence.get('client1'),
      source_value=vendor)
    resource = self.portal.getDefaultModule(
        self.resource_portal_type).newContent(
                    portal_type=self.resource_portal_type,
                    title='Resource',
                    sale_supply_line_source_account="account_module/sale",
                    product_line='apparel')
    product_line = invoice.newContent(portal_type="Invoice Line",
      resource_value=resource, quantity=1, price=0.014)
    product_line = invoice.newContent(portal_type="Invoice Line",
      resource_value=resource, quantity=1, price=0.014)
    self.tic()
    invoice.plan()
    invoice.confirm()
    self.tic()
    invoice.start()
    self.tic()
    movement_list = invoice.getMovementList(
        portal_type=invoice.getPortalAccountingMovementTypeList())
    receivable_line = [m for m in movement_list \
      if m.getSourceValue().getAccountType() == \
        "asset/receivable"][0]
    self.assertEquals(0.03, receivable_line.getSourceDebit())
    data = invoice.Invoice_getODTDataDict()
    precision = invoice.getQuantityPrecisionFromResource(
      invoice.getResource())
    self.assertEquals(round(data['total_price'], precision),
      receivable_line.getSourceDebit())
    vat_line = [m for m in movement_list \
      if m.getSourceValue().getAccountType() == \
        "liability/payable/collected_vat"][0]
    self.assertEquals(0.0, vat_line.getSourceDebit())
    income_line = [m for m in movement_list \
      if m.getSourceValue().getAccountType() == \
        "income"][0]
    self.assertEquals(0.03, income_line.getSourceCredit())

  def test_AccountingTransaction_roundDebitCredit(self):
    """
      Check that with two invoice lines with total price equal 0.14,
      the receivable line will be 0.03 and vat line 0
    """
    sequence_list = SequenceList()
    sequence_list.addSequenceString("""
      stepCreateCurrency
      stepCreateEntities
      stepCheckInvoiceWithBadPrecision
    """)
    sequence_list.play(self)

2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823
  def test_02_TwoInvoicesFromTwoPackingList(self, quiet=quiet):
    """
    This test was created for the following bug:
        - an order is created and confirmed
        - the packing list is split
        - the 2 packing list are delivered (at different date)
        - 2 invoices are built, then we set the same date on both of them
        - the accounting rules are generated and put in only one invoice !!,
          so we have an invoice with twice the number of accounting rules
          and an invoice with no accounting rules. both invoices are wrong
    """
    if not quiet: self.logMessage('Two Invoices from Two Packing List')
    sequence_list = SequenceList()
    for base_sequence in (self.TWO_PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepSetReadyPackingList
        stepSetReadyNewPackingList
        stepTic
        stepStartPackingList
        stepStartNewPackingList
        stepTic
2824 2825
        stepInvoiceBuilderAlarm
        stepTic
2826 2827 2828
        stepCheckTwoInvoices
        stepStartTwoInvoices
        stepTic
2829 2830
        stepInvoiceBuilderAlarm
        stepTic
2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843
        stepCheckTwoInvoicesTransactionLines
        stepCheckInvoicesConsistency
      """)
    sequence_list.play(self, quiet=quiet)

  def test_03_InvoiceEditAndInvoiceRule(self, quiet=quiet):
    """
    Invoice Rule should not be applied on invoice lines created from\
    Packing List.

    We want to prevent this from happening:
      - Create a packing list
      - An invoice is created from packing list
2844
      - Invoice is edited, updateSimulation is called
2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
      - A new Invoice Rule is created for this invoice, and accounting
        movements for this invoice are present twice in the simulation.
    """
    if not quiet:
      self.logMessage('Invoice Edit')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
2860 2861
        stepInvoiceBuilderAlarm
        stepTic
2862 2863
        stepCheckInvoiceBuilding
        stepEditInvoice
2864
        stepTic
2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882
        stepCheckInvoiceRuleNotAppliedOnInvoiceEdit
        stepCheckInvoicesConsistency
      """)
    sequence_list.play(self, quiet=quiet)

  def test_04_PackingListEditAndInvoiceRule(self, quiet=quiet):
    """
    Delivery Rule should not be applied on packing list lines created\
    from Order.
    """
    if not quiet:
      self.logMessage('Packing List Edit')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepEditPackingList
2883
        stepTic
2884
        stepCheckDeliveryRuleNotAppliedOnPackingListEdit
2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900
      """)
    sequence_list.play(self, quiet=quiet)

  def test_05_InvoiceEditPackingListLine(self, quiet=quiet):
    """
    Checks that editing a Packing List Line still creates a correct
    Invoice
    """
    if not quiet:
      self.logMessage('Packing List Line Edit')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
    """
      stepEditPackingListLine
2901 2902 2903 2904 2905 2906
      stepTic
      stepCheckPackingListIsDiverged
      stepAssertCausalityStateIsNotSolvedInConsistencyMessage
      stepSetReadyWorkflowTransitionIsBlockByConsistency
      stepAcceptDecisionDescriptionPackingList
      stepTic
2907 2908 2909 2910 2911
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
2912 2913
      stepInvoiceBuilderAlarm
      stepTic
2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
      stepCheckInvoicesConsistency
    """)
    sequence_list.play(self, quiet=quiet)

  def test_06_InvoiceDeletePackingListLine(self, quiet=quiet):
    """
    Checks that deleting a Packing List Line still creates a correct
    Invoice
    """
    if not quiet:
      self.logMessage('Packing List Line Delete')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
    """
      stepDeletePackingListLine
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
2938 2939
      stepInvoiceBuilderAlarm
      stepTic
2940 2941 2942
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
      stepCheckInvoicesConsistency
2943
      stepTic
2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960
    """)
    sequence_list.play(self, quiet=quiet)

  def test_07_InvoiceAddPackingListLine(self, quiet=quiet):
    """
    Checks that adding a Packing List Line still creates a correct
    Invoice
    """
    if not quiet:
      self.logMessage('Packing List Line Add')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE,
        self.PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE) :
      sequence_list.addSequenceString(
        base_sequence +
    """
      stepAddPackingListLine
2961
      stepTic
2962 2963 2964 2965 2966 2967 2968
      stepSetContainerFullQuantity
      stepTic
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
2969 2970
      stepInvoiceBuilderAlarm
      stepTic
2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
      stepCheckInvoicesConsistency
    """)
    sequence_list.play(self, quiet=quiet)

  def test_08_InvoiceDecreaseQuantity(self, quiet=quiet):
    """
    Change the quantity of a Invoice Line,
    check that the invoice is divergent,
    then split and defer, and check everything is solved
    """
    if not quiet:
      self.logMessage('Invoice Decrease Quantity')
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
2993 2994
    stepInvoiceBuilderAlarm
    stepTic
2995 2996 2997 2998 2999 3000 3001 3002 3003
    stepCheckInvoiceBuilding

    stepDecreaseInvoiceLineQuantity
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepSplitAndDeferInvoice
    stepTic
3004 3005
    stepInvoiceBuilderAlarm
    stepTic
3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019

    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved
    stepCheckInvoiceSplitted

    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """
    self.playSequence(sequence, quiet=quiet)

3020
  @newSimulationExpectedFailure
3021 3022 3023 3024
  def test_09_InvoiceChangeStartDateFail(self, quiet=quiet):
    """
    Change the start_date of a Invoice Line,
    check that the invoice is divergent,
3025 3026 3027
    then accept decision, and check Packing list is *not* divergent,
    because Unify Solver does not propagage the change to the upper
    simulation movement.
3028 3029
    """
    if not quiet:
3030
      self.logMessage('Invoice Change Start Date')
3031 3032 3033 3034 3035 3036 3037 3038
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3039 3040
    stepInvoiceBuilderAlarm
    stepTic
3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054
    stepCheckInvoiceBuilding

    stepChangeInvoiceStartDate
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepUnifyStartDateWithDecisionInvoice
    stepTic

    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

3055 3056 3057 3058 3059 3060
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
3061 3062 3063
    """
    self.playSequence(sequence, quiet=quiet)

3064
  @newSimulationExpectedFailure
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081
  def test_09b_InvoiceChangeStartDateSucceed(self, quiet=quiet):
    """
    Change the start_date of a Invoice Line,
    check that the invoice is divergent,
    deliver the Packing List to make sure it's frozen,
    then accept decision, and check everything is solved
    """
    if not quiet:
      self.logMessage('Invoice Change Sart Date')
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3082 3083
    stepInvoiceBuilderAlarm
    stepTic
3084 3085 3086 3087 3088 3089 3090 3091 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
    stepCheckInvoiceBuilding
    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic

    stepChangeInvoiceStartDate
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepUnifyStartDateWithDecisionInvoice
    stepTic

    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """
    self.playSequence(sequence, quiet=quiet)

  def test_10_AcceptDecisionOnPackingList(self, quiet=quiet):
    """
    - Increase or Decrease the quantity of a Packing List line
    - Accept Decision on Packing List
    - Packing List must not be divergent and use new quantity
    - Invoice must not be divergent and use new quantity
    """
    if not quiet:
      self.logMessage('InvoiceAcceptDecisionOnPackingList')
    end_sequence = \
    """
    stepSetContainerFullQuantity
    stepCheckPackingListIsCalculating
    stepTic
    stepCheckPackingListIsDiverged
    stepAcceptDecisionQuantity
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListNotSplitted

    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3137 3138
    stepInvoiceBuilderAlarm
    stepTic
3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197
    stepCheckInvoiceBuilding

    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """

    mid_sequence_list = ["""
    stepCheckInvoicingRule
    stepDecreasePackingListLineQuantity
    """, """
    stepCheckInvoicingRule
    stepIncreasePackingListLineQuantity
    """]

    sequence_list = SequenceList()
    for seq in mid_sequence_list:
      sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
          seq + end_sequence
      sequence_list.addSequenceString(sequence)
    sequence_list.play(self, quiet=quiet)

  def test_16a_ManuallyAddedMovementsManyTransactions(self, quiet=quiet):
    """
    Checks that adding invoice lines and accounting lines to one invoice
    generates correct simulation

    In this case checks what is happening, where movements are added in
    one transaction and edited in another
    """
    if not quiet:
      self.logMessage('Invoice with Manually Added Movements in separate transactions')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
          base_sequence +
          """
          stepSetReadyPackingList
          stepTic
          stepStartPackingList
          stepCheckInvoicingRule
          stepTic
3198 3199
          stepInvoiceBuilderAlarm
          stepTic
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241
          stepCheckInvoiceBuilding
          stepRebuildAndCheckNothingIsCreated
          stepCheckInvoicesConsistency
          stepAddInvoiceLinesManyTransactions
          stepTic
          stepCheckInvoiceIsSolved
          stepStartInvoice
          stepTic
          stepCheckSimulationTrees
          """)
    sequence_list.play(self, quiet=quiet)


  def test_11_AcceptDecisionOnPackingListAndInvoice(self, quiet=quiet):
    """
    - Increase or Decrease the quantity of a Packing List line
    - Accept Decision on Packing List
    - Packing List must not be divergent and use new quantity
    - Put old quantity on Invoice
    - Accept Decision on Invoice
    - Packing List must not be divergent and use new quantity
    - Invoice must not be divergent and use old quantity
    """
    if not quiet:
      self.logMessage('InvoiceAcceptDecisionOnPackingListAndInvoice')
    mid_sequence = \
    """
    stepSetContainerFullQuantity
    stepCheckPackingListIsCalculating
    stepTic
    stepCheckPackingListIsDiverged
    stepAcceptDecisionQuantity
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListNotSplitted

    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3242 3243
    stepInvoiceBuilderAlarm
    stepTic
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339
    stepCheckInvoiceBuilding

    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule
    """
    end_sequence = \
    """
    stepCheckInvoiceIsDiverged
    stepAcceptDecisionQuantityInvoice
    stepTic
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved
    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule
    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """

    mid_sequence_list = [("""
    stepCheckInvoicingRule
    stepDecreasePackingListLineQuantity
    """, """
    stepIncreaseInvoiceLineQuantity
    stepTic
    """), ("""
    stepCheckInvoicingRule
    stepIncreasePackingListLineQuantity
    """, """
    stepDecreaseInvoiceLineQuantity
    stepTic
    """)]

    sequence_list = SequenceList()
    for seq1, seq2 in mid_sequence_list:
      sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
          seq1 + mid_sequence + seq2 + end_sequence
      sequence_list.addSequenceString(sequence)
    sequence_list.play(self, quiet=quiet)

  def test_12_SplitPackingListAndAcceptInvoice(self, quiet=quiet):
    """
    - Decrease the quantity of a Packing List line
    - Split and Defer on Packing List
    - Packing List must not be divergent and use new quantity
    - splitted Packing List must not be divergent and use old - new quantity

    - Put old quantity on Invoice1
    - Accept Decision on Invoice1
    - Packing List must not be divergent and use new quantity
    - splitted Packing List must not be divergent and use old - new quantity
    - Invoice1 must not be divergent and use old quantity

    - set Invoice2 quantity to 0
    - Accept Decision on Invoice2
    - Packing List must not be divergent and use new quantity
    - splitted Packing List must not be divergent and use old - new quantity
    - Invoice1 must not be divergent and use old quantity
    - Invoice2 must not be divergent and use 0 as quantity
    """
    if not quiet:
      self.logMessage('InvoiceSplitPackingListAndAcceptInvoice')
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepCheckInvoicingRule
    stepDecreasePackingListLineQuantity
    stepSetContainerFullQuantity
    stepCheckPackingListIsCalculating
    stepTic
    stepCheckPackingListIsDiverged
    stepSplitAndDeferPackingList
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListSplitted

    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3340 3341
    stepInvoiceBuilderAlarm
    stepTic
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 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
    stepCheckInvoiceBuilding
    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListSplitted

    stepIncreaseInvoiceLineQuantity
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepAcceptDecisionQuantityInvoice
    stepTic
    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckInvoiceIsSolved
    stepCheckInvoiceNotSplitted
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency

    stepSwitchPackingLists

    stepAddPackingListContainer
    stepSetContainerFullQuantity
    stepTic
    stepCheckPackingListIsSolved
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3383 3384
    stepInvoiceBuilderAlarm
    stepTic
3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435
    stepCheckInvoiceBuilding
    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsSolved

    stepSetInvoiceLineQuantityToZero
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepAcceptDecisionQuantityInvoice
    stepTic
    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckInvoiceIsSolved
    stepCheckInvoiceNotSplitted
    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """
    self.playSequence(sequence, quiet=quiet)

  def test_13_SplitAndDeferInvoice(self, quiet=quiet):
    """
    - Accept Order, Accept Packing List
    - Decrease quantity on Invoice
    - Split and defer Invoice
    - Accept Invoice
    - Accept splitted Invoice
    - Packing List must not be divergent and use old quantity
    - Invoice must not be divergent and use new quantity
    - splitted Invoice must not be divergent and use old - new quantity
    """
    if not quiet:
      self.logMessage('InvoiceSplitAndDeferInvoice')
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3436 3437
    stepInvoiceBuilderAlarm
    stepTic
3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
    stepCheckInvoiceBuilding
    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListNotSplitted

    stepDecreaseInvoiceLineQuantity
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepSplitAndDeferInvoice
    stepTic
    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved
    stepCheckInvoiceSplitted

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency

    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepSwitchInvoices

    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """
    self.playSequence(sequence, quiet=quiet)

  def test_14_AcceptDecisionOnInvoice(self, quiet=quiet):
    """
    - Accept Order, Accept Packing List
    - Increase or Decrease quantity on Invoice
    - Accept Decision on Invoice
    - Accept Invoice
    - Packing List must not be divergent and use old quantity
    - Invoice must not be divergent and use new quantity
    """
    if not quiet:
      self.logMessage('InvoiceAcceptDecisionOnInvoice')
    mid_sequence = \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
3505 3506
    stepInvoiceBuilderAlarm
    stepTic
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 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574
    stepCheckInvoiceBuilding
    stepStopPackingList
    stepTic
    stepDeliverPackingList
    stepTic
    stepCheckPackingListIsSolved
    stepCheckPackingListNotSplitted
    """
    end_sequence = \
    """
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepAcceptDecisionQuantityInvoice
    stepTic
    stepStartInvoice
    stepTic
    stepStopInvoice
    stepTic
    stepDeliverInvoice
    stepTic

    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """

    mid_sequence_list = ["""
    stepDecreaseInvoiceLineQuantity
    """, """
    stepIncreaseInvoiceLineQuantity
    """]

    sequence_list = SequenceList()
    for seq in mid_sequence_list:
      sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
          mid_sequence + seq + end_sequence
      sequence_list.addSequenceString(sequence)
    sequence_list.play(self, quiet=quiet)


  def test_Reference(self):
    # A reference is set automatically on Sale Invoice Transaction
    supplier = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Supplier')
    client = self.portal.organisation_module.newContent(
                            portal_type='Organisation',
                            title='Client')
    currency = self.portal.currency_module.newContent(
                            portal_type='Currency')
    invoice = self.portal.accounting_module.newContent(
                    portal_type='Sale Invoice Transaction',
                    start_date=DateTime(),
                    price_currency_value=currency,
                    resource_value=currency,
                    source_section_value=supplier,
                    destination_section_value=client)
    self.portal.portal_workflow.doActionFor(invoice, 'confirm_action')

3575
    self.assertEqual('1', invoice.getReference())
3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593

  def test_16_ManuallyAddedMovements(self, quiet=quiet):
    """
    Checks that adding invoice lines and accounting lines to one invoice
    generates correct simulation
    """
    if not quiet:
      self.logMessage('Invoice with Manually Added Movements')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
          base_sequence +
          """
          stepSetReadyPackingList
          stepTic
          stepStartPackingList
          stepCheckInvoicingRule
          stepTic
3594 3595
          stepInvoiceBuilderAlarm
          stepTic
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623
          stepCheckInvoiceBuilding
          stepRebuildAndCheckNothingIsCreated
          stepCheckInvoicesConsistency
          stepAddInvoiceLines
          stepTic
          stepStartInvoice
          stepTic
          stepCheckSimulationTrees
          """)
    sequence_list.play(self, quiet=quiet)

  def test_17_ManuallyAddedWrongMovements(self, quiet=quiet):
    """
    Checks that adding invoice lines and accounting lines to one invoice
    generates correct simulation, even when adding very wrong movements
    """
    if not quiet:
      self.logMessage('Invoice with Manually Added Movements')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
          base_sequence +
          """
          stepSetReadyPackingList
          stepTic
          stepStartPackingList
          stepCheckInvoicingRule
          stepTic
3624 3625
          stepInvoiceBuilderAlarm
          stepTic
3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650
          stepCheckInvoiceBuilding
          stepAddWrongInvoiceLines
          stepTic
          stepStartInvoice
          stepCheckStartInvoiceFail
          stepCheckSimulationTrees
          """)
    sequence_list.play(self, quiet=quiet)

  def test_18_compareInvoiceAndPackingList(self, quiet=quiet):
    """
    Checks that a Simple Invoice is created from a Packing List
    """
    if not quiet:
      self.logMessage('Simple Invoice')
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
3651 3652
        stepInvoiceBuilderAlarm
        stepTic
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675
        stepCheckInvoiceBuilding
        stepCheckInvoicesConsistency
        stepCheckPackingListInvoice
      """)
    sequence_list.play(self, quiet=quiet)

  def _adoptDivergenceOnPackingList(self, packing_list, divergence_list):
    builder_list = packing_list.getBuilderList()
    for builder in builder_list:
      builder.solveDivergence(packing_list.getRelativeUrl(),
                              divergence_to_adopt_list=divergence_list)

  def test_accept_quantity_divergence_on_invoice_with_started_packing_list(
                        self, quiet=quiet):
    # only applies to sale invoice, because purchase invoices are not built yet
    # when the packing list is in started state
    sequence_list = SequenceList()
    sequence = sequence_list.addSequenceString(self.PACKING_LIST_DEFAULT_SEQUENCE)
    sequence_list.play(self, quiet=quiet)

    packing_list = sequence.get('packing_list')
    packing_list_line = packing_list.getMovementList()[0]
    previous_quantity = packing_list_line.getQuantity()
3676

3677 3678
    packing_list.setReady()
    packing_list.start()
3679
    self.assertEqual('started', packing_list.getSimulationState())
3680
    self.tic()
3681 3682
    self.stepInvoiceBuilderAlarm()
    self.tic()
3683 3684 3685 3686 3687

    invoice = packing_list.getCausalityRelatedValue(
                                  portal_type=self.invoice_portal_type)
    self.assertNotEquals(invoice, None)
    invoice_line_list = invoice.getMovementList()
3688
    self.assertEqual(1, len(invoice_line_list))
3689 3690 3691 3692
    invoice_line = invoice_line_list[0]

    new_quantity = invoice_line.getQuantity() * 2
    invoice_line.setQuantity(new_quantity)
3693

3694 3695 3696 3697
    self.tic()

    self.assertTrue(invoice.isDivergent())
    divergence_list = invoice.getDivergenceList()
3698
    self.assertEqual(1, len(divergence_list))
3699 3700

    divergence = divergence_list[0]
3701
    self.assertEqual('quantity', divergence.tested_property)
3702 3703 3704 3705 3706

    # accept decision
    self._acceptDivergenceOnInvoice(invoice, divergence_list)

    self.tic()
3707
    self.assertEqual('solved', invoice.getCausalityState())
3708

3709 3710 3711
    self.assertEqual([], invoice.getDivergenceList())
    self.assertEqual(new_quantity, invoice_line.getQuantity())
    self.assertEqual(new_quantity,
3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723
          invoice_line.getDeliveryRelatedValue(portal_type='Simulation Movement'
              ).getQuantity())

    if invoice_line.getDeliveryRelatedValue().getParentValue().getSpecialiseId() == \
        'new_invoice_simulation_rule':
      # With new simulation solvers, changes on simulation movements will
      # not backtrack.
      pass
    else:
      # With legacy simulation solvers, changes on simulation movements
      # will backtrack if simulation movements are not frozen.
      # the packing list is divergent, because it is not frozen
3724
      self.assertEqual('diverged', packing_list.getCausalityState())
3725
      divergence_list = packing_list.getDivergenceList()
3726
      self.assertEqual(1, len(divergence_list))
3727
      divergence = divergence_list[0]
3728
      self.assertEqual('quantity', divergence.tested_property)
3729 3730 3731 3732
      # if we adopt prevision on this packing list, both invoice and
      # packing list will be solved
      self._adoptDivergenceOnPackingList(packing_list, divergence_list)
      self.tic()
3733 3734
    self.assertEqual('solved', packing_list.getCausalityState())
    self.assertEqual('solved', invoice.getCausalityState())
3735

3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772
  def test_19_SimpleInvoiceModifyArrow(self):
    """
    Check we can modify arrow on an invoice without having building issues
    of transaction lines
    """
    sequence_list = SequenceList()
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
      sequence_list.addSequenceString(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
        stepInvoiceBuilderAlarm
        stepTic
        stepCheckInvoiceBuilding
      """)
    sequence_list.play(self)
    sequence = sequence_list.getSequenceList()[0]
    invoice = sequence.get("invoice")
    self.assertEqual("confirmed", invoice.getSimulationState())
    self.assertEqual("solved", invoice.getCausalityState())
    self.portal.portal_workflow.doActionFor(invoice, "start_action")
    other_client = sequence.get("organisation3")
    invoice.setDestinationSectionValue(other_client)
    self.tic()
    self.assertEqual("diverged", invoice.getCausalityState())
    self.assertEqual(set([("411", -65714.22),
                         ("44571", 10769.22),
                         ("70712", 54945.00)]),
                     set([(x.getSourceValue().getGapId(),
                           x.getQuantity()) for x in \
                           invoice.objectValues(
                    portal_type="Sale Invoice Transaction Line")]))

3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804
class TestPurchaseInvoice(TestInvoice, ERP5TypeTestCase):
  """Tests for purchase invoice.
  """
  resource_portal_type = 'Product'
  order_portal_type = 'Purchase Order'
  order_line_portal_type = 'Purchase Order Line'
  order_cell_portal_type = 'Purchase Order Cell'
  packing_list_portal_type = 'Purchase Packing List'
  packing_list_line_portal_type = 'Purchase Packing List Line'
  packing_list_cell_portal_type = 'Purchase Packing List Cell'
  invoice_portal_type = 'Purchase Invoice Transaction'
  invoice_transaction_line_portal_type = 'Purchase Invoice Transaction Line'
  invoice_line_portal_type = 'Invoice Line'
  invoice_cell_portal_type = 'Invoice Cell'

  # default sequence for one line of not varianted resource.
  PACKING_LIST_DEFAULT_SEQUENCE = """
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
3805 3806
      stepPackingListBuilderAlarm
      stepTic
3807 3808 3809 3810 3811 3812
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepTic
    """

3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834
class OpenDocumentTextFile :
  def __init__ (self, filelikeobj) :
    zip = zipfile.ZipFile(filelikeobj)
    self.content = xml.dom.minidom.parseString(zip.read("content.xml"))

  def toString (self) :
    """ Converts the document to a string. """
    buffer = u""
    for val in ["text:p", "text:h", "text:list"]:
      for paragraph in self.content.getElementsByTagName(val) :
        buffer += self.textToString(paragraph) + "\n"
    return buffer

  def textToString(self, element) :
    buffer = u""
    for node in element.childNodes :
      if node.nodeType == xml.dom.Node.TEXT_NODE :
        buffer += node.nodeValue
      elif node.nodeType == xml.dom.Node.ELEMENT_NODE :
        buffer += self.textToString(node)
    return buffer

3835 3836 3837 3838 3839 3840
import unittest
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestSaleInvoice))
  suite.addTest(unittest.makeSuite(TestPurchaseInvoice))
  return suite