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

32 33 34 35 36
TODO:
  * check empty related Delivery Rule
  * check divergence 
  
"""
37 38 39

from random import randint

40 41
import os, sys
if __name__ == '__main__':
42
    execfile(os.path.join(sys.path[0], 'framework.py'))
43 44 45 46 47

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

48
from Testing import ZopeTestCase
49
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
50 51
from AccessControl.SecurityManagement import newSecurityManager, \
                                             noSecurityManager
52
from DateTime import DateTime
53
from Acquisition import aq_base, aq_inner
54
from zLOG import LOG
55
from Products.ERP5Type.DateUtils import addToDate
56
from Products.ERP5Type.tests.Sequence import Sequence, SequenceList
57 58 59 60 61
import time
import os
from Products.ERP5Type import product_path
from Products.CMFCore.utils import getToolByName
from testPackingList import TestPackingListMixin
62
from testAccountingRules import TestAccountingRulesMixin
63

64 65
class TestInvoice(TestPackingListMixin,
                  TestAccountingRulesMixin,
Jérome Perrin's avatar
Jérome Perrin committed
66
                  ERP5TypeTestCase):
67
  """Test invoice are created from orders then packing lists. """
Jean-Paul Smets's avatar
Jean-Paul Smets committed
68
  
69
  RUN_ALL_TESTS = 1
70

71
  default_region = "europe/west/france"
72
  vat_gap = 'fr/pcg/4/44/445/4457/44571'
73
  vat_rate = 0.196
74 75
  sale_gap = 'fr/pcg/7/70/707/7071/70712'
  customer_gap = 'fr/pcg/4/41/411'
76

77 78 79 80 81
  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'

82 83
  def getTitle(self):
    return "Invoices"
84 85
  
  def login(self, quiet=0, run=1):
86
    uf = self.getPortal().acl_users
87 88
    uf._doAddUser('alex', '', ['Manager', 'Assignee', 'Assignor',
                               'Associate', 'Auditor', 'Author'], [])
Jean-Paul Smets's avatar
Jean-Paul Smets committed
89
    user = uf.getUserById('alex').__of__(uf)
90
    newSecurityManager(None, user)
91 92 93 94 95 96 97 98 99 100 101
  
  def createCategories(self):
    """Create the categories for our test. """
    TestPackingListMixin.createCategories(self)
    # create categories
    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(
Jérome Perrin's avatar
Jérome Perrin committed
102 103 104
                    portal_type='Category',
                    id=cat,
                    immediate_reindex=1 )
105
        else:
Jérome Perrin's avatar
Jérome Perrin committed
106
          path = path[cat]
107 108 109 110 111 112 113 114
    # 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."""
115
    return ('region/%s' % self.default_region,
116 117 118 119
            'gap/%s' % self.vat_gap,
            'gap/%s' % self.sale_gap,
            'gap/%s' % self.customer_gap,
        )
120 121 122 123 124
  
  def getBusinessTemplateList(self):
    """ """
    return TestPackingListMixin.getBusinessTemplateList(self) + (
              'erp5_accounting',)
125

126
  def stepTic(self, **kw):
Jean-Paul Smets's avatar
Jean-Paul Smets committed
127 128
    self.tic()

129 130 131 132
  def stepCreateEntities(self, sequence, **kw) :
    """Create a vendor and a client. """
    self.stepCreateOrganisation1(sequence, **kw)
    self.stepCreateOrganisation2(sequence, **kw)
133 134 135 136 137 138 139 140 141
    self.stepCreateOrganisation3(sequence, **kw)
    sequence.edit(vendor=sequence.get('organisation1'))
    client1 = sequence.get('organisation2')
    client1.setRegion(self.default_region)
    self.assertNotEquals(client1.getRegionValue(), None)
    sequence.edit(client1=client1)
    client2 = sequence.get('organisation3')
    self.assertEquals(client2.getRegionValue(), None)
    sequence.edit(client2=client2)
