testERP5Simulation.py 30.2 KB
Newer Older
1
# -*- coding: utf-8 -*-
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
##############################################################################
#
# Copyright (c) 2009 Nexedi SA and Contributors. All Rights Reserved.
#
# 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
##############################################################################
"""
This test is experimental for new simulation implementation.
"""

import unittest
import transaction

35 36
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from Products.ERP5Type.tests.Sequence import SequenceList
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
37
from Products.ERP5Type.UnrestrictedMethod import UnrestrictedMethod
38
from testPackingList import TestPackingList, TestPackingListMixin
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
39
from testInvoice import TestSaleInvoice, TestInvoiceMixin
40
from Products.ERP5Type.tests.backportUnittest import expectedFailure
41
from Products.ERP5Type.Document.BusinessTemplate import getChainByType
42

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
43
class TestERP5SimulationMixin(TestInvoiceMixin):
44
  def getBusinessTemplateList(self):
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
45 46
    return list(TestInvoiceMixin.getBusinessTemplateList(self)) + \
           ['erp5_administration', 'erp5_simulation',]
47 48

  def afterSetUp(self, quiet=1, run=1):
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
49
    TestInvoiceMixin.afterSetUp(self)
50
    portal_rules = self.portal.portal_rules
51
    for rule in portal_rules.objectValues(portal_type='Order Root Simulation Rule'):
52 53
      if rule.getValidationState() == 'validated':
        rule.invalidate()
54
    self.validateNewRules()
55 56 57 58 59 60 61
    self.setUpBusinessProcess()

  def setUpBusinessProcess(self):
    business_process = self.portal.business_process_module.erp5_default_business_process
    pay_business_path = business_process['pay']
    pay_business_path.setSource('account_module/bank')
    pay_business_path.setDestination('account_module/bank')
62

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
  @UnrestrictedMethod
  def createInvoiceTransactionRule(self, resource=None):
    """Create a sale invoice transaction rule with only one cell for
    product_line/apparel and default_region
    The accounting rule cell will have the provided resource, but this his more
    or less optional (as long as price currency is set correctly on order)
    """
    portal = self.portal
    account_module = portal.account_module
    for account_id, account_gap, account_type \
               in self.account_definition_list:
      if not account_id in account_module.objectIds():
        account = account_module.newContent(id=account_id)
        account.setGap(account_gap)
        account.setAccountType(account_type)
        portal.portal_workflow.doActionFor(account, 'validate_action')
79 80 81 82 83 84
    invoice_rule = portal.portal_rules.new_invoice_transaction_simulation_rule
    if invoice_rule.getValidationState() == 'validated':
      invoice_rule.invalidate()
    invoice_rule.deleteContent(list(invoice_rule.contentIds(filter={'portal_type':['Predicate', 'Accounting Rule Cell']})))
    transaction.commit()
    self.tic()
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    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 =
                   ['destination_region/region/%s' % self.default_region ],
      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'
    )
    product_line_predicate.immediateReindexObject()
    region_predicate.immediateReindexObject()

    invoice_rule.updateMatrix()
    cell_list = invoice_rule.getCellValueList(base_id='movement')
    self.assertEquals(len(cell_list),1)
    cell = cell_list[0]

    for line_id, line_source_id, line_destination_id, line_ratio in \
        self.transaction_line_definition_list:
      line = cell.newContent(id=line_id,
          portal_type='Accounting Transaction Line', quantity=line_ratio,
          resource_value=resource,
          source_value=account_module[line_source_id],
          destination_value=account_module[line_destination_id])

    invoice_rule.validate()
    transaction.commit()
    self.tic()
120 121

  def validateNewRules(self):
122
    # create an Order Rule document.
123
    portal_rules = self.portal.portal_rules
124
    new_order_rule = filter(
125 126
      lambda x:x.title == 'New Default Order Root Simulation Rule',
      portal_rules.objectValues(portal_type='Order Root Simulation Rule'))[0]
127 128 129
    if new_order_rule.getValidationState() != 'validated':
      new_order_rule.validate()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
130
  def _acceptDecisionQuantity(self, document):
Jérome Perrin's avatar
Jérome Perrin committed
131 132
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(document)
133
    quantity_solver_decision = filter(
134
      lambda x:x.getCausalityValue().getTestedProperty()=='quantity',
135
      solver_process.contentValues())[0]
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
136
    # use Quantity Accept Solver.
