testTradeModelLine.py 54.9 KB
Newer Older
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
1
# -*- coding: utf-8 -*-
2
##############################################################################
3
# Copyright (c) 2009-2010 Nexedi SA and Contributors. All Rights Reserved.
4 5
#          Łukasz Nowak <luke@nexedi.com>
#          Fabien Morin <fabien@nexedi.com>
6
#          Julien Muchembled <jm@nexedi.com>
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
#
# 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.
#
##############################################################################

31 32
from UserDict import UserDict
import random
33 34 35
import unittest
import transaction

36
from Products.ERP5.tests.testBPMCore import TestBPMMixin
37 38
from Products.ERP5Type.Base import Base
from Products.ERP5Type.Utils import simple_decorator
39
from DateTime import DateTime
40
from Products.ERP5Type.tests.utils import createZODBPythonScript, updateCellList
41

42

43 44 45 46 47 48 49 50 51 52 53 54
def save_result_as(name):
  @simple_decorator
  def decorator(function):
    def wrapper(self, *args, **kw):
      result = function(self, *args, **kw)
      self[name] = result
      return result
    return wrapper
  return decorator


class TestTradeModelLineMixin(TestBPMMixin, UserDict):
55 56 57
  """Provides methods to implementations sharing similar logic to Trade Model Lines"""
  # Constants and variables shared by tests
  base_unit_quantity = 0.01
58 59
  node_portal_type = 'Organisation'
  order_date = DateTime()
60
  amount_generator_line_portal_type = 'Trade Model Line'
61

62 63 64 65 66 67 68 69
  def setBaseAmountQuantityMethod(self, base_amount_id, text):
    """Populate TradeModelLine_getBaseAmountQuantityMethod shared script

    This helper method edits the script so that:
    - there's no need to do any cleanup
    - data produced by previous still behaves as expected
    """
    base_amount = self.portal.portal_categories.base_amount
70 71 72 73 74
    for name in self.__class__.__name__, self._testMethodName:
      try:
        base_amount = base_amount[name]
      except KeyError:
        base_amount = base_amount.newContent(name)
75 76 77 78 79
    try:
      return base_amount[base_amount_id].getRelativeUrl()
    except KeyError:
      base_amount = base_amount.newContent(base_amount_id).getRelativeUrl()
    skin = self.portal.portal_skins.custom
80 81
    script_id = self.amount_generator_line_portal_type.replace(' ', '') \
                + '_getBaseAmountQuantityMethod'
82 83 84 85
    test = "\nif base_application == %r:\n  " % base_amount
    try:
      old_text = '\n' + skin[script_id].body()
    except KeyError:
86
      old_text = ''
87 88 89 90 91 92
    else:
      skin._delObject(script_id)
    text = test + '\n  '.join(text.splitlines()) + old_text
    createZODBPythonScript(skin, script_id, "base_application", text)
    return base_amount

93 94
  def afterSetUp(self):
    UserDict.__init__(self)
95
    return super(TestTradeModelLineMixin, self).afterSetUp()
96 97 98

  def beforeTearDown(self):
    UserDict.clear(self)
99
    return super(TestTradeModelLineMixin, self).beforeTearDown()
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117

  def clone(self, document):
    parent = document.getParentValue()
    clone, = parent.manage_pasteObjects(
      parent.manage_copyObjects(ids=document.getId()))
    clone = parent[clone['new_id']]
    try:
      self[clone.getPath()] = self[document.getPath()]
    except KeyError:
      pass
    return clone

  @save_result_as('node')
  def createNode(self, **kw):
    module = self.portal.getDefaultModule(portal_type=self.node_portal_type)
    return module.newContent(portal_type=self.node_portal_type, **kw)

  @save_result_as('resource')
118 119 120 121
  def createResource(self, portal_type, **kw):
    module = self.portal.getDefaultModule(portal_type=portal_type)
    return module.newContent(portal_type=portal_type, **kw)

122 123 124 125 126 127
  @save_result_as('currency')
  def createCurrency(self):
    return self.createResource('Currency', title='Currency',
                               base_unit_quantity=self.base_unit_quantity)

  @save_result_as('business_process')
128
  def createBusinessProcess(self, **kw):
129 130
    business_process = super(TestTradeModelLineMixin,
        self).createBusinessProcess(**kw)
131
    if self.business_link_portal_type is not None:
132 133 134 135 136 137 138
      business_link_list = [
        dict(reference='discount',
             trade_phase='default/discount',
             predecessor='trade_state/invoiced',
             # should successor be trade_state/discounted? There is no
             # such trade_state category
             successor='trade_state/accounted',
139 140
             delivery_builder=['portal_deliveries/purchase_invoice_transaction_trade_model_builder',
                               'portal_deliveries/sale_invoice_transaction_trade_model_builder'],
Łukasz Nowak's avatar
Łukasz Nowak committed
141
             test_tales_expression="python: context.getResourceValue() is not None and context.getResourceValue().getUse() == 'discount'",
142 143 144 145 146 147 148 149 150 151 152 153 154
        ),
        dict(reference='tax',
             trade_phase='default/tax',
             predecessor='trade_state/invoiced',
             # should successor be trade_state/taxed? There IS such a
             # trade_state category, but the rule that wants to match
             # the Simulation Movement that has this link as causality
             # is default_invoice_transaction_rule, the same as for
             # default/discount, so I'll use the same successor as
             # above. Besides, we'd have to create a new business_link
             # just to get back to accounted, and match it with (or
             # create a new) a portal_rule.
             successor='trade_state/accounted',
155 156
             delivery_builder=['portal_deliveries/purchase_invoice_transaction_trade_model_builder',
                               'portal_deliveries/sale_invoice_transaction_trade_model_builder'],
Łukasz Nowak's avatar
Łukasz Nowak committed
157
             test_tales_expression="python: context.getResourceValue() is not None and context.getResourceValue().getUse() == 'tax'",
158 159
        ),
      ]
160 161 162
      for business_link in business_link_list:
        link = self.createBusinessLink(business_process, **business_link)
        self['business_link/' + link.getTradePhaseId()] = link
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
    return business_process

  @save_result_as('trade_condition')
  def createTradeCondition(self, specialise_value_list,
                           trade_model_line_list=(), **kw):
    module = self.portal.getDefaultModule(
        portal_type=self.trade_condition_portal_type)
    if isinstance(specialise_value_list, Base):
      specialise_value_list = specialise_value_list,
    trade_condition = module.newContent(
        portal_type=self.trade_condition_portal_type,
        title=self.id(),
        specialise_value_list=specialise_value_list,
        **kw)
    for int_index, line_kw in enumerate(trade_model_line_list):
      kw = dict(int_index=int_index)
      kw.update(line_kw)
      self.createTradeModelLine(trade_condition, **kw)
    return trade_condition
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  def createTradeModelLine(self, document, **kw):
    line = document.newContent(portal_type='Trade Model Line', **kw)
    reference = line.getReference()
    if reference:
      self['trade_model_line/' + reference] =  line
    return line

  @save_result_as('order')
  def createOrder(self, specialise_value_list, order_line_list=(), **kw):
    module = self.portal.getDefaultModule(portal_type=self.order_portal_type)
    if isinstance(specialise_value_list, Base):
      specialise_value_list = specialise_value_list,
    kw.setdefault('start_date', self.order_date)
    order = module.newContent(
        portal_type=self.order_portal_type,
        title=self.id(),
        specialise_value_list=specialise_value_list,
        **kw)
    for arrow in ('source_value', 'source_section_value',
                  'destination_value', 'destination_section_value'):
      if order.getProperty(arrow) is None:
        order._setProperty(arrow, self.createNode())
    if not order.getPriceCurrency():
      self['price_currency'] = price_currency = self.createCurrency()
      order._setPriceCurrencyValue(price_currency)
    for line_kw in order_line_list:
      order.newContent(portal_type=self.order_line_portal_type, **line_kw)
    return order