142 143 144
  
  def stepCreateCurrency(self, sequence, **kw) :
    """Create a default currency. """
145 146 147 148 149 150
    currency_module = self.getCurrencyModule()
    if len(currency_module.objectValues(id='EUR'))==0:
      currency = self.getCurrencyModule().newContent(
            portal_type = 'Currency',
            id = "EUR" )
    currency = currency_module.objectValues(id='EUR')[0]
151 152 153 154
    sequence.edit(currency = currency)
  
  def stepSetOrderPriceCurrency(self, sequence, **kw) :
    """Set the price currency of the order. 
Jean-Paul Smets's avatar
Jean-Paul Smets committed
155
    
156 157 158 159 160 161 162 163 164 165
    This step is not necessary. 
    TODO : - include a test without this step.
           - include a test with this step late.
    """
    currency = sequence.get('currency')
    order = sequence.get('order')
    order.setPriceCurrency(currency.getRelativeUrl())
  
  def stepCreateSaleInvoiceTransactionRule(self, sequence, **kw) :
    """Create the rule for accounting. """
166 167 168

    portal = self.getPortal()
    account_module = self.getAccountModule()
169 170 171 172 173 174 175 176 177
    for account_id, account_gap in (('receivable_vat', self.vat_gap),
                                    ('sale', self.sale_gap),
                                    ('customer', self.customer_gap)):
      if not account_id in account_module.objectIds():
        account = account_module.newContent(id=account_id)
        account.setGap(account_gap)
        portal.portal_workflow.doActionFor(account,
            'validate_action', wf_id='account_workflow')

Jérome Perrin's avatar
Jérome Perrin committed
178 179 180
    vat_account = account_module['receivable_vat']
    sale_account = account_module['sale']
    customer_account = account_module['customer']
181
    
Jérome Perrin's avatar
Jérome Perrin committed
182 183 184 185
    invoice_rule = self.getPortal().portal_rules\
                          .default_invoice_transaction_rule
    invoice_rule.deleteContent([x.getId()
                          for x in invoice_rule.objectValues()])
186 187 188 189 190
    region_predicate = invoice_rule.newContent(portal_type = 'Predicate')
    product_line_predicate = invoice_rule.newContent(portal_type = 'Predicate')
    region_predicate.edit(
      membership_criterion_base_category_list = ['destination_region'],
      membership_criterion_category_list =
Jérome Perrin's avatar
Jérome Perrin committed
191
                   ['destination_region/region/%s' % self.default_region ],
192 193 194 195 196 197 198 199 200 201
      int_index = 1,
      string_index = 'region'
    )
    product_line_predicate.edit(
      membership_criterion_base_category_list = ['product_line'],
      membership_criterion_category_list =
                            ['product_line/apparel'],
      int_index = 1,
      string_index = 'product'
    )
202 203 204
    product_line_predicate.immediateReindexObject()
    region_predicate.immediateReindexObject()

205
    invoice_rule.updateMatrix()
206 207 208
    cell_list = invoice_rule.getCellValueList(base_id='movement')
    self.assertEquals(len(cell_list),1)
    cell = cell_list[0]
209 210 211 212 213 214 215 216 217 218

    for line_id, line_source, line_ratio in (('income', sale_account, 1.0),
        ('receivable', customer_account, -1.0 - self.vat_rate),
        ('collected_vat', vat_account, self.vat_rate)):

      line = cell.newContent(id=line_id,
          portal_type=self.sale_invoice_transaction_portal_type)
      line.setQuantity(line_ratio)
      line.setSourceValue(line_source)

Jérome Perrin's avatar
Jérome Perrin committed
219 220
  def modifyPackingListState(self, transition_name,
                             sequence,packing_list=None):
221
    """ calls the workflow for the packing list """
222 223
    if packing_list is None:
      packing_list = sequence.get('packing_list')