Jérome Perrin's avatar
Jérome Perrin committed
137
    quantity_solver_decision.setSolverValue(self.portal.portal_solvers['Accept Solver'])
138 139 140
    # configure for Accept Solver.
    kw = {'tested_property_list':['quantity',]}
    quantity_solver_decision.updateConfiguration(**kw)
141 142 143
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
144 145 146
  def _acceptDivergenceOnInvoice(self, invoice, divergence_list):
    print invoice, divergence_list
    return self._acceptDecisionQuantity(invoice)
147

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
148
  def stepAcceptDecisionQuantity(self,sequence=None, sequence_list=None):
149
    """
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
150
    Solve quantity divergence by using solver tool.
151
    """
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
152 153
    packing_list = sequence.get('packing_list')
    self._acceptDecisionQuantity(packing_list)
154

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
155 156
  def stepAcceptDecisionQuantityInvoice(self, sequence=None,
                                        sequence_list=None):
157 158 159
    """
    Solve quantity divergence by using solver tool.
    """
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
160 161
    invoice = sequence.get('invoice')
    self._acceptDecisionQuantity(invoice)
162

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
163
  def stepAcceptDecisionResource(self,sequence=None, sequence_list=None):
164 165 166 167
    """
    Solve quantity divergence by using solver tool.
    """
    packing_list = sequence.get('packing_list')
Jérome Perrin's avatar
Jérome Perrin committed
168 169
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
170 171 172
    resource_solver_decision = filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='resource',
      solver_process.contentValues())[0]
173
    # use Resource Replacement Solver.
Jérome Perrin's avatar
Jérome Perrin committed
174
    resource_solver_decision.setSolverValue(self.portal.portal_solvers['Accept Solver'])
175 176 177
    # configure for Accept Solver.
    kw = {'tested_property_list':['resource',]}
    resource_solver_decision.updateConfiguration(**kw)
178
    solver_process.buildTargetSolverList()
179 180
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
181
  def stepSplitAndDeferPackingList(self, sequence=None, sequence_list=None):
182 183 184 185
    """
      Do the split and defer action
    """
    packing_list = sequence.get('packing_list')
Jérome Perrin's avatar
Jérome Perrin committed
186 187
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
188 189 190
    quantity_solver_decision = filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='quantity',
      solver_process.contentValues())[0]
191
    # use Quantity Split Solver.
Jérome Perrin's avatar
Jérome Perrin committed
192
    quantity_solver_decision.setSolverValue(self.portal.portal_solvers['Quantity Split Solver'])
193
    # configure for Quantity Split Solver.
194
    kw = {'delivery_solver':'FIFO Delivery Solver',
195 196
          'start_date':self.datetime + 15,
          'stop_date':self.datetime + 25}
197 198
    quantity_solver_decision.updateConfiguration(**kw)
    solver_process.buildTargetSolverList()
199
    solver_process.solve()
200 201 202 203 204 205 206 207 208 209 210 211 212 213
    # build split deliveries manually. XXX ad-hoc
    previous_tag = None
    for delivery_builder in packing_list.getBuilderList():
      this_builder_tag = '%s_split_%s' % (packing_list.getPath(),
                                          delivery_builder.getId())
      after_tag = []
      if previous_tag:
        after_tag.append(previous_tag)
      delivery_builder.activate(
        after_method_id=('solve',
                         'immediateReindexObject',
                         'recursiveImmediateReindexObject',), # XXX too brutal.
        after_tag=after_tag,
        ).build(explanation_uid=packing_list.getCausalityValue().getUid())
214

215 216 217 218
  def _adoptPrevisionQuantity(self, packing_list):
    """
    Solve quantity divergence by using solver tool.
    """
Jérome Perrin's avatar
Jérome Perrin committed
219 220
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
221 222 223 224
    quantity_solver_decision = filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='quantity',
      solver_process.contentValues())[0]
    # use Quantity Adoption Solver.
Jérome Perrin's avatar
Jérome Perrin committed
225
    quantity_solver_decision.setSolverValue(self.portal.portal_solvers['Adopt Solver'])
226 227 228
    # configure for Adopt Solver.
    kw = {'tested_property_list':['quantity',]}
    quantity_solver_decision.updateConfiguration(**kw)