212 213 214
  def getAggregatedAmountList(self, amount_generator, *args, **kw):
    return amount_generator.getAggregatedAmountList(*args, **kw)

215 216
  def getAggregatedAmountDict(self, amount_generator, partial_check=False,
                              **expected_amount_dict):
217
    amount_list = self.getAggregatedAmountList(amount_generator)
218 219 220
    amount_dict = {}
    for amount in amount_list:
      reference = amount.getReference()
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237
      try:
        expected_amount = expected_amount_dict.pop(reference)
      except KeyError:
        if not partial_check:
          raise
      else:
        for k, v in expected_amount.iteritems():
          if k == 'causality_value_list':
            self.assertEqual(v, amount.getValueList('causality'))
          else:
            self.assertEqual(v, amount.getProperty(k))
        amount_dict[reference] = amount
    if partial_check:
      for value in expected_amount_dict.itervalues():
        self.assertEqual(None, value)
    else:
      self.assertEqual({}, expected_amount_dict)
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257
    return amount_dict

  def getTradeModelSimulationMovementList(self, delivery_line):
    result_list = []
    for simulation_movement in delivery_line.getDeliveryRelatedValueList(
        portal_type='Simulation Movement'):
      if delivery_line.getPortalType() == self.order_line_portal_type:
        applied_rule, = [x
          for x in simulation_movement.objectValues()
          if x.getSpecialiseReference() == 'default_delivering_rule']
        simulation_movement, = applied_rule.objectValues()
      applied_rule, = [x
        for x in simulation_movement.objectValues()
        if x.getSpecialiseReference() == 'default_invoicing_rule']
      simulation_movement, = applied_rule.objectValues()
      applied_rule, = [x
        for x in simulation_movement.objectValues()
        if x.getSpecialiseReference() == 'default_trade_model_rule']
      result_list.append(applied_rule.objectValues())
    return result_list
258

259

260
class TestTradeModelLine(TestTradeModelLineMixin):
261

262 263 264 265 266 267 268 269
  # Constants and variables shared by tests
  default_discount_ratio = -0.05 # -5%
  default_tax_ratio = 0.196 # 19,6%

  new_discount_ratio = -0.04 # -4%
  new_tax_ratio = 0.22 # 22%

  modified_order_line_price_ratio = 2.0
270
  modified_packing_list_line_quantity_ratio = 0.4
271 272 273
  modified_invoice_line_quantity_ratio = modified_order_line_quantity_ratio \
      = 2.5

274 275 276 277 278 279
  @save_result_as('product/taxed')
  def createProductTaxed(self):
    return self.createResource('Product',
      title='Product Taxed',
      base_contribution=['base_amount/tax'],
      use='normal')
280

281 282 283 284 285 286
  @save_result_as('product/discounted')
  def createProductDiscounted(self):
    return self.createResource('Product',
      title='Product Discounted',
      base_contribution=['base_amount/discount'],
      use='normal')
287

288 289 290 291 292 293
  @save_result_as('product/taxed_discounted')
  def createProductDiscountedTaxed(self):
    return self.createResource('Product',
      title='Product Discounted & Taxed',
      base_contribution=['base_amount/discount', 'base_amount/tax'],
      use='normal')
294

295 296 297
  @save_result_as('service/tax')
  def createServiceTax(self):
    return self.createResource('Service', title='Tax', use='tax')
298

299 300 301
  @save_result_as('service/discount')
  def createServiceDiscount(self):
    return self.createResource('Service', title='Discount', use='discount')
302

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
  def packPackingList(self, packing_list):
    if packing_list.getContainerState() == 'packed':
      return
    packing_list.manage_delObjects(ids=[q.getId()
      for q in packing_list.objectValues(portal_type='Container')])
    transaction.commit()
    container = packing_list.newContent(portal_type='Container')
    for movement in packing_list.getMovementList():
      container.newContent(portal_type='Container Line',
                           resource=movement.getResource(),
                           quantity=movement.getQuantity())
    transaction.commit()
    self.tic()
    self.assertEqual('packed', packing_list.getContainerState())

  def copyExpectedAmountDict(self, delivery, ratio=1):
    self[delivery.getPath()] = expected_amount_dict = {}
    causality = delivery.getCausalityValue()
    for base_amount, amount_dict in self[causality.getPath()].iteritems():
      expected_amount_dict[base_amount] = new_amount_dict = {}
      for line in delivery.getMovementList():
        line_id = line.getCausalityId()
        if line_id in amount_dict:
          new_amount_dict[line.getId()] = ratio * amount_dict[line_id]

  def acceptDecisionQuantityInvoice(self, invoice):
Sebastien Robin's avatar
Sebastien Robin committed
329 330
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(invoice)
331 332 333 334 335 336
    for quantity_solver_decision in solver_process.contentValues():
      if quantity_solver_decision.getCausalityValue().getTestedProperty() \
        == 'quantity':
        # use Trade Model Solver.
        quantity_solver_decision.setSolverValue(
          self.portal.portal_solvers['Trade Model Solver'])
337 338
    solver_process.buildTargetSolverList()
    solver_process.solve()
339

340 341 342 343
  def processPackingListBuildInvoice(self, packing_list, build=None):
    self.packPackingList(packing_list)
    transaction.commit()
    self.tic()
344

345
    packing_list.start()
346
    packing_list.stop()
347 348
    transaction.commit()
    self.tic()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
349 350 351
    self.stepInvoiceBuilderAlarm()
    transaction.commit()
    self.tic()
352

353 354 355
    invoice, = packing_list.getCausalityRelatedValueList(
      portal_type=self.invoice_portal_type)
    self.assertEqual(5, len(invoice))
356

357 358 359
    packing_list.deliver()
    transaction.commit()
    self.tic()
360

361 362 363
    self['invoice'] = invoice
    if build == 'invoice':
      return invoice
364

365 366
    self.checkCausalityState(invoice, 'solved')
    self.checkTradeModelRuleSimulationExpand(packing_list)
367

368
    invoice.start()
369 370 371
    transaction.commit()
    self.tic()