224 225 226 227 228 229 230 231
    packing_list.portal_workflow.doActionFor(packing_list,
          transition_name, wf_id='packing_list_workflow')
  
  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')
    self.assertEquals(packing_list.getSimulationState(), 'ready')
232

Jérome Perrin's avatar
Jérome Perrin committed
233 234
  def stepSetReadyNewPackingList(self, sequence=None,
                                 sequence_list=None, **kw):
235 236 237 238 239 240
    """ 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)
    self.assertEquals(packing_list.getSimulationState(), 'ready')

241 242 243 244
  def stepStartPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('start_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
    self.assertEquals(packing_list.getSimulationState(), 'started')
Jean-Paul Smets's avatar
Jean-Paul Smets committed
245
    
246 247 248 249 250 251
  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)
    self.assertEquals(packing_list.getSimulationState(), 'started')
    
252 253 254 255 256 257 258 259 260
  def stepStopPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('stop_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
    self.assertEquals(packing_list.getSimulationState(), 'stopped')
    
  def stepCancelPackingList(self, sequence=None, sequence_list=None, **kw):
    self.modifyPackingListState('cancel_action', sequence=sequence)
    packing_list = sequence.get('packing_list')
    self.assertEquals(packing_list.getSimulationState(), 'cancelled')
261

262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
  def stepPackingListSimulation(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.
        self.assertEquals( simulation_movement.getRootAppliedRule(),
                           order_root_applied_rule)
      self.assertEquals(total_quantity, movement.getQuantity())
    
  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_applied_rule_list = packing_list.getCausalityRelatedValueList(
                                   portal_type=self.applied_rule_portal_type)
    related_invoice_list = packing_list.getCausalityRelatedValueList(
Jérome Perrin's avatar
Jérome Perrin committed
288
                     portal_type=self.sale_invoice_transaction_portal_type)
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324

    packing_list_building_state = 'started'
    packing_list_state = packing_list.getSimulationState()
    if packing_list_state != packing_list_building_state :
      self.assertEquals(0, len(related_invoice_list))
    else:
      self.assertEquals(1, len(related_invoice_list))

      invoice = related_invoice_list[0].getObject()
      self.failUnless(invoice is not None)
      # Invoices created by Delivery Builder are in planned state
      self.assertEquals(invoice.getSimulationState(), 'planned')
      
      # 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()
        self.assertEquals(len(invoice_movement_list), 1)
        invoice_movement = invoice_movement_list[0]
        self.failUnless(invoice_movement is not None)
        self.assert_(invoice_movement.getRelativeUrl().\
                              startswith(invoice_relative_url))

      # Then, test if each Invoice movement is equals to the sum of somes
325
      # Simulation Movements
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
      for invoice_movement in invoice.getMovementList(portal_type = [
                          self.sale_invoice_cell_portal_type,
                          self.sale_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
          self.assertEquals(invoice_movement.getResource(), \
                            related_simulation_movement.getResource())
          # Test resource variation
          self.assertEquals(invoice_movement.getVariationText(), \
                            related_simulation_movement.getVariationText())
          self.assertEquals(invoice_movement.getVariationCategoryList(), \
                        related_simulation_movement.getVariationCategoryList())
          # Test acquisition
          self.checkAcquisition(invoice_movement,
                                related_simulation_movement)
          # Test delivery ratio
          self.assertEquals(related_simulation_movement.getQuantity() /\
                            invoice_movement_quantity, \
                            related_simulation_movement.getDeliveryRatio())

        self.assertEquals(quantity, invoice_movement.getQuantity())
        # Test price
        self.assertEquals(total_price / quantity, invoice_movement.getPrice())

      sequence.edit(invoice = invoice)
      
      # Test causality
      self.assertEquals(len(invoice.getCausalityValueList(
                      portal_type = self.packing_list_portal_type)), 1)
      self.assertEquals(invoice.getCausalityValue(), packing_list)
      
      # Finally, test getTotalQuantity and getTotalPrice on Invoice
      self.assertEquals(packing_list.getTotalQuantity(),
                        invoice.getTotalQuantity())
      self.assertEquals(packing_list.getTotalPrice(),
                        invoice.getTotalPrice())


  def stepCreateSimpleSaleOrder(self, sequence, **kw):
    """ create the Order for our test.
      It contains one line :
        resource : product_module/notebook
        quantity : 10
        price : 100