229 230 231
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
232 233 234 235 236 237 238 239 240
  def _adoptDivergenceOnInvoice(self, invoice, divergence_list):
    print invoice, divergence_list
    return self._adoptPrevisionQuantity(invoice)

  def _adoptDivergenceOnPackingList(self, packing_list, divergence_list):
    print packing_list, divergence_list
    return self._adoptPrevisionQuantity(packing_list)

  def stepAdoptPrevisionQuantity(self,sequence=None, sequence_list=None):
241 242 243 244 245 246 247
    """
    Solve quantity divergence by using solver tool.
    """
    packing_list = sequence.get('packing_list')
    self._adoptPrevisionQuantity(packing_list)

  def stepNewPackingListAdoptPrevisionQuantity(self, sequence=None,
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
248
                                               sequence_list=None):
249 250 251 252 253 254
    """
    Solve quantity divergence by using solver tool.
    """
    packing_list = sequence.get('new_packing_list')
    self._adoptPrevisionQuantity(packing_list)

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
255
  def stepAdoptPrevisionResource(self,sequence=None, sequence_list=None):
256 257 258 259
    """
    Solve resource divergence by using solver tool.
    """
    packing_list = sequence.get('packing_list')
Jérome Perrin's avatar
Jérome Perrin committed
260 261
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
262 263 264 265
    resource_solver_decision = filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='resource',
      solver_process.contentValues())[0]
    # use Resource Adopt Solver.
Jérome Perrin's avatar
Jérome Perrin committed
266
    resource_solver_decision.setSolverValue(self.portal.portal_solvers['Adopt Solver'])
267 268 269
    # configure for Adopt Solver.
    kw = {'tested_property_list':['resource',]}
    resource_solver_decision.updateConfiguration(**kw)
270 271 272
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
273
  def stepCheckPackingListLineWithSameResource(self,sequence=None, sequence_list=None):
274 275 276 277 278 279 280 281 282 283
    """
      Look if the packing list has new previsions
    """
    old_packing_list_line = sequence.get('packing_list_line')
    packing_list_line = old_packing_list_line.aq_parent[str(int(old_packing_list_line.getId())-1)]
    resource = sequence.get('resource')
    for line in sequence.get('packing_list').getMovementList():
      self.assertEquals(line.getResourceValue(), resource)
      self.assertEquals(line.getQuantity(), self.default_quantity)
      self.assertEquals(line.getCausalityList(),
284
                        [x.getParentValue().getParentValue().getDelivery() for x in \
285 286
                         line.getDeliveryRelatedValueList()])

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
287
  def stepUnifyDestinationWithDecision(self,sequence=None, sequence_list=None):
288 289 290 291
    """
      Check if simulation movement are disconnected
    """
    packing_list = sequence.get('packing_list')
Jérome Perrin's avatar
Jérome Perrin committed
292 293
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
294 295 296 297
    for destination_solver_decision in filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='destination',
      solver_process.contentValues()):
      # use Destination Replacement Solver.
Jérome Perrin's avatar
Jérome Perrin committed
298
      destination_solver_decision.setSolverValue(self.portal.portal_solvers['Accept Solver'])
299 300 301
      # configure for Accept Solver.
      kw = {'tested_property_list':['destination',]}
      destination_solver_decision.updateConfiguration(**kw)
302 303 304
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
305
  def _unifyStartDateWithDecision(self, document):
Jérome Perrin's avatar
Jérome Perrin committed
306 307
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(document)
308 309 310 311
    for start_date_solver_decision in filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='start_date',
      solver_process.contentValues()):
      # use StartDate Replacement Solver.
Jérome Perrin's avatar
Jérome Perrin committed
312
      start_date_solver_decision.setSolverValue(self.portal.portal_solvers['Unify Solver'])
313 314 315
      # configure for Unify Solver.
      kw = {'tested_property_list':['start_date',],
            'value':document.getStartDate()}
316 317 318 319
      start_date_solver_decision.updateConfiguration(**kw)
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
320 321 322 323 324 325 326 327 328
  def stepUnifyStartDateWithDecision(self,sequence=None, sequence_list=None):
    packing_list = sequence.get('packing_list')
    self._unifyStartDateWithDecision(packing_list)

  def stepUnifyStartDateWithDecisionInvoice(self,sequence=None, sequence_list=None):
    invoice = sequence.get('invoice')
    self._unifyStartDateWithDecision(invoice)

  def stepUnifyStartDateWithPrevision(self,sequence=None, sequence_list=None):