372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
    self.checkInvoiceAccountingMovements(invoice)

  ###
  ##  Check methods
  ##

  def checkWithoutBPM(self, order):
    transaction.commit() # clear transactional cache
    order.getSpecialiseValue()._setSpecialise(None)
    self.assertRaises(ValueError, order.expand,
      applied_rule_id=order.getCausalityRelatedId(portal_type='Applied Rule'))
    transaction.abort()

  def checkModelLineOnDelivery(self, delivery):
    for portal_type in (self.business_link_portal_type,
                        self.trade_model_path_portal_type,
                        'Trade Model Line'):
      self.assertRaises(ValueError, delivery.newContent,
                        portal_type=portal_type)

  def checkComposition(self, movement, specialise_value_list, type_count_dict):
    composed = movement.asComposedDocument()
    self.assertFalse(movement in composed._effective_model_list)
    self.assertSameSet(composed.getSpecialiseValueList(),
                       specialise_value_list)
    count = 0
    for portal_type, n in type_count_dict.iteritems():
      count += n
      self.assertEqual(n, len(composed.objectValues(portal_type=portal_type)))
    self.assertTrue(count, len(composed.objectValues()))

  def checkAggregatedAmountList(self, order):
    expected_result_dict = self[order.getPath()]
    def check(movement, movement_id):
      kw = {}
      for reference, result in expected_result_dict.iteritems():
408 409
        total_price = result.get(movement_id) or 0.0
        if True:
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
          model_line = self['trade_model_line/' + reference]
          kw[reference] = dict(total_price=total_price,
            causality_value_list=[model_line],
            base_application_list=model_line.getBaseApplicationList(),
            base_contribution_list=model_line.getBaseContributionList())
      self.getAggregatedAmountDict(movement, **kw)

    check(order, None)
    for line in order.getMovementList():
      check(line, line.getId())

  def checkTradeModelRuleSimulationExpand(self, delivery):
    expected_result_dict = self[delivery.getPath()]
    price_currency = self['price_currency']

    for line in delivery.getMovementList():
      simulation_movement_list, = \
        self.getTradeModelSimulationMovementList(line)
      result_dict = dict((sm.getResourceValue().getUse(), sm)
                         for sm in simulation_movement_list)
      self.assertEqual(len(simulation_movement_list),
                       len(result_dict))
      for use in 'discount', 'tax':
433 434
        total_price = expected_result_dict[use].get(line.getId()) or 0.0
        if True:
435
          sm = result_dict.pop(use)
Łukasz Nowak's avatar
Łukasz Nowak committed
436 437 438
          business_link_list = sm.asComposedDocument().getBusinessLinkValueList(context=sm)
          self.assertEqual(len(business_link_list), 1)
          is_buildable = sm.isBuildable(business_link_list[0])
439
          self.assertEqual(str(sm.getTotalPrice() or 0.0), str(total_price))