378
    """
379 380 381 382 383 384
    source_section = sequence.get('source_section')
    source = sequence.get('source')
    destination_section = sequence.get('destination_section')
    destination = sequence.get('destination')
    product = sequence.get('product')
    
385 386 387 388
    order_module = self.getSaleOrderModule()
    order = order_module.newContent(portal_type='Sale Order')
    order.setStartDate(DateTime('2004-11-20'))
    order.setStopDate(DateTime('2004-11-24'))
389 390 391 392 393 394 395 396
    order.setDestinationValue(destination)
    order.setDestinationSectionValue(destination_section)
    order.setSourceValue(source)
    order.setSourceSectionValue(source_section)
    order_line = order.newContent(portal_type = 'Sale Order Line', id = '1')
    order_line.setResourceValue(product)
    order_line.setQuantity(10)
    order_line.setPrice(100)
397
    self.assertEquals(len(order.checkConsistency()), 0)
398 399 400 401 402 403 404
    sequence.edit(
      order = order,
      order_line = order_line,
      order_line_list = [order_line])
    self.assertEquals(order_line.getTotalPrice(), 10*100)

  def stepCheckOrderRule(self, sequence=None, sequence_list=None, **kw):
405
    """Check we have a related Order Rule"""
406 407 408
    order = sequence.get('order')
    simulation_tool = self.getSimulationTool()
    # Check that there is an applied rule for our packing list
409 410 411 412
    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)
413 414 415

    self.assertEquals(len(order.getMovementList()),
                  sum([len(rule.objectIds()) for rule in rule_list]))
416
    
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
  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')
    for order_rule in order_rule_list :
      for order_simulation_movement in order_rule.objectValues() :
        invoicing_rule_list = order_simulation_movement.objectValues()
        self.assertEquals(len(invoicing_rule_list), 1)
        invoicing_rule = invoicing_rule_list[0]
        sequence.edit(invoicing_rule = invoicing_rule)
        self.assertEquals(invoicing_rule.getSpecialiseId(),
                         'default_invoicing_rule')
        self.assertEquals(invoicing_rule.getPortalType(),
                         'Applied Rule')
    
        simulation_movement_list = invoicing_rule.objectValues()
        self.assertNotEquals(len(simulation_movement_list), 0)
        for simulation_movement in simulation_movement_list :
435
          resource_list = sequence.get('resource_list')
436 437
          self.assertEquals(simulation_movement.getPortalType(),
                            'Simulation Movement')
438 439
          self.assertTrue(simulation_movement.getResourceValue() in
              resource_list)
440 441 442 443 444 445
          # TODO: What is the invoice dates supposed to be ?
          # is this done through profiles ?
          self.assertEquals(simulation_movement.getStartDate(),
                     sequence.get('order').getStartDate())
          self.assertEquals(simulation_movement.getStopDate(),
                      sequence.get('order').getStopDate())
446

447 448 449 450
  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. """
451 452
    # TODO

453 454 455 456
  def stepCheckDeliveryRuleIsEmpty(
                      self, sequence=None, sequence_list=None, **kw):
    """ Checks that an empty delivery rule is created for the
        convergeant Packing List"""
457 458 459 460
    packing_list = sequence.get('packing_list')
    self.failUnless(packing_list is not None)
    simulation_tool = self.getSimulationTool()
    # Check that there is an applied rule for our packing list
461 462
    rule_list = [x for x in simulation_tool.objectValues()
                          if x.getCausalityValue()==packing_list]
463 464 465 466 467
    self.assertEquals(len(rule_list),1)
    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()