329 330 331 332
    """
      Check if simulation movement are disconnected
    """
    packing_list = sequence.get('packing_list')
333 334 335
    applied_rule = sequence.get('applied_rule')
    simulation_line_list = applied_rule.objectValues()
    start_date = simulation_line_list[-1].getStartDate()
Jérome Perrin's avatar
Jérome Perrin committed
336 337
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
338 339 340 341
    for start_date_solver_decision in filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='start_date',
      solver_process.contentValues()):
      # use StartDate Replacement Solver.
Jérome Perrin's avatar
Jérome Perrin committed
342
      start_date_solver_decision.setSolverValue(self.portal.portal_solvers['Unify Solver'])
343 344 345
      # configure for Unify Solver.
      kw = {'tested_property_list':['start_date',],
            'value':start_date}
346
      start_date_solver_decision.updateConfiguration(**kw)
347 348 349
    solver_process.buildTargetSolverList()
    solver_process.solve()

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
350
  def stepCheckPackingListLineWithDifferentResource(self,sequence=None, sequence_list=None):
351 352 353 354 355 356 357 358
    """
      Look if the packing list has new previsions
    """
    packing_list_line = sequence.get('packing_list_line')
    new_resource = sequence.get('resource')
    self.assertEquals(packing_list_line.getQuantity(), self.default_quantity*2)
    self.assertEquals(packing_list_line.getResourceValue(), new_resource)
    simulation_line_list = packing_list_line.getDeliveryRelatedValueList()
359
    order_line_list = sum([x.getParentValue().getParentValue().getDeliveryList() for x in simulation_line_list], [])
360 361 362
    self.assertEquals(sorted(packing_list_line.getCausalityList()),
                      sorted(order_line_list))

363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
  def stepCheckSimulationMovementHasRecordedQuantity(self, sequence=None,
                                                     sequence_list=None):
    movement_list = sequence.get('packing_list').objectValues(
      portal_type=self.packing_list_line_portal_type)
    self._checkRecordedProperty(movement_list, 'quantity', True)

  def stepCheckSimulationMovementHasNoRecordedQuantity(self, sequence=None,
                                                       sequence_list=None):
    movement_list = sequence.get('packing_list').objectValues(
      portal_type=self.packing_list_line_portal_type)
    self._checkRecordedProperty(movement_list, 'quantity', False)

  def stepCheckSimulationMovementHasRecordedResource(self, sequence=None,
                                                     sequence_list=None):
    movement_list = sequence.get('packing_list').objectValues(
      portal_type=self.packing_list_line_portal_type)
    self._checkRecordedProperty(movement_list, 'resource', True)

  def stepCheckSimulationMovementHasNoRecordedResource(self, sequence=None,
                                                       sequence_list=None):
    movement_list = sequence.get('packing_list').objectValues(
      portal_type=self.packing_list_line_portal_type)
    self._checkRecordedProperty(movement_list, 'resource', False)

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
387 388 389 390
class TestERP5Simulation(TestERP5SimulationMixin, ERP5TypeTestCase):
  run_all_test = 1
  quiet = 0

391 392
  def afterSetUp(self):
    TestERP5SimulationMixin.afterSetUp(self)
393 394
    new_delivery_rule = self.portal.portal_rules.new_delivery_simulation_rule
    new_delivery_rule['quantity_tester'].edit(quantity=None,
395 396 397 398
                                           quantity_range_max=2,
                                           quantity_range_min=-1)

  def beforeTearDown(self):
399 400
    new_delivery_rule = self.portal.portal_rules.new_delivery_simulation_rule
    new_delivery_rule['quantity_tester'].edit(quantity=0,
401 402
                                           quantity_range_max=None,
                                           quantity_range_min=None)
403
    transaction.commit()