Łukasz Nowak's avatar
Łukasz Nowak committed
440 441 442 443 444 445 446 447 448 449
          if is_buildable:
            self.assertEqual(3, len(sm.getCausalityValueList()))
          else:
            self.assertEqual(2, len(sm.getCausalityValueList()))
          if is_buildable:
            self.assertEqual(1, len(sm.getCausalityValueList(
              portal_type=self.business_link_portal_type)))
          else:
            self.assertEqual(0, len(sm.getCausalityValueList(
              portal_type=self.business_link_portal_type)))
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485
          self.assertEqual(1, len(sm.getCausalityValueList(
            portal_type=self.trade_model_path_portal_type)))
          self.assertEqual(1, len(sm.getCausalityValueList(
            portal_type='Trade Model Line')))
          self.assertEqual(sm.getBaseApplicationList(),
                           ['base_amount/' + use])
          self.assertEqual(sm.getBaseContributionList(),
                           dict(discount=['base_amount/tax'], tax=[])[use])
      self.assertEqual({}, result_dict)

  def checkCausalityState(self, delivery, state):
    self.assertEqual(state, delivery.getCausalityState(),
      delivery.getDivergenceList())

  def checkInvoiceAccountingMovements(self, invoice):
    # Wouldn't it be better to use 'invoice.getAggregatedAmountList()'
    # instead of looking at invoice lines ? We wouldn't have to clear
    # base_contribution_list in test_01a_InvoiceNewTradeConditionOrLineSupport
    line_dict = {}
    for line in invoice.getMovementList():
      if line.getPortalType() == self.invoice_line_portal_type:
        key = line.getResourceValue().getUse()
      else:
        key = ('income_expense', 'payable_receivable', 'vat')[
          ['income', 'expense',
           'liability/payable', 'asset/receivable',
           'liability/payable/collected_vat', 'asset/receivable/refundable_vat',
          ].index(line.getSourceValue().getAccountType()) // 2]
      line_dict.setdefault(key, 0)
      line_dict[key] += line.getTotalPrice()
    self.assertEqual(6, len(line_dict))

    currency_precision = self['price_currency'].getQuantityPrecision()
    rounded_total_price = round(line_dict['normal'], currency_precision)
    rounded_tax_price = round(line_dict['tax'], currency_precision)
    rounded_discount_price = round(line_dict['discount'], currency_precision)
486 487 488 489 490 491
    self.assertEqual(str(abs(line_dict['payable_receivable'])),
        str(rounded_total_price + rounded_tax_price + rounded_discount_price))
    self.assertEqual(str(abs(line_dict['vat'])),
        str(rounded_tax_price))
    self.assertEquals(str(abs(line_dict['income_expense'])),
        str(rounded_total_price + rounded_discount_price))
492

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
493 494
  def stepPackingListBuilderAlarm(self, sequence=None,
                                  sequence_list=None, **kw):
495 496 497 498 499
    # global builder alarm does not exist in legacy simulation
    # business templates.
    alarm = getattr(self.portal.portal_alarms, 'packing_list_builder_alarm', None)
    if alarm is not None:
      alarm.activeSense()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
500 501 502

  def stepInvoiceBuilderAlarm(self, sequence=None,
                                  sequence_list=None, **kw):
503 504 505 506 507
    # global builder alarm does not exist in legacy simulation
    # business templates.
    alarm = getattr(self.portal.portal_alarms, 'invoice_builder_alarm', None)
    if alarm is not None:
      alarm.activeSense()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
508

509 510 511
  ###
  ##  Test cases
  ##
512

513 514
  def test_01_OrderWithSimpleTaxedAndDiscountedLines(self, build=None):
    """Full test case with quite simple linear use case
515

516 517 518 519 520 521 522 523 524 525 526 527 528 529
    Data:
    - 1 SO: 1 taxed, 1 discounted, 1 taxed&discounted
    - 1 TC: tax, discount
    - 1 BP (linked to default BP)

    Checks:
    - composition
    - getAggregatedAmountList
    - expand (before and after modifying quantities on order lines)
    - build of packing list (+ pack) and invoice
    """
    taxed = self.createProductTaxed()
    discounted = self.createProductDiscounted()
    taxed_discounted = self.createProductDiscountedTaxed()
530
    business_process = self.createBusinessProcess()
531
    trade_condition = self.createTradeCondition(
532
      business_process, (
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
      dict(price=self.default_discount_ratio,
           base_application='base_amount/discount',
           base_contribution='base_amount/tax',
           trade_phase='default/discount',
           resource_value=self.createServiceDiscount(),
           reference='discount',
           int_index=10),
      dict(price=self.default_tax_ratio,
           base_application='base_amount/tax',
           trade_phase='default/tax',
           resource_value=self.createServiceTax(),
           reference='tax',
           int_index=20),
      ))
    order = self.createOrder(trade_condition, (
      dict(price=1, quantity=2, id='taxed',
                                resource_value=taxed),
      dict(price=3, quantity=4, id='discounted',
                                resource_value=discounted),
      dict(price=5, quantity=6, id='taxed_discounted',
                                resource_value=taxed_discounted),
      ))
    discount = {None: (3*4 + 5*6) * self.default_discount_ratio,
                'discounted': (3*4) * self.default_discount_ratio,
                'taxed_discounted': (5*6) * self.default_discount_ratio}
    self[order.getPath()] = dict(
      discount=discount,
      tax={None: (1*2 + 5*6 + discount[None]) * self.default_tax_ratio,
           'taxed': (1*2) * self.default_tax_ratio,
           'discounted': discount['discounted'] * self.default_tax_ratio,
           'taxed_discounted': (5*6 + discount['taxed_discounted'])
                               * self.default_tax_ratio})

    transaction.commit()
    self.tic()

    if not build:
570 571 572 573 574 575
      # Check amount_generator refuses to produce amounts
      # if lines are not ordered correctly.
      self['trade_model_line/tax'].setIntIndex(0)
      self.assertRaises(ValueError, order.getGeneratedAmountList)
      transaction.abort()

576 577 578
      for movement in (order, order['taxed'], order['discounted'],
                       order['taxed_discounted']):
        self.checkComposition(movement, [trade_condition], {
579
          self.trade_model_path_portal_type: 12,
580
          self.business_link_portal_type: 7,
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620
          "Trade Model Line": 2})

      self.checkAggregatedAmountList(order)

      order.plan()
      transaction.commit()
      self.tic()

      self.checkTradeModelRuleSimulationExpand(order)

      self.checkWithoutBPM(order)

      order2 = self.clone(order)

      # Multiply prices by 2 and quantities by 2.5
      order['taxed'].edit(price=2, quantity=5)
      order['discounted'].edit(price=6, quantity=10)
      order['taxed_discounted'].edit(price=10, quantity=15)
      transaction.commit()
      self.tic()

      discount = {None: (6*10 + 10*15) * self.default_discount_ratio,
                  'discounted': (6*10) * self.default_discount_ratio,
                  'taxed_discounted': (10*15) * self.default_discount_ratio}
      self[order.getPath()] = dict(
        discount=discount,
        tax={None: (2*5 + 10*15 + discount[None]) * self.default_tax_ratio,
             'taxed': (2*5) * self.default_tax_ratio,
             'discounted': discount['discounted'] * self.default_tax_ratio,
             'taxed_discounted': (10*15 + discount['taxed_discounted'])
                                 * self.default_tax_ratio})

      self.checkTradeModelRuleSimulationExpand(order)

      self.checkAggregatedAmountList(order)
      order = order2

    order.confirm()
    transaction.commit()
    self.tic()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
621 622 623
    self.stepPackingListBuilderAlarm()
    transaction.commit()
    self.tic()
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 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

    packing_list, = order.getCausalityRelatedValueList(
      portal_type=self.packing_list_portal_type)
    self.copyExpectedAmountDict(packing_list)

    self['packing_list'] = packing_list
    if build == 'packing_list':
      return packing_list

    return self.processPackingListBuildInvoice(packing_list, build)

  def test_01a_InvoiceNewTradeConditionOrLineSupport(self):
    invoice = self.test_01_OrderWithSimpleTaxedAndDiscountedLines('invoice')

    # on invoice, make specialise point to a new TC and check it diverged
    trade_condition = self['trade_condition']
    new_trade_condition = self.clone(trade_condition)
    line_dict = dict((line.getReference(), line)
                     for line in new_trade_condition.objectValues())
    line_dict['discount'].edit(reference='discount_2',
                               price=self.new_discount_ratio)
    line_dict['tax'].edit(reference='tax_2',
                          price=self.new_tax_ratio)

    self.assertEqual([trade_condition], invoice.getSpecialiseValueList())
    invoice.setSpecialiseValue(new_trade_condition)
    transaction.commit()
    self.tic()
    self.checkCausalityState(invoice, 'diverged')

    # revert to reuse invoice
    invoice.setSpecialiseValue(trade_condition)
    transaction.commit()
    self.tic()
    self.checkCausalityState(invoice, 'solved')

    # check how is supported addition of invoice line to invoice
    for line in self['order'].getMovementList():
      line = invoice.newContent(portal_type=self.invoice_line_portal_type,
                                resource=line.getResource(),
                                quantity=line.getQuantity(),
                                price=line.getPrice())
      # XXX base_contribution_list is automatically copied from the resource
      #     but Invoice Transaction Trade Model Line Builder will not be called
      #     again (or if we call it, lines would be built in a new invoice)
      #     and accounting lines would not match invoice lines.
      #     So we clear the list to make the test simpler.
      #     See also 'checkInvoiceAccountingMovements' method.
      self.assertTrue(line.getBaseContributionList())
      line._setBaseContributionList(())
    transaction.commit()
    self.tic()
    self.checkCausalityState(invoice, 'solved')

    invoice.start()
    transaction.commit()
    self.tic()

    self.checkCausalityState(invoice, 'solved')
    self.checkInvoiceAccountingMovements(invoice)

    invoice.stop()
    invoice.deliver()
    transaction.commit()
    self.tic()

690
  def test_01b_NewSimulation_InvoiceModifyQuantityAndSolveDivergency(self):
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
    invoice = self.test_01_OrderWithSimpleTaxedAndDiscountedLines('invoice')

    for line in invoice.getMovementList():
      if line.getResourceValue().getUse() == 'normal':
        line.setQuantity(line.getQuantity() *
          self.modified_invoice_line_quantity_ratio)
    transaction.commit()
    self.tic()
    self.checkCausalityState(invoice, 'diverged')

    self.acceptDecisionQuantityInvoice(invoice)
    transaction.commit()
    self.tic()
    self.checkCausalityState(invoice, 'solved')

  def test_01c_PackingListSplitBuildInvoiceBuild(self):
    packing_list = \
      self.test_01_OrderWithSimpleTaxedAndDiscountedLines('packing_list')

    for line in packing_list.getMovementList():
        line.setQuantity(line.getQuantity() *
          self.modified_packing_list_line_quantity_ratio)
    transaction.commit()
    self.tic()
    self.checkCausalityState(packing_list, 'diverged')

    order = self['order']
    self.checkTradeModelRuleSimulationExpand(order)
    self.copyExpectedAmountDict(packing_list,
        self.modified_packing_list_line_quantity_ratio)

    listbox = [{'listbox_key':line.getRelativeUrl(),
                'choice':'SplitAndDefer'}
               for line in packing_list.getMovementList()
               if line.isDivergent()]
    self.assertEqual(len(order), len(listbox))
    self.portal.portal_workflow.doActionFor(
      packing_list,
      'split_and_defer_action',
      start_date=packing_list.getStartDate() + 15,
      stop_date=packing_list.getStopDate() + 25,
      listbox=listbox)

    transaction.commit()
    self.tic()
    self.checkCausalityState(packing_list, 'solved')
    new_packing_list, = [x for x in order.getCausalityRelatedValueList(
                             portal_type=self.packing_list_portal_type)
                           if x != packing_list]
    self.copyExpectedAmountDict(new_packing_list,
        1 - self.modified_packing_list_line_quantity_ratio)

    invoice_count = len(self.portal
        .accounting_module.objectValues(portal_type=self.invoice_portal_type))
    self.processPackingListBuildInvoice(packing_list)
746 747
    # For some time, the following assertion failed. Here was the reason:
    #     With legacy code, only 1 invoice was built after starting the first
748 749 750 751 752
    #     packing list. Now, all invoice lines generated by trade model are
    #     built immediately, creating a second invoice before starting the
    #     second packing list, and we end up with 3 invoices. In other words,
    #     the new simulation splits the second invoice, and I am not sure it's
    #     correct.
753 754 755 756
    #     The difference between old and new simulation is that when the first
    #     invoice is confirmed, the old code does not expand the simulation
    #     tree completely and SaleInvoice_selectTradeModelMovementList can't
    #     find any simulation movements related to the second packing list.
757 758 759
    # This was fixed by removing 'planned' state from
    # {Purchase,Sale}Invoice_selectTradeModelMovementList scripts.
    self.assertEqual(invoice_count + 1, len(self.portal
760 761 762 763 764 765
        .accounting_module.objectValues(portal_type=self.invoice_portal_type)))
    self.processPackingListBuildInvoice(new_packing_list)

  def test_02_OrderWithComplexTaxedAndDiscountedLines(self):
    service_discount = self.createServiceDiscount()
    service_tax = self.createServiceTax()
766
    business_process = self.createBusinessProcess()
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 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
    line_list = [
      dict(price=0.2,
           base_application='base_amount/tax',
           base_contribution='base_amount/total_tax',
           trade_phase='default/tax',
           resource_value=service_tax,
           reference='service_tax',
           int_index=10),
      dict(price=0.32,
           base_application='base_amount/discount',
           base_contribution='base_amount/total_discount',
           trade_phase='default/discount',
           resource_value=service_discount,
           reference='total_dicount_2',
           int_index=10),
      dict(price=0.2,
           base_application='base_amount/tax',
           base_contribution='base_amount/total_tax',
           trade_phase='default/tax',
           resource_value=service_tax,
           reference='service_tax_2',
           int_index=10),
      dict(price=0.12,
           base_application='base_amount/total_tax',
           base_contribution='base_amount/total_discount',
           trade_phase='default/tax',
           resource_value=service_tax,
           reference='tax_3',
           int_index=20),
      dict(price=0.8,
           base_application='base_amount/total_discount',
           trade_phase='default/discount',
           resource_value=service_discount,
           reference='total_discount',
           int_index=30),
      ]
    random.shuffle(line_list)
    trade_condition = self.createTradeCondition(business_process, line_list)

    taxed = self.createProductTaxed()
    discounted = self.createProductDiscounted()
    order = self.createOrder(trade_condition, (
      dict(price=1, quantity=2, id='taxed',
                                resource_value=taxed),
      dict(price=3, quantity=4, id='discounted',
                                resource_value=discounted),
      ))
    discount_price = (3*4) * 0.32
    tax_price = (1*2) * 0.2
    total_tax_price = tax_price * 2 * 0.12
    self[order.getPath()] = dict(
      service_tax={None: tax_price, 'taxed': tax_price},
      total_dicount_2={None: discount_price, 'discounted': discount_price},
      service_tax_2={None: tax_price, 'taxed': tax_price},
      tax_3={None: total_tax_price, 'taxed': total_tax_price},
      total_discount={None: (total_tax_price+discount_price) * 0.8,
                      'taxed': total_tax_price * 0.8,
                      'discounted': discount_price * 0.8})
825

826 827 828 829
    transaction.commit()
    self.tic()

    self.checkModelLineOnDelivery(order)
830

831 832
    for movement in order, order['taxed'], order['discounted']:
      self.checkComposition(movement, [trade_condition], {
833
        self.trade_model_path_portal_type: 12,
834
        self.business_link_portal_type: 7,
835 836 837
        "Trade Model Line": 5})

    self.checkAggregatedAmountList(order)
838

839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
  def test_03_VariatedModelLine(self):
    base_amount = self.setBaseAmountQuantityMethod('tax', """\
def getBaseAmountQuantity(delivery_amount, base_application,
                          variation_category_list=(), **kw):
  if variation_category_list:
    quantity = delivery_amount.getGeneratedAmountQuantity(base_application)
    tax_range, = variation_category_list
    if tax_range == 'tax_range/0_200':
      return min(quantity, 200)
    else:
      assert tax_range == 'tax_range/200_inf'
      return max(0, quantity - 200)
  return context.getBaseAmountQuantity(delivery_amount, base_application, **kw)
return getBaseAmountQuantity""")
    business_process = self.createBusinessProcess()
    trade_condition = self.createTradeCondition(business_process, (
      dict(price=0.3,
           base_application=base_amount,
           reference='tax1',
           int_index=10),
      dict(base_application=base_amount,
           base_contribution='base_amount/total_tax',
           reference='tax2',
           int_index=20),
      dict(base_application='base_amount/total_tax',
           base_contribution='base_amount/total',
           reference='tax3',
           int_index=30),
      ))
    def createCells(line, matrix, base_application=(), base_contribution=()):
      range_list = [set() for x in iter(matrix).next()]
      for index in matrix:
        for x, y in zip(range_list, index):
          x.add(y)
      line.setCellRange(*range_list)
      for index, price in matrix.iteritems():
        line.newCell(mapped_value_property='price', price=price,
          base_application_list=[index[i] for i in base_application],
          base_contribution_list=[index[i] for i in base_contribution],
          *index)
    createCells(self['trade_model_line/tax2'], {
      ('tax_range/0_200', 'tax_share/A'): .1,
      ('tax_range/0_200', 'tax_share/B'): .2,
      ('tax_range/200_inf', 'tax_share/A'): .3,
      ('tax_range/200_inf', 'tax_share/B'): .4,
      }, base_application=(0,), base_contribution=(1,))
    createCells(self['trade_model_line/tax3'], {
      ('tax_share/A',): .5,
      ('tax_share/B',): .6,
      }, base_application=(0,))
    from Products.ERP5Type.Document import newTempAmount
890
    for x in ((100, 30, 10, 0, 0, 20, 5, 12),
891 892 893 894 895 896 897 898
              (500, 150, 20, 90, 40, 120, 55, 96)):
      amount = newTempAmount(self.portal, '_',
                            quantity=x[0], price=1,
                            base_contribution=base_amount)
      amount_list = trade_condition.getGeneratedAmountList((amount,))
      self.assertEqual(sorted(x[1:]),
                       sorted(y.getTotalPrice() for y in amount_list))

899
  def test_tradeModelLineWithFixedPrice(self):
900 901 902 903 904
    """
      Check it's possible to have fixed quantity on lines. Sometimes we want
      to say "discount 10 euros" or "pay more 10 euros" instead of saying "10%
      discount from total"
    """
905 906 907
    fixed_quantity = self.setBaseAmountQuantityMethod('fixed_quantity', """\
return lambda *args, **kw: 1""")

908 909 910 911 912 913
    tax = self.createServiceTax()
    trade_condition = self.createTradeCondition((), (
      # create a model line with 100 euros
      dict(reference='A', resource_value=tax, quantity=100, price=1),
      # add a discount of 10 euros
      dict(reference='B', resource_value=tax, quantity=10, price=-1)))
914 915 916
    order = self.createOrder(trade_condition, (
      dict(),
      ))
917 918
    amount_list = order.getAggregatedAmountList()
    self.assertEqual([0, 0], [x.getTotalPrice() for x in amount_list])
919 920
    for line in trade_condition.objectValues():
      line.setBaseApplication(fixed_quantity)
921
    amount_list = order.getAggregatedAmountList()
922
    self.assertEqual([-10, 100], sorted(x.getTotalPrice() for x in amount_list))
923

924
  def test_BuildTradeModelLineAndAccountingFromOrder(self):
925
    business_process = self.createBusinessProcess()
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946

    product = self.createProductTaxed()
    tax = self.createServiceTax()
    trade_condition = self.createTradeCondition(
      business_process, (
      dict(reference='VAT',
           price=.15,
           resource_value=tax,
           trade_phase='default/tax',
           base_application='base_amount/tax'),
      ))
    source = self.createNode()
    destination = self.createNode()

    order = self.createOrder(trade_condition, (
      dict(price=100, quantity=10, resource_value=product),
      ),
      source_value=source,
      destination_value=destination,
      source_section_value=source,
      destination_section_value=destination)
947 948 949 950 951

    order.plan()
    order.confirm()
    transaction.commit()
    self.tic()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
952 953 954
    self.stepPackingListBuilderAlarm()
    transaction.commit()
    self.tic()
955 956 957 958 959 960 961 962 963

    packing_list = order.getCausalityRelatedValue(
                      portal_type=self.packing_list_portal_type)
    self.assertNotEquals(packing_list, None)
    self.assertEquals(1000, packing_list.getTotalPrice())
    
    packing_list.start()
    packing_list.stop()
    packing_list.deliver()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
964 965 966
    transaction.commit()
    self.tic()
    self.stepInvoiceBuilderAlarm()
967 968 969 970 971 972 973 974
    transaction.commit()
    self.tic()

    invoice = packing_list.getCausalityRelatedValue(
                      portal_type=self.invoice_portal_type)
    self.assertNotEquals(invoice, None)
    self.assertEquals(2, len(invoice.getMovementList()))
    self.assertEquals(1150, invoice.getTotalPrice())
975
    self.assertEquals([], invoice.getDivergenceList())
976
    
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    invoice.start()
    transaction.commit()
    self.tic()

    self.assertEquals([], invoice.getDivergenceList())
    accounting_line_list = invoice.getMovementList(
             portal_type=self.invoice_transaction_line_portal_type)
    self.assertEquals(3, len(accounting_line_list))

    receivable_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.receivable_account]
    self.assertEquals(1, len(receivable_movement_list))
    receivable_movement = receivable_movement_list[0]
    self.assertEquals(receivable_movement.getDestinationValue(),
                      self.payable_account)
    self.assertEquals(1150, receivable_movement.getSourceDebit())

    collected_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.collected_tax_account]
    self.assertEquals(1, len(collected_movement_list))
    collected_movement = collected_movement_list[0]
    self.assertEquals(collected_movement.getDestinationValue(),
                      self.refundable_tax_account)
    self.assertEquals(150, collected_movement.getSourceCredit())

    income_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.income_account]
    self.assertEquals(1, len(income_movement_list))
    income_movement = income_movement_list[0]
    self.assertEquals(income_movement.getDestinationValue(),
                      self.expense_account)
    self.assertEquals(1000, income_movement.getSourceCredit())

  def test_BuildTradeModelLineAndAccountingFromInvoice(self):