468 469 470
    self.assertEquals(len(packing_list_line_list),
                      len(rule_line_list))
    self.assertEquals(1, len(rule_line_list))
471 472
    rule_line = rule_line_list[0]
    packing_list_line = packing_list_line_list[0]
473 474 475 476 477 478 479 480 481 482
    self.assertEquals(rule_line.getQuantity(), 10)
    self.assertEquals(rule_line.getPrice(), 100)
    self.assertEquals(rule_line.getDeliveryValue(),
                      packing_list_line)
    self.assertEquals(rule_line.getStartDate(),
                      packing_list_line.getStartDate())
    self.assertEquals(rule_line.getStopDate(),
                      packing_list_line.getStopDate())
    self.assertEquals(rule_line.getPortalType(),
                      'Simulation Movement')
483

484

485
  def stepCheckPackingList(self,sequence=None, sequence_list=None,**kw):
486
    """  """
487 488 489 490 491 492 493
    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)
494
    self.assertEquals(len(sale_packing_list_list), 1)
495 496 497 498
    sale_packing_list = sale_packing_list_list[0]
    sale_packing_list_line_list = sale_packing_list.objectValues()
    self.assertEquals(len(sale_packing_list_line_list),1)
    sale_packing_list_line = sale_packing_list_line_list[0]
499 500 501 502 503 504 505 506 507 508 509 510 511
    product = sequence.get('resource')
    self.assertEquals(sale_packing_list_line.getResourceValue(),
                      product)
    self.assertEquals(sale_packing_list_line.getPrice(),
                      self.price1)
    LOG('sale_packing_list_line.showDict()',0,
          sale_packing_list_line.showDict())
    self.assertEquals(sale_packing_list_line.getQuantity(),
                      self.quantity1)
    self.assertEquals(sale_packing_list_line.getTotalPrice(),
                      self.total_price1)
    sequence.edit(packing_list = sale_packing_list)

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537
  def stepCheckTwoInvoices(self,sequence=None, sequence_list=None, **kw):
    """ checks invoice properties are well set. """
    # New we will check that we have two invoices
    packing_list = sequence.get('packing_list')
    invoice_list = packing_list.getCausalityRelatedValueList(
         portal_type=self.sale_invoice_transaction_portal_type)
    self.assertEquals(len(invoice_list),1)
    invoice = invoice_list[0]
    sequence.edit(invoice=invoice)
    new_packing_list = sequence.get('new_packing_list')
    new_invoice_list = new_packing_list.getCausalityRelatedValueList(
        portal_type=self.sale_invoice_transaction_portal_type)
    self.assertEquals(len(new_invoice_list),1)
    new_invoice = new_invoice_list[0]
    sequence.edit(new_invoice=new_invoice)

  def stepConfirmTwoInvoices(self,sequence=None, sequence_list=None, **kw):
    """ confirme both invoices. """
    portal = self.getPortal()
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
    portal.portal_workflow.doActionFor(invoice,
        'confirm_action',wf_id='accounting_workflow')
    portal.portal_workflow.doActionFor(new_invoice,
        'confirm_action',wf_id='accounting_workflow')

Jérome Perrin's avatar
Jérome Perrin committed
538 539
  def stepCheckTwoInvoicesTransactionLines(self,sequence=None,
                                           sequence_list=None, **kw):
540 541 542 543 544 545 546
    """ checks invoice properties are well set. """
    invoice = sequence.get('invoice')
    new_invoice = sequence.get('new_invoice')
    self.assertEquals(3,len(invoice.objectValues(
        portal_type=self.sale_invoice_transaction_line_portal_type)))
    self.assertEquals(3,len(new_invoice.objectValues(
        portal_type=self.sale_invoice_transaction_line_portal_type)))
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
    account_module = self.getAccountModule()
    vat_account=account_module['receivable_vat']
    sale_account=account_module['sale']
    customer_account=account_module['customer']
    found_dict = {}
    for line in invoice.objectValues(
        portal_type=self.sale_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.sale_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)
      }