404
    TestERP5SimulationMixin.beforeTearDown(self)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435

  def _modifyPackingListLineQuantity(self, sequence=None,
      sequence_list=None, delta=0.0):
    """
    Set a increased quantity on packing list lines
    """
    packing_list = sequence.get('packing_list')
    quantity = self.default_quantity + delta
    sequence.edit(line_quantity=quantity)
    for packing_list_line in packing_list.objectValues(
        portal_type=self.packing_list_line_portal_type):
      packing_list_line.edit(quantity=quantity)
    sequence.edit(last_delta=delta)

  def stepIncreasePackingListLineQuantity2(self, sequence=None,
      sequence_list=None, **kw):
    return self._modifyPackingListLineQuantity(sequence, sequence_list, 2.0)

  def stepDecreasePackingListLineQuantity1(self, sequence=None,
      sequence_list=None, **kw):
    return self._modifyPackingListLineQuantity(sequence, sequence_list, -1.0)

  def stepDecreasePackingListLineQuantity10(self, sequence=None,
      sequence_list=None, **kw):
    return self._modifyPackingListLineQuantity(sequence, sequence_list, -10.0)

  def stepSplitAndDeferPackingList(self, sequence=None, sequence_list=None, **kw):
    """
      Do the split and defer action
    """
    packing_list = sequence.get('packing_list')
Jérome Perrin's avatar
Jérome Perrin committed
436 437
    solver_process_tool = self.portal.portal_solver_processes
    solver_process = solver_process_tool.newSolverProcess(packing_list)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
438 439 440 441 442
    sequence.edit(solver_process=solver_process)
    quantity_solver_decision = filter(
      lambda x:x.getCausalityValue().getTestedProperty()=='quantity',
      solver_process.contentValues())[0]
    # use Quantity Split Solver.
Jérome Perrin's avatar
Jérome Perrin committed
443 444
    quantity_solver_decision.setSolverValue(
        self.portal.portal_solvers['Quantity Split Solver'])
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
445
    # configure for Quantity Split Solver.
446
    kw = {'delivery_solver':'FIFO Delivery Solver',
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
447 448 449
          'start_date':packing_list.getStartDate() + 10}
    quantity_solver_decision.updateConfiguration(**kw)
    solver_process.buildTargetSolverList()
Jérome Perrin's avatar
Jérome Perrin committed
450

Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
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 486 487 488 489 490 491 492 493 494 495 496 497
    solver_process.solve()
    # build split deliveries manually. XXX ad-hoc
    previous_tag = None
    for delivery_builder in packing_list.getBuilderList():
      this_builder_tag = '%s_split_%s' % (packing_list.getPath(),
                                          delivery_builder.getId())
      after_tag = []
      if previous_tag:
        after_tag.append(previous_tag)
      delivery_builder.activate(
        after_method_id=('solve',
                         'immediateReindexObject',
                         'recursiveImmediateReindexObject',), # XXX too brutal.
        after_tag=after_tag,
        ).build(explanation_uid=packing_list.getCausalityValue().getUid())

  def stepCheckPackingListSplitted(self, sequence=None, sequence_list=None, **kw):
    """
      Test if packing list was splitted
    """
    order = sequence.get('order')
    packing_list_list = order.getCausalityRelatedValueList(
                               portal_type=self.packing_list_portal_type)
    self.assertEquals(2,len(packing_list_list))
    packing_list1 = None
    packing_list2 = None
    for packing_list in packing_list_list:
      if packing_list.getUid() == sequence.get('packing_list').getUid():
        packing_list1 = packing_list
      else:
        packing_list2 = packing_list
    sequence.edit(new_packing_list=packing_list2)
    for line in packing_list1.objectValues(
          portal_type= self.packing_list_line_portal_type):
      self.assertEquals(self.default_quantity-10,line.getQuantity())
    for line in packing_list2.objectValues(
          portal_type= self.packing_list_line_portal_type):
      self.assertEquals(10,line.getQuantity())

  def _checkSolverState(self, sequence=None, sequence_list=None,
                        state='solved'):
    """
      Check if target solvers' state.
    """
    solver_process = sequence.get('solver_process')
    for solver in solver_process.objectValues(
      portal_type=self.portal.getPortalTargetSolverTypeList()):