1011
    business_process = self.createBusinessProcess()
1012 1013 1014

    product = self.createProductTaxed()
    tax = self.createServiceTax()
1015
    currency = self.createResource('Currency', title='EUR')
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
    trade_condition = self.createTradeCondition(
      business_process, (
      dict(reference='VAT',
           price=.15,
           resource_value=tax,
           trade_phase='default/tax',
           base_application='base_amount/tax'),
      ))
    source = self.createNode()
    destination = self.createNode()
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

    invoice = self.portal.accounting_module.newContent(
               portal_type=self.invoice_portal_type,
               source_value=source,
               destination_value=destination,
               source_section_value=source,
               destination_section_value=destination,
               specialise_value=trade_condition,
               price_currency_value=currency,
               start_date=self.order_date,
               stop_date=self.order_date,
               created_by_builder=True)
    invoice.newContent(
                portal_type=self.invoice_line_portal_type,
                resource_value=product,
                quantity=10,
                price=100)

    invoice.plan()
    invoice.confirm()
    transaction.commit()
    self.tic()

    self.assertEquals(2, len(invoice.getMovementList()))
    self.assertEquals(1150, invoice.getTotalPrice())
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
    self.assertEquals([], invoice.getDivergenceList())

    invoice.start()
    transaction.commit()
    self.tic()

    self.assertEquals([], invoice.getDivergenceList())
    accounting_line_list = invoice.getMovementList(
             portal_type=self.invoice_transaction_line_portal_type)
    self.assertEquals(3, len(accounting_line_list))

    receivable_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.receivable_account]
    self.assertEquals(1, len(receivable_movement_list))
    receivable_movement = receivable_movement_list[0]
    self.assertEquals(receivable_movement.getDestinationValue(),
                      self.payable_account)
    self.assertEquals(1150, receivable_movement.getSourceDebit())

    collected_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.collected_tax_account]
    self.assertEquals(1, len(collected_movement_list))
    collected_movement = collected_movement_list[0]
    self.assertEquals(collected_movement.getDestinationValue(),
                      self.refundable_tax_account)
    self.assertEquals(150, collected_movement.getSourceCredit())

    income_movement_list = [m for m in accounting_line_list if
        m.getSourceValue() == self.income_account]
    self.assertEquals(1, len(income_movement_list))
    income_movement = income_movement_list[0]
    self.assertEquals(income_movement.getDestinationValue(),
                      self.expense_account)
    self.assertEquals(1000, income_movement.getSourceCredit())