Jérome Perrin's avatar
Jérome Perrin committed
576
    self.failIfDifferentSet(expected_dict.keys(), found_dict.keys())
577
    for key in found_dict.keys():
Jérome Perrin's avatar
Jérome Perrin committed
578
      self.assertAlmostEquals(expected_dict[key], found_dict[key], places=2)
579

580 581 582 583
  def stepRebuildAndCheckNothingIsCreated(self, sequence=None,
                                           sequence_list=None, **kw):
    """Rebuilds with sale_invoice_builder and checks nothing more is
    created. """
584
    accounting_module = self.getAccountingModule()
585 586 587 588 589
    sale_invoice_transaction_count = len(accounting_module.objectValues())
    for builder in self.getPortal().portal_deliveries.objectValues():
      builder.build()
    self.assertEquals(sale_invoice_transaction_count,
                      len(accounting_module.objectValues()))
590 591 592

  def stepModifyInvoicesDate(self, sequence=None,
                                           sequence_list=None, **kw):
593
    """Change invoice date"""
594 595 596 597 598 599 600 601
    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 stepRemoveDateMovementGroupForTransactionBuilder(self, sequence=None,
602
            sequence_list=None, **kw):
603 604 605 606 607 608 609 610 611
    """
    Remove DateMovementGroup
    """
    portal = self.getPortal()
    builder = portal.portal_deliveries.sale_invoice_transaction_builder
    previous_list = builder.getDeliveryCollectOrderList()
    new_list = [x for x in previous_list if x != 'DateMovementGroup']
    new_list.append('ParentExplanationMovementGroup')
    builder.setDeliveryCollectOrderList(new_list)
612
    
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658
  def stepEditInvoice(self, sequence=None, sequence_list=None, **kw):
    """Edit the current invoice, to trigger updateAppliedRule."""
    invoice = sequence.get('invoice')
    invoice.edit()

    # call updateAppliedRule directly, don't rely on edit interactions
    rule_id = 'default_invoice_rule'
    self.failUnless(rule_id in
                    self.getPortal().portal_rules.objectIds())
    invoice.updateAppliedRule(rule_id=rule_id)

  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')
    # FIXME: empty applied rule should not be created
    #self.assertEquals(len(invoice.getCausalityRelatedValueList(
    #         portal_type=self.applied_rule_portal_type)), 0)
    for invoice_mvt in invoice.getMovementList():
      self.assertEquals(len(invoice_mvt.getOrderRelatedValueList(
            portal_type=self.simulation_movement_portal_type)), 0)

  def stepEditPackingList(self, sequence=None, sequence_list=None, **kw):
    """Edit the current packing list, to trigger updateAppliedRule."""
    packing_list = sequence.get('packing_list')
    packing_list.edit()
    
    # call updateAppliedRule directly, don't rely on edit interactions
    rule_id = 'default_delivery_rule'
    self.failUnless(rule_id in
                    self.getPortal().portal_rules.objectIds())
    packing_list.updateAppliedRule(rule_id=rule_id)

  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')
    # FIXME: empty applied rule should not be created
    #self.assertEquals(len(packing_list.getCausalityRelatedValueList(
    #         portal_type=self.applied_rule_portal_type)), 0)
    for delivery_mvt in packing_list.getMovementList():
      self.assertEquals(len(delivery_mvt.getOrderRelatedValueList(
            portal_type=self.simulation_movement_portal_type)), 0)
    
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
  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)

  def stepCheckInvoiceIsCalculating(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is calculating
    """
    invoice = sequence.get('invoice')
    self.assertEquals('calculating',invoice.getCausalityState())

  def stepCheckInvoiceIsDiverged(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is diverged
    """
    invoice = sequence.get('invoice')
    self.assertEquals('diverged',invoice.getCausalityState())

  def stepCheckInvoiceIsSolved(self, sequence=None, sequence_list=None,
      **kw):
    """
    Test if invoice is solved
    """
    invoice = sequence.get('invoice')
    self.assertEquals('solved',invoice.getCausalityState())

  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')
    self.assertFalse(invoice.isDivergent())

  def stepSplitAndDifferInvoice(self, sequence=None, sequence_list=None,
      **kw):
    """
    split and differ at the invoice level
    """
    invoice = sequence.get('invoice')
    invoice.portal_workflow.doActionFor(invoice,'split_prevision_action',
        wf_id='invoice_causality_workflow', start_date=self.datetime +
        15, stop_date=self.datetime + 25)

  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)
    self.assertEquals(2,len(invoice_list))
    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):
      self.assertEquals(self.default_quantity-1,line.getQuantity())
    for line in invoice2.objectValues(
          portal_type=self.invoice_line_portal_type):
      self.assertEquals(1,line.getQuantity())