498
      self.assertEquals(state, solver.getValidationState())
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550

  def stepCheckSolverIsSolving(self, sequence=None, sequence_list=None, **kw):
    """
      Check if all target solvers have 'solving' state.
    """
    self._checkSolverState(sequence, sequence_list, 'solving')

  def stepCheckSolverIsSolved(self, sequence=None, sequence_list=None, **kw):
    """
      Check if all target solvers have 'solved' state.
    """
    self._checkSolverState(sequence, sequence_list, 'solved')

  def test_01_splitAndDefer(self, quiet=quiet, run=run_all_test):
    """
      Change the quantity on an delivery line, then
      see if the packing list is divergent and then
      split and defer the packing list
    """
    if not run: return
    sequence_list = SequenceList()

    # Test with a simply order without cell
    sequence_string = self.default_sequence + '\
                      stepIncreasePackingListLineQuantity2 \
                      stepCheckPackingListIsCalculating \
                      stepTic \
                      stepCheckPackingListIsNotDivergent \
                      stepCheckPackingListIsSolved \
                      stepDecreasePackingListLineQuantity1 \
                      stepCheckPackingListIsCalculating \
                      stepTic \
                      stepCheckPackingListIsNotDivergent \
                      stepCheckPackingListIsSolved \
                      stepDecreasePackingListLineQuantity10 \
                      stepCheckPackingListIsCalculating \
                      stepTic \
                      stepCheckPackingListIsDiverged \
                      stepSplitAndDeferPackingList \
                      stepCheckSolverIsSolving \
                      stepTic \
                      stepCheckPackingListSplitted \
                      stepCheckPackingListIsSolved \
                      stepCheckSolverIsSolved \
                      '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self, quiet=quiet)

class TestERP5SimulationPackingList(TestERP5SimulationMixin, TestPackingList):
  pass

551
for failing_method in [
552 553 554 555
  # This test does not work as it is because of the different behaviour of
  # Adopt Solver.
  'test_05d_SimulationChangeResourceOnOneSimulationMovementForMergedLine',

556 557 558 559 560 561 562
  # Those tests currently fail because they are making assertions on an applied
  # rule which with the new simulation structure is not the same as in the
  # original test packing list
  'test_06_SimulationChangeStartDate',
  'test_07_SimulationChangeStartDateWithTwoOrderLine',
  'test_07a_SimulationChangeStartDateWithTwoOrderLine',
  
563 564 565 566
  ]:
  setattr(TestERP5SimulationPackingList, failing_method,
          expectedFailure(getattr(TestERP5SimulationPackingList, failing_method)))
        
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
567
class TestERP5SimulationInvoice(TestERP5SimulationMixin, TestSaleInvoice):
568 569 570 571 572 573 574 575 576 577 578 579 580 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
  quiet = TestSaleInvoice.quiet

  def test_09_InvoiceChangeStartDateFail(self, quiet=quiet):
    """
    Change the start_date of a Invoice Line,
    check that the invoice is divergent,
    then accept decision, and check Packing list is *not* divergent,
    because Unify Solver does not propagage the change to the upper
    simulation movement.
    """
    if not quiet:
      self.logMessage('Invoice Change Sart Date')
    sequence = self.PACKING_LIST_DEFAULT_SEQUENCE + \
    """
    stepSetReadyPackingList
    stepTic
    stepStartPackingList
    stepCheckInvoicingRule
    stepCheckInvoiceTransactionRule
    stepTic
    stepCheckInvoiceBuilding

    stepChangeInvoiceStartDate
    stepCheckInvoiceIsDivergent
    stepCheckInvoiceIsCalculating
    stepTic
    stepCheckInvoiceIsDiverged
    stepUnifyStartDateWithDecisionInvoice
    stepTic

    stepCheckInvoiceNotSplitted
    stepCheckInvoiceIsNotDivergent
    stepCheckInvoiceIsSolved

    stepCheckPackingListIsNotDivergent
    stepCheckPackingListIsSolved
    stepCheckInvoiceTransactionRule

    stepRebuildAndCheckNothingIsCreated
    stepCheckInvoicesConsistency
    """
    self.playSequence(sequence, quiet=quiet)
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
610

611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
class TestAutomaticSolvingPackingList(TestERP5SimulationMixin, TestPackingListMixin,
                                      ERP5TypeTestCase):
  quiet = 0

  def afterSetUp(self, quiet=1, run=1):
    TestERP5SimulationMixin.afterSetUp(self)
    solver_process_type_info = self.portal.portal_types['Solver Process']
    self.original_allowed_content_types = solver_process_type_info.getTypeAllowedContentTypeList()
    self.added_target_solver_list = []

  def beforeTearDown(self, quiet=1, run=1):
    self.portal.portal_rules.new_delivery_simulation_rule.quantity_tester.edit(
      solver=())
    solver_process_type_info = self.portal.portal_types['Solver Process']
    solver_process_type_info.setTypeAllowedContentTypeList(self.original_allowed_content_types)
    self.portal.portal_solvers.manage_delObjects(self.added_target_solver_list)