1086 1087 1088 1089 1090 1091
  def test_tradeModelLineWithTargetLevelSetting(self):
    """
      Test that target level setting can specify a target of trade model line
      and trade model line can works with appropriate context(delivery or
      movement) only.
    """
1092 1093 1094 1095 1096 1097
    bounded_fee = self.setBaseAmountQuantityMethod('bounded_fee', """\
return lambda *args, **kw: min(800,
  context.getBaseAmountQuantity(*args, **kw))""")
    fixed_quantity = self.setBaseAmountQuantityMethod('fixed_quantity', """\
return lambda *args, **kw: 1""")

1098 1099
    tax = self.createServiceTax()
    trade_condition = self.createTradeCondition(self.createBusinessProcess())
1100
    # create a model line and set target level to `delivery`.
1101
    tml = self.createTradeModelLine(trade_condition,
1102
                                    reference='TAX',
1103 1104
                                    resource_value=tax,
                                    base_application='base_amount/tax',
1105
                                    target_delivery=True,
1106
                                    price=0.05)
1107 1108 1109 1110

    # create an order.
    resource_A = self.createResource('Product', title='A')
    resource_B = self.createResource('Product', title='B')
1111
    order = self.createOrder(trade_condition)
1112
    base_contribution_list = 'base_amount/tax', bounded_fee