749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
  # default sequence for one line of not varianted resource.
  PACKING_LIST_DEFAULT_SEQUENCE = """
      stepCreateSaleInvoiceTransactionRule
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepSetContainerLineFullQuantity
      stepTic
      stepCheckPackingListIsPacked
775
    """
776
      
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
  # default sequence for two lines of not varianted resource.
  PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE = """
      stepCreateSaleInvoiceTransactionRule
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepTic
      stepSetContainerFullQuantity
      stepTic
      stepCheckPackingListIsPacked
    """
      
811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  # default sequence for one line of not varianted resource.
  TWO_PACKING_LIST_DEFAULT_SEQUENCE = """
      stepCreateSaleInvoiceTransactionRule
      stepCreateEntities
      stepCreateCurrency
      stepCreateOrder
      stepSetOrderProfile
      stepSetOrderPriceCurrency
      stepCreateNotVariatedResource
      stepTic
      stepCreateOrderLine
      stepSetOrderLineResource
      stepSetOrderLineDefaultValues
      stepOrderOrder
      stepTic
      stepCheckDeliveryBuilding
      stepConfirmOrder
      stepTic
      stepCheckOrderRule
      stepCheckOrderSimulation
      stepCheckDeliveryBuilding
832 833 834 835 836 837
      stepDecreasePackingListLineQuantity 
      stepCheckPackingListIsCalculating 
      stepSplitAndDeferPackingList 
      stepTic 
      stepCheckPackingListIsSolved 
      stepCheckPackingListSplitted
838 839 840 841 842 843 844 845 846 847
      stepAddPackingListContainer
      stepAddPackingListContainerLine
      stepSetContainerLineFullQuantity
      stepTic
      stepCheckPackingListIsPacked
      stepDefineNewPackingListContainer
      stepTic
      stepCheckNewPackingListIsPacked
    """

848
  def test_01_SimpleInvoice(self, quiet=0, run=RUN_ALL_TESTS):
849
    """Checks that a Simple Invoice is created from a Packing List"""
850
    if not run: return