627 628
    transaction.commit()
    self.tic()
629 630 631 632 633 634 635 636 637 638 639 640 641
    TestERP5SimulationMixin.beforeTearDown(self)

  @UnrestrictedMethod
  def _setUpTargetSolver(self, solver_id, solver_class, tested_property_list):
    solver_tool = self.portal.portal_solvers
    solver = solver_tool.newContent(
      portal_type='Solver Type',
      id=solver_id,
      tested_property_list=tested_property_list,
      automatic_solver=1,
      type_factory_method_id='add%s' % solver_class,
      type_group_list=('target_solver',),
    )
642 643 644
    solver.setCriterion(property='portal_type',
                        identity=['Simulation Movement',])
    solver.setCriterionProperty('portal_type')
645 646 647 648 649 650 651 652 653
    solver_process_type_info = self.portal.portal_types['Solver Process']
    solver_process_type_info.setTypeAllowedContentTypeList(
      solver_process_type_info.getTypeAllowedContentTypeList() + \
      [solver_id]
    )
    (default_chain, chain_dict) = getChainByType(self.portal)
    chain_dict['chain_%s' % solver_id] = 'solver_workflow'
    self.portal.portal_workflow.manage_changeWorkflows(default_chain,
                                                       props=chain_dict)
654
    self.portal.portal_caches.clearAllCache()
655 656 657 658 659 660 661 662
    self.added_target_solver_list.append(solver_id)

  def stepSetUpAutomaticQuantityAcceptSolver(self, sequence=None, sequence_list=None):
    self._setUpTargetSolver('Automatic Quantity Accept Solver',
                            'AcceptSolver', ('quantity',))
    self.portal.portal_rules.new_delivery_simulation_rule.quantity_tester.edit(
      solver=('portal_solvers/Automatic Quantity Accept Solver',))

663 664 665 666 667 668
  def stepSetUpAutomaticQuantityAdoptSolver(self, sequence=None, sequence_list=None):
    self._setUpTargetSolver('Automatic Quantity Adopt Solver',
                            'AdoptSolver', ('quantity',))
    self.portal.portal_rules.new_delivery_simulation_rule.quantity_tester.edit(
      solver=('portal_solvers/Automatic Quantity Adopt Solver',))

669 670 671
  def test_01_PackingListDecreaseQuantity(self, quiet=quiet):
    """
      Change the quantity on an delivery line, then
672 673
      see if the packing list is solved automatically
      with accept solver.
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    """
    sequence_list = SequenceList()

    # Test with a simply order without cell
    sequence_string = '\
                      stepSetUpAutomaticQuantityAcceptSolver \
                      ' + self.default_sequence + '\
                      stepDecreasePackingListLineQuantity \
                      stepCheckPackingListIsCalculating \
                      stepTic \
                      stepCheckPackingListIsSolved \
                      '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self, quiet=quiet)

690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710
  def test_02_PackingListDecreaseQuantity(self, quiet=quiet):
    """
      Change the quantity on an delivery line, then
      see if the packing list is solved automatically
      with adopt solver.
    """
    sequence_list = SequenceList()

    # Test with a simply order without cell
    sequence_string = '\
                      stepSetUpAutomaticQuantityAdoptSolver \
                      ' + self.default_sequence + '\
                      stepDecreasePackingListLineQuantity \
                      stepCheckPackingListIsCalculating \
                      stepTic \
                      stepCheckPackingListIsSolved \
                      '
    sequence_list.addSequenceString(sequence_string)

    sequence_list.play(self, quiet=quiet)

711 712 713
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestERP5Simulation))
714
  suite.addTest(unittest.makeSuite(TestERP5SimulationPackingList))
Kazuhiko Shiozaki's avatar
Kazuhiko Shiozaki committed
715
  suite.addTest(unittest.makeSuite(TestERP5SimulationInvoice))
716
  suite.addTest(unittest.makeSuite(TestAutomaticSolvingPackingList))
717
  return suite