1113 1114 1115 1116 1117 1118 1119 1120
    kw = {'portal_type': self.order_line_portal_type,
          'base_contribution_list': base_contribution_list}
    order_line_1 = order.newContent(price=1000, quantity=1,
                                    resource_value=resource_A, **kw)
    order_line_2 = order.newContent(price=500, quantity=1,
                                    resource_value=resource_B, **kw)
    amount_list = order.getGeneratedAmountList()
    self.assertEqual([75], [x.getTotalPrice() for x in amount_list])
1121 1122

    # change target level to `movement`.
1123
    tml.setTargetDelivery(False)
1124 1125
    amount_list = order.getGeneratedAmountList()
    self.assertEqual([25, 50], sorted(x.getTotalPrice() for x in amount_list))
1126 1127 1128

    # create other trade model lines.
    # for movement
1129 1130
    extra_fee_a = self.createTradeModelLine(trade_condition,
                                            reference='EXTRA_FEE_A',
1131
                                            resource_value=tax,
1132
                                            base_application=bounded_fee,
1133
                                            price=.2)
1134 1135 1136 1137
    # Extra fee b has a fixed quantity so that this trade model line is applied
    # to all movements by force.
    extra_fee_b = self.createTradeModelLine(trade_condition,
                                            reference='EXTRA_FEE_B',
1138
                                            resource_value=tax,
1139
                                            base_application=fixed_quantity,
1140
                                            price=1)
1141 1142 1143
    # for delivery level
    discount = self.createTradeModelLine(trade_condition,
                                         reference='DISCOUNT_B',
1144
                                         resource_value=tax,
1145 1146
                                         base_application=fixed_quantity,
                                         target_delivery=True,
1147
                                         quantity=10, price=-1)
1148

Julien Muchembled's avatar
Julien Muchembled committed
1149 1150
    transaction.commit() # flush transactional cache

1151 1152 1153 1154 1155 1156 1157 1158
    expected_tax = 1000*0.05, 500*0.05, 500*0.2, 800*0.2, 1, 1, -10
    amount_list = order.getGeneratedAmountList()
    self.assertEqual(sorted(expected_tax),
                     sorted(x.getTotalPrice() for x in amount_list))
    amount_list = order.getAggregatedAmountList()
    expected_tax = 1000*0.05 + 500*0.05, 500*0.2 + 800*0.2, 1 + 1, -10
    self.assertEqual(sorted(expected_tax),
                     sorted(x.getTotalPrice() for x in amount_list))
1159
    # Change target level
1160 1161
    extra_fee_a.setTargetDelivery(True)
    extra_fee_b.setTargetDelivery(True)
1162 1163 1164 1165 1166
    amount_list = order.getAggregatedAmountList()
    expected_tax = 1000*0.05 + 500*0.05, 800*0.2, 1, -10
    self.assertEqual(sorted(expected_tax),
                     sorted(x.getTotalPrice() for x in amount_list))

Yusei Tahara's avatar
Yusei Tahara committed
1167 1168 1169 1170
  def test_tradeModelLineWithRounding(self):
    """
      Test if trade model line works with rounding.
    """
1171
    trade_condition = self.createTradeCondition(self.createBusinessProcess())
Yusei Tahara's avatar
Yusei Tahara committed
1172 1173 1174
    # create a model line and set target level to `delivery`
    tax = self.createTradeModelLine(trade_condition,
                                    reference='TAX',
1175 1176 1177 1178
                                    base_application='base_amount/tax',
                                    base_contribution='base_amount/total_tax',
                                    price=0.05,
                                    target_delivery=True)
Yusei Tahara's avatar
Yusei Tahara committed
1179 1180 1181 1182

    # create a rounding model for tax
    rounding_model = self.portal.portal_roundings.newContent(portal_type='Rounding Model')
    rounding_model.setDecimalRoundingOption('ROUND_DOWN')
1183
    rounding_model.setPrecision(1)
Yusei Tahara's avatar
Yusei Tahara committed
1184 1185 1186 1187 1188 1189 1190 1191
    rounding_model.setRoundedPropertyId('total_price')
    rounding_model._setMembershipCriterionCategoryList(['base_contribution/base_amount/total_tax'])
    rounding_model._setMembershipCriterionBaseCategoryList(['base_contribution'])
    rounding_model.validate()

    # create an order
    resource_A = self.createResource('Product', title='A')
    resource_B = self.createResource('Product', title='B')
1192
    order = self.createOrder(trade_condition)
Yusei Tahara's avatar
Yusei Tahara committed
1193 1194 1195
    order_line_1 = order.newContent(portal_type=self.order_line_portal_type,
                                    price=3333, quantity=1,
                                    resource_value=resource_A,
1196
                                    base_contribution='base_amount/tax')
Yusei Tahara's avatar
Yusei Tahara committed
1197 1198 1199
    order_line_2 = order.newContent(portal_type=self.order_line_portal_type,
                                    price=171, quantity=1,
                                    resource_value=resource_B,
1200
                                    base_contribution='base_amount/tax')
Yusei Tahara's avatar
Yusei Tahara committed
1201 1202 1203 1204

    transaction.commit()
    self.tic()
    # check the result without rounding
1205 1206
    amount, = order.getAggregatedAmountList(rounding=False)
    self.assertEqual((3333+171)*0.05, amount.getTotalPrice()) # 175.2
Yusei Tahara's avatar
Yusei Tahara committed
1207
    # check the result with rounding
1208 1209
    amount, = order.getAggregatedAmountList(rounding=True)
    self.assertEqual(175, amount.getTotalPrice())
Yusei Tahara's avatar
Yusei Tahara committed
1210 1211

    # change tax trade model line to `movement` level
1212
    tax.setTargetDelivery(False)
Yusei Tahara's avatar
Yusei Tahara committed
1213 1214 1215 1216

    def getTotalAmount(amount_list):
      result = 0
      for amount in amount_list:
1217 1218
        if amount.getBaseContribution() in ('base_amount/total',
                                            'base_amount/total_tax'):
Yusei Tahara's avatar
Yusei Tahara committed
1219 1220 1221 1222
          result += amount.getTotalPrice()
      return result

    # check the result without rounding
1223 1224
    amount, = order.getAggregatedAmountList(rounding=False)
    self.assertEqual(3333*0.05+171*0.05, amount.getTotalPrice()) # 175.2
Yusei Tahara's avatar
Yusei Tahara committed
1225
    # check the result with rounding
1226
    amount_list = order.getAggregatedAmountList(rounding=True)
1227
    self.assertEqual(2, len(amount_list)) # XXX 1 or 2 ???
Yusei Tahara's avatar
Yusei Tahara committed
1228 1229 1230 1231
    self.assertEqual(174, getTotalAmount(amount_list))

    # check getAggregatedAmountList result of each movement
    # order line 1