851
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
852 853 854 855 856 857 858 859 860 861 862 863
      self.playSequence(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
        stepCheckInvoiceBuilding
        stepRebuildAndCheckNothingIsCreated
      """)

864
  def test_02_TwoInvoicesFromTwoPackingList(self, quiet=0, run=RUN_ALL_TESTS):
865 866 867 868 869 870 871 872 873
    """ 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
    """
874
    if not run: return
875
    for base_sequence in (self.TWO_PACKING_LIST_DEFAULT_SEQUENCE, ) :
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
      self.playSequence(
        base_sequence +
      """
        stepSetReadyPackingList
        stepSetReadyNewPackingList
        stepTic
        stepStartPackingList
        stepStartNewPackingList
        stepTic
        stepCheckTwoInvoices
        stepRemoveDateMovementGroupForTransactionBuilder
        stepConfirmTwoInvoices
        stepTic
        stepCheckTwoInvoicesTransactionLines
      """)

892
  def test_03_InvoiceEditAndInvoiceRule(self, quiet=0, run=RUN_ALL_TESTS):
893 894 895
    """Invoice Rule should not be applied on invoice lines created from\
    Packing List.

896
    We want to prevent this from happening:
897 898 899 900 901 902
      - Create a packing list
      - An invoice is created from packing list
      - Invoice is edited, updateAppliedRule is called
      - A new Invoice Rule is created for this invoice, and accounting
        movements for this invoice are present twice in the simulation.
    """
903
    if not run: return
904
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
905 906 907 908 909 910 911 912 913 914 915 916 917
      self.playSequence(
        base_sequence +
      """
        stepSetReadyPackingList
        stepTic
        stepStartPackingList
        stepCheckInvoicingRule
        stepTic
        stepCheckInvoiceBuilding
        stepEditInvoice
        stepCheckInvoiceRuleNotAppliedOnInvoiceEdit
      """)
  
918
  def test_04_PackingListEditAndInvoiceRule(self, quiet=0, run=RUN_ALL_TESTS):
919 920 921
    """Delivery Rule should not be applied on packing list lines created\
    from Order.
    """
922
    if not run: return
923
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
924 925 926 927 928 929 930
      self.playSequence(
        base_sequence +
      """
        stepEditPackingList
        stepCheckDeliveryRuleNotAppliedOnPackingListEdit
      """)

931
  def test_05_InvoiceEditPackingListLine(self, quiet=0, run=RUN_ALL_TESTS):
932 933
    """Checks that editing a Packing List Line still creates a correct
      Invoice"""
934
    if not run: return
935
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE, ) :
936 937
      self.playSequence(
        base_sequence +
938
    """
939 940 941 942 943 944 945 946 947 948
      stepEditPackingListLine
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
    """)

949 950
  def test_06_InvoiceDeletePackingListLine(self, quiet=0,
      run=RUN_ALL_TESTS):
951 952
    """Checks that deleting a Packing List Line still creates a correct
    Invoice"""
953
    if not run: return
954
    for base_sequence in (self.PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE, ) :
955 956
      self.playSequence(
        base_sequence +
957
    """
958 959 960 961 962 963 964 965 966 967
      stepDeletePackingListLine
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
    """)

968
  def test_07_InvoiceAddPackingListLine(self, quiet=0, run=RUN_ALL_TESTS):
969 970
    """Checks that adding a Packing List Line still creates a correct
    Invoice"""
971
    if not run: return
972 973
    for base_sequence in (self.PACKING_LIST_DEFAULT_SEQUENCE,
        self.PACKING_LIST_TWO_LINES_DEFAULT_SEQUENCE) :
974 975 976 977
      self.playSequence(
        base_sequence +
    """
      stepAddPackingListLine
978 979
      stepSetContainerFullQuantity
      stepTic
980 981 982 983 984 985 986 987
      stepSetReadyPackingList
      stepTic
      stepStartPackingList
      stepCheckInvoicingRule
      stepTic
      stepCheckInvoiceBuilding
      stepRebuildAndCheckNothingIsCreated
    """)
988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015

  #def test_08_InvoiceDecreaseQuantity(self, quiet=0, run=RUN_ALL_TESTS):
  def test_08_InvoiceDecreaseQuantity(self, quiet=0, run=1):
    """Change the quantity of a Invoice Line,
    check that the packing list is divergent,
    then split and differ"""
    if not run: return
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepTic
    stepCheckInvoiceBuilding

    stepDecreaseInvoiceLineQuantity
    stepCheckInvoiceIsCalculating
    stepSplitAndDifferInvoice
    stepTic
    stepCheckInvoiceIsSolved
    stepCheckInvoiceSplitted
    stepCheckPackingListIsDivergent
    stepCheckPackingListIsDiverged

    stepRebuildAndCheckNothingIsCreated
    """
    self.playSequence(sequence)
1016 1017 1018 1019 1020 1021 1022 1023 1024
    
if __name__ == '__main__':
  framework()
else:
  import unittest
  def test_suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(TestInvoice))
    return suite
1025