1232 1233 1234 1235
    amount, = order_line_1.getAggregatedAmountList(rounding=False)
    self.assertEqual(3333*0.05, amount.getTotalPrice()) # 166.65
    amount, = order_line_1.getAggregatedAmountList(rounding=True)
    self.assertEqual(166, amount.getTotalPrice())
Yusei Tahara's avatar
Yusei Tahara committed
1236
    # order line 2
1237 1238 1239 1240
    amount, = order_line_2.getAggregatedAmountList(rounding=False)
    self.assertEqual(171*0.05, amount.getTotalPrice()) # 8.55
    amount, = order_line_2.getAggregatedAmountList(rounding=True)
    self.assertEqual(8, amount.getTotalPrice())
Yusei Tahara's avatar
Yusei Tahara committed
1241 1242 1243

    # change rounding model definition
    rounding_model.setDecimalRoundingOption('ROUND_UP')
1244
    rounding_model.setPrecision(1)
Yusei Tahara's avatar
Yusei Tahara committed
1245 1246 1247 1248 1249 1250 1251 1252 1253
    rounding_model.setRoundedPropertyIdList(['total_price', 'quantity'])

    # change quantity
    order_line_1.edit(quantity=3.3333)

    transaction.commit()
    self.tic()

    # check the result without rounding
1254 1255
    amount, = order.getAggregatedAmountList(rounding=False)
    self.assertEqual(3.3333*3333*0.05+171*0.05, amount.getTotalPrice())
Yusei Tahara's avatar
Yusei Tahara committed
1256 1257 1258 1259
    # check the result with rounding
    # both quantity and total price will be rounded so that the expression
    # should be "round_up(round_up(3.3333 * 3333) * 0.05) + round_up(round_up
    # (1* 171) * 0.05)"
1260
    amount_list = order.getAggregatedAmountList(rounding=True)
1261
    self.assertEqual(2, len(amount_list)) # XXX 1 or 2 ???
Yusei Tahara's avatar
Yusei Tahara committed
1262 1263 1264 1265 1266
    self.assertEqual(565, getTotalAmount(amount_list))

    # create a rounding model to round quantity property of order line
    rounding_model_for_quantity = self.portal.portal_roundings.newContent(portal_type='Rounding Model')
    rounding_model_for_quantity.setDecimalRoundingOption('ROUND_DOWN')
1267
    rounding_model_for_quantity.setPrecision(1)
Yusei Tahara's avatar
Yusei Tahara committed
1268 1269 1270 1271 1272 1273 1274 1275
    rounding_model_for_quantity.setRoundedPropertyId('quantity')
    rounding_model_for_quantity._setMembershipCriterionCategoryList(['base_contribution/base_amount/tax'])
    rounding_model_for_quantity._setMembershipCriterionBaseCategoryList(['base_contribution'])
    rounding_model_for_quantity.validate()

    transaction.commit()
    self.tic()

1276
    amount_list = order.getAggregatedAmountList(rounding=True)
Yusei Tahara's avatar
Yusei Tahara committed
1277 1278
    # The expression should be "round_up(round_up(round_down(3.3333) * 3333)
    # * 0.05) + round_up(round_up(round_down(1) * 171) * 0.05)"
1279
    self.assertEqual(2, len(amount_list)) # XXX 1 or 2 ???
Yusei Tahara's avatar
Yusei Tahara committed
1280 1281 1282 1283 1284
    self.assertEqual(509, getTotalAmount(amount_list))

    # create a rounding model to round price property of order line
    rounding_model_for_price = self.portal.portal_roundings.newContent(portal_type='Rounding Model')
    rounding_model_for_price.setDecimalRoundingOption('ROUND_UP')
1285
    rounding_model_for_price.setPrecision(0.1)
Yusei Tahara's avatar
Yusei Tahara committed
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299
    rounding_model_for_price.setRoundedPropertyId('price')
    rounding_model_for_price._setMembershipCriterionCategoryList(['base_contribution/base_amount/tax'])
    rounding_model_for_price._setMembershipCriterionBaseCategoryList(['base_contribution'])
    rounding_model_for_price.validate()

    # change price
    order_line_2.edit(price=171.1234)
    # invalidate rounding model for total price
    rounding_model.invalidate()

    transaction.commit()
    self.tic()

    # check the result without rounding
1300 1301
    amount, = order.getAggregatedAmountList(rounding=False)
    self.assertEqual(3.3333*3333*0.05+171.1234*0.05, amount.getTotalPrice())
Yusei Tahara's avatar
Yusei Tahara committed
1302
    # check the result with rounding
1303
    amount_list = order.getAggregatedAmountList(rounding=True)
Yusei Tahara's avatar
Yusei Tahara committed
1304 1305
    # The expression should be "round_down(3.3333) * round_up(3333) * 0.05 +
    # round_down(1) * round_up(171.1234) * 0.05"
1306
    self.assertEqual(2, len(amount_list)) # XXX 1 or 2 ???
Yusei Tahara's avatar
Yusei Tahara committed
1307 1308
    self.assertEqual(508.51000000000005, getTotalAmount(amount_list))

Sebastien Robin's avatar
Sebastien Robin committed
1309 1310 1311 1312 1313
  def test_tradeModelLineWithEmptyBaseContributionMovement(self):
    """
    Make sure that a movement which does not have any base_contribution values
    does not match to any trade model lines.
    """
1314 1315 1316 1317 1318 1319 1320
    trade_condition = self.createTradeCondition(
      (), (
      dict(price=0.05,
           reference='TAX',
           base_application_list=['base_amount/tax'],
           base_contribution_list=['base_amount/total_tax']),
      ))
Sebastien Robin's avatar
Sebastien Robin committed
1321 1322 1323

    # create an order
    resource_A = self.createResource('Product', title='A')
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
    order = self.createOrder(
      trade_condition, (
      # create a movement which should be aggregated
      dict(id='1',
           price=100, quantity=1,
           resource_value=resource_A,
           base_contribution_list=['base_amount/tax']),
      # create a movement which base contribution is empty and shoud not be
      # aggregated
      dict(id='2',
           price=31, quantity=1,
           resource_value=resource_A,
           base_contribution_list=[]),
      ))
Sebastien Robin's avatar
Sebastien Robin committed
1338 1339 1340 1341 1342

    transaction.commit()
    self.tic()

    # check the result
1343 1344
    amount, = order.getAggregatedAmountList()
    self.assertEqual(100*0.05, amount.getTotalPrice())
Sebastien Robin's avatar
Sebastien Robin committed
1345 1346


1347 1348 1349
class TestTradeModelLineSale(TestTradeModelLine):
  invoice_portal_type = 'Sale Invoice Transaction'
  invoice_line_portal_type = 'Invoice Line'
1350
  invoice_transaction_line_portal_type = 'Sale Invoice Transaction Line'
1351 1352 1353 1354 1355
  order_portal_type = 'Sale Order'
  order_line_portal_type = 'Sale Order Line'
  packing_list_portal_type = 'Sale Packing List'
  trade_condition_portal_type = 'Sale Trade Condition'

1356

1357 1358 1359 1360
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestTradeModelLineSale))
  return suite