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

TODO:
Fabien Morin's avatar
Fabien Morin committed
32
  - review naming of new methods
33 34 35 36 37
  - in the test test_04_paySheetCalculation, add sub_object (annotation_line, 
  ratio_line and payment conditioni), and verify that before the script 
  'PaySheetTransaction_applyModel' is called, subobjects are not in the 
  paysheet, and after that there are copied in.
  - use ratio settings and test it (there is a method getRatioQuantityList, see
Fabien Morin's avatar
Fabien Morin committed
38
  the file Document/PaySheetTransaction.py)
39 40 41 42
  - test with bonus which participate on the base_salary and see if the 
  contribution are applied on the real base_salary or on the base_salary + bonus
  (it should).

Fabien Morin's avatar
Fabien Morin committed
43 44 45
WARNING: 
  - current API naming may change although model should be stable.

46 47 48 49 50
"""

from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
from AccessControl.SecurityManagement import newSecurityManager
from Testing import ZopeTestCase
51
from DateTime import DateTime
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
from Acquisition import aq_parent

class TestPayrollMixin(ERP5TypeTestCase):

  paysheet_model_portal_type        = 'Pay Sheet Model'
  paysheet_model_line_portal_type   = 'Pay Sheet Model Line'
  paysheet_transaction_portal_type  = 'Pay Sheet Transaction'
  paysheet_line_portal_type         = 'Pay Sheet Line'
  payroll_service_portal_type       = 'Payroll Service'
  currency_portal_type              = 'Currency'
  person_portal_type                = 'Person'
  organisation_portal_type          = 'Organisation'


  default_region                    = 'europe/west/france'
  france_settings_forfait           = 'france/forfait'
  france_settings_slice_a           = 'france/tranche_a'
  france_settings_slice_b           = 'france/tranche_b'
  france_settings_slice_c           = 'france/tranche_c'
  tax_category_employer_share       = 'employer_share'
  tax_category_employee_share       = 'employee_share'
  base_amount_deductible_tax        = 'deductible_tax'
  base_amount_non_deductible_tax    = 'deductible_tax'
  base_amount_bonus                 = 'bonus'
  base_amount_base_salary           = 'base_salary'
  grade_worker                      = 'worker'
  grade_engineer                    = 'engineer'

  plafond = 2682.0

  model = None
  model_id                          = 'model_one'
  model_title                       = 'Model One'
  person_id                         = 'one'
  person_title                      = 'One'
  person_career_grade               = 'worker'
  organisation_id                   = 'company_one'
  organisation_title                = 'Company One'
  variation_settings_category_list  = ['salary_range/france',]
  price_currency                    = 'currency_module/EUR'

  def getTitle(self):
    return "Payroll"

  def afterSetUp(self):
    """Prepare the test."""
    self.portal = self.getPortal()
    self.organisation_module = self.portal.organisation_module
    self.person_module = self.portal.person_module
    self.payroll_service_module = self.portal.payroll_service_module
102
    self.paysheet_model_module = self.portal.paysheet_model_module
103 104 105
    self.createCategories()
    self.createCurrencies()

106 107 108
    self.model = self.createModel(self.model_id, self.model_title,
        self.person_id, self.person_title, self.person_career_grade,
        self.organisation_id, self.organisation_title,
109 110 111 112 113 114 115 116
        self.variation_settings_category_list, self.price_currency)

    self.login()

    # creation of payroll services
    self.urssaf_id = 'sickness_insurance'
    self.labour_id = 'labour'

117 118
    self.urssaf_slice_list = ['salary_range/'+self.france_settings_slice_a,
                              'salary_range/'+self.france_settings_slice_b,
119 120 121 122 123 124 125 126 127
                              'salary_range/'+self.france_settings_slice_c]

    self.urssaf_share_list = ['tax_category/'+self.tax_category_employee_share,
                              'tax_category/'+self.tax_category_employer_share]

    self.salary_slice_list = ['salary_range/'+self.france_settings_forfait,]
    self.salary_share_list = ['tax_category/'+self.tax_category_employee_share,]


128 129 130
    payroll_service_organisation = self.createOrganisation(id='urssaf',
                                                           title='URSSAF')
    self.urssaf=self.createPayrollService(id=self.urssaf_id,
131
        title='State Insurance',
132
        organisation=payroll_service_organisation,
133
        base_amount_list=['deductible_tax',],
134
        product_line='state_insurance',
135 136 137 138
        variation_base_category_list=['tax_category', 'salary_range'],
        variation_category_list=self.urssaf_slice_list + \
                                self.urssaf_share_list)

139
    self.labour=self.createPayrollService(id=self.labour_id,
140
        title='Labour',
141
        organisation=None,
142
        product_line='labour',
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        base_amount_list=['base_salary', 'gross_salary'],
        variation_base_category_list=['tax_category', 'salary_range'],
        variation_category_list=self.salary_slice_list +\
                                self.salary_share_list)

  def _safeTic(self):
    """Like tic, but swallowing errors, usefull for teardown"""
    try:
      get_transaction().commit()
      self.tic()
    except RuntimeError:
      pass

  def beforeTearDown(self):
    """Clear everything for next test."""
    self._safeTic()
    for module in [ 'organisation_module',
                    'person_module',
                    'currency_module',
                    'payroll_service_module',
                    'paysheet_model_module',
                    'accounting_module']:
      folder = getattr(self.getPortal(), module, None)
      if folder:
        [x.unindexObject() for x in folder.objectValues()]
        self._safeTic()
        folder.manage_delObjects([x.getId() for x in folder.objectValues()])
    self._safeTic()
    # cancel remaining messages
    activity_tool = self.getPortal().portal_activities
    for message in activity_tool.getMessageList():
      activity_tool.manageCancel(message.object_path, message.method_id)
      ZopeTestCase._print('\nCancelling active message %s.%s()\n'
                          % (message.object_path, message.method_id) )
    get_transaction().commit()

  def login(self, quiet=0, run=1):
    uf = self.getPortal().acl_users
    uf._doAddUser('admin', 'admin', ['Manager', 'Assignee', 'Assignor',
                               'Associate', 'Auditor', 'Author'], [])
    user = uf.getUserById('admin').__of__(uf)
    newSecurityManager(None, user)

  def createCategories(self):
    """Create the categories for our test. """
    # create categories
    for cat_string in self.getNeededCategoryList() :
      base_cat = cat_string.split("/")[0]
      # if base_cat not exist, create it
      if getattr(self.getPortal().portal_categories, base_cat, None) == None:
        self.getPortal().portal_categories.newContent(\
                                          portal_type='Base Category',
                                          id=base_cat)
        get_transaction().commit()
        self.tic()
      path = self.getPortal().portal_categories[base_cat]
      for cat in cat_string.split("/")[1:] :
        if not cat in path.objectIds() :
          path = path.newContent(
                    portal_type='Category',
                    id=cat,
                    title=cat.replace('_', ' ').title(),)
        else:
          path = path[cat]
    get_transaction().commit()
    self.tic()
    # check categories have been created
    for cat_string in self.getNeededCategoryList() :
      self.assertNotEquals(None,
                self.getCategoryTool().restrictedTraverse(cat_string),
                cat_string)

  def getNeededCategoryList(self):
    """return a list of categories that should be created."""
    return ('region/%s' % self.default_region,
            'salary_range/%s' % self.france_settings_forfait,
            'salary_range/%s' % self.france_settings_slice_a,
            'salary_range/%s' % self.france_settings_slice_b,
            'salary_range/%s' % self.france_settings_slice_c,
            'tax_category/%s' % self.tax_category_employer_share,
            'tax_category/%s' % self.tax_category_employee_share,
            'base_amount/%s' % self.base_amount_deductible_tax,
            'base_amount/%s' % self.base_amount_non_deductible_tax,
            'base_amount/%s' % self.base_amount_bonus,
            'base_amount/%s' % self.base_amount_base_salary,
            'grade/%s' % self.grade_worker,
            'grade/%s' % self.grade_engineer,
           )

  def createCurrencies(self):
    """Create some currencies.
234
    This script will reuse existing currencies, because we want currency ids
235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    to be stable, as we use them as categories.
    """
    currency_module = self.getCurrencyModule()
    if not hasattr(currency_module, 'EUR'):
      self.EUR = currency_module.newContent(
          portal_type = self.currency_portal_type,
          reference = "EUR", id = "EUR", base_unit_quantity=0.001 )
      self.USD = currency_module.newContent(
          portal_type = self.currency_portal_type,
          reference = "USD", id = "USD" )
      self.YEN = currency_module.newContent(
          portal_type = self.currency_portal_type,
          reference = "YEN", id = "YEN" )
      get_transaction().commit()
      self.tic()
    else:
      self.EUR = currency_module.EUR
      self.USD = currency_module.USD
      self.YEN = currency_module.YEN

  def getBusinessTemplateList(self):
    """ """
257 258
    return ('erp5_base', 'erp5_pdm', 'erp5_trade', 'erp5_accounting',
            'erp5_payroll',)
259

260
  def createPerson(self, id='one', title='One',
261 262 263 264 265 266 267 268
      career_subordination_value=None, career_grade=None, **kw):
    """
      Create some Pesons so that we have something to feed.
    """
    person_module = self.portal.getDefaultModule(portal_type=\
                                                 self.person_portal_type)
    if hasattr(person_module, id):
      person_module.manage_delObjects([id])
269
    person = person_module.newContent(portal_type=self.person_portal_type,
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
                                      id=id)
    person.edit(
        title=title,
        career_subordination_value=career_subordination_value,
        career_grade=career_grade,
               )
    get_transaction().commit()
    self.tic()
    return person

  def createOrganisation(self, id='company_one', title='Company One', **kw):
    if hasattr(self.organisation_module, id):
      self.organisation_module.manage_delObjects([id])
    organisation = self.organisation_module.newContent( \
                                   portal_type=self.organisation_portal_type,
                                   id=id,
                                   title=title)
    get_transaction().commit()
    self.tic()
    return organisation

291
  def createPayrollService(self, id='', title='', organisation='',
292
      base_amount_list=None, variation_base_category_list=None,
293
      variation_category_list=None, product_line=None, **kw):
294 295 296 297
    payroll_service_portal_type = 'Payroll Service'
    payroll_service_module = self.portal.getDefaultModule(\
                                    portal_type=payroll_service_portal_type)

298
    if base_amount_list == None:
299
      base_amount_list=[]
300
    if variation_category_list == None:
301
      variation_category_list=[]
302
    if variation_base_category_list == None:
303 304 305 306 307
      variation_category_list=[]
    if hasattr(payroll_service_module, id):
      payroll_service_module.manage_delObjects([id])

    payroll_service = payroll_service_module.newContent(\
308
        title=title,
309 310 311 312
        portal_type                  = self.payroll_service_portal_type,
        id                           = id,
        source_value                 = organisation,
        quantity_unit                = 'time/month',
313
        product_line                 = product_line,
314 315 316 317 318 319 320
        base_amount_list             = base_amount_list)
    payroll_service.setVariationBaseCategoryList(variation_base_category_list)
    payroll_service.setVariationCategoryList(variation_category_list)
    get_transaction().commit()
    self.tic()
    return payroll_service

321 322
  def createModel(self, id, title='', person_id='',
      person_title='', person_career_grade='',
323 324 325 326 327 328 329 330 331 332
      organisation_id='', organisation_title='',
      variation_settings_category_list=None,
      price_currency=''):
    """
      Create a model
    """
    if variation_settings_category_list == None:
      variation_settings_category_list = []

    organisation = self.createOrganisation(organisation_id, organisation_title)
333
    person = self.createPerson(id=person_id, title=person_title,
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
                               career_subordination_value=organisation,
                               career_grade=person_career_grade)

    if hasattr(self.paysheet_model_module, id):
      self.paysheet_model_module.manage_delObjects([id])
    paysheet_model = self.paysheet_model_module.newContent( \
                                portal_type=self.paysheet_model_portal_type,
                                id=id)
    paysheet_model.edit(\
        title=title,
        variation_settings_category_list=variation_settings_category_list,
        destination_section_value=organisation,
        source_section_value=person,)
    paysheet_model.setPriceCurrency(price_currency)
    get_transaction().commit()
    self.tic()

    return paysheet_model

  def addSlice(self, model, slice, min_value, max_value, base_id='cell'):
    '''
      add a new slice in the model
    '''
357
    slice = model.newCell(slice, portal_type='Pay Sheet Model Slice',
358
        base_id=base_id)
359 360 361 362 363
    slice.setQuantityRangeMax(max_value)
    slice.setQuantityRangeMin(min_value)
    get_transaction().commit()
    self.tic()
    return slice
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

  def addAllSlices(self, model):
    '''
      create all usefull slices with min and max values
    '''
    model.updateCellRange(base_id='cell')
    slice_list = []
    slice_list.append(self.addSlice(model, 'salary_range/%s' % \
        self.france_settings_forfait, 0, 9999999999999))
    slice_list.append(self.addSlice(model, 'salary_range/%s' % \
        self.france_settings_slice_a, 0, self.plafond))
    slice_list.append(self.addSlice(model, 'salary_range/%s' % \
        self.france_settings_slice_b, self.plafond, self.plafond*4))
    slice_list.append(self.addSlice(model, 'salary_range/%s' % \
        self.france_settings_slice_c, self.plafond*4, self.plafond*8))
    return slice_list

381
  def createModelLine(self, model, id, variation_category_list,
382 383 384
      resource, slice_list, share_list, values, editable=False,
      base_amount_list=['base_salary']):
    '''
385
      test the function addModelLine and test if the model line has been
386 387
      well created.
      explaination for values :
388 389 390 391
      if slice_list is ('slice_a', 'slice_b') and share list is ('employer',
      'employee') and if you want to put 100 % of 1000 for slice_a for the
      employee and employer, and 50% of the base_application for slice_b
      employer and and 2000 for slice_b employee, the value list will look
392 393 394 395 396 397
      like this :
      values = [[[1000, 1], [1000, 1]], [[2000, None], [None, 0.5]]]

      next, two representations to well understand :
      
       'employee_share', 'employer_share'
398
      [[  1470, None  ], [  2100, None  ]]
399 400 401 402 403 404 405
       'salary_range/france/forfait'

    'employee_share',  'employer_share'   'employee_share',  'employer_share'
[ [   None, 0.01   ], [   None, 0.02   ],[   None, 0.01  ], [   None, 0.02  ] ]
'salary_range/france/tranche_a''salary_range/france/tranche_b'
    '''
    
406
    # verify if category used in this model line are selected in the resource
407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    resource_list = resource.getVariationCategoryList(base=1)
    msg='%r != %r' % (resource_list, variation_category_list)
    for i in variation_category_list:
      self.failUnless(i in resource_list, msg)

    if hasattr(model, id):
      model.manage_delObjects([id])
    model_line = model.newContent(\
        portal_type                  = self.paysheet_model_line_portal_type,
        id                           = id,
        resource_value               = resource,
        source_section_value         = model.getSourceSectionValue(),
        editable                     = editable,
        base_amount_list             = base_amount_list,
        variation_category_list      = variation_category_list,)
    get_transaction().commit()
    self.tic()

    # put values in Model Line cells
    model_line.updateCellRange(base_id='movement')
    for slice in slice_list:
      for share in share_list:
        cell = model_line.newCell(\
430
            share, slice, portal_type='Pay Sheet Cell', base_id='movement')
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
        cell.setMappedValuePropertyList(['quantity', 'price'])
        amount = values[share_list.index(share)][slice_list.index(slice)][0]
        percent = values[share_list.index(share)][slice_list.index(slice)][1]
        if amount != None:
          cell.setQuantity(amount)
        if percent != None:
          cell.setPrice(percent)
        get_transaction().commit()
        self.tic()

    return model_line

  def createPaySheet(self, model, id='my_paysheet'):
    '''
      create a Pay Sheet with the model specialisation
    '''
    paysheet_module = self.portal.getDefaultModule(\
                            portal_type=self.paysheet_transaction_portal_type)
    if hasattr(paysheet_module, id):
      paysheet_module.manage_delObjects([id])
    paysheet = paysheet_module.newContent(\
        portal_type               = self.paysheet_transaction_portal_type,
        id                        = id,
        title                     = id,
        specialise_value          = model,
        source_section_value      = model.getSourceSectionValue(),
457 458 459
        destination_section_value = model.getDestinationSectionValue(),
        start_date                = DateTime(2008, 1, 1),
        stop_date                 = DateTime(2008, 1, 31),)
460 461 462 463 464 465 466
    paysheet.setPriceCurrency('currency_module/EUR')
    get_transaction().commit()
    self.tic()
    return paysheet

  def calculatePaySheet(self, paysheet):
    '''
467
      Calcul the given paysheet like if you hace click on the 'Calculation of
468 469 470 471
      the Pay Sheet Transaction' action button.
      XXX Editable line are not yet take into account
    '''
    paysheet_line_list = \
472
        paysheet.createPaySheetLineList()
473 474 475 476 477 478 479 480 481 482 483 484 485 486
    portal_type_list = ['Annotation Line', 'Payment Condition',
                        'Pay Sheet Model Ratio Line']
    paysheet.PaySheetTransaction_copySubObject(portal_type_list)
    get_transaction().commit()
    self.tic()
    return paysheet_line_list

  def assertEqualAmounts(self, pay_sheet_line, correct_value_slice_list,
      base_salary, i):
    slice_list = pay_sheet_line.getVariationCategoryList(\
        base_category_list='base_salary')
    share_list = pay_sheet_line.getVariationCategoryList(\
        base_category_list='tax_category')
    for slice in slice_list:
487
      for share in share_list:
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
        cell = pay_sheet_line.getCell(share, slice)
        value = cell.getQuantity()
        min_slice = correct_value_slice_list[i-1]
        max_slice = correct_value_slice_list[i]

        if base_salary <= max_slice:
          correct_value = base_salary - min_slice
        else:
          correct_value = max_slice - min_slice
        self.assertEqual(correct_value, value)
      i += 1


class TestPayroll(TestPayrollMixin):

503
  def test_01_modelCreation(self):
504 505 506 507 508 509 510 511 512 513 514
    '''
      test the function createModel and test if the model has been well created
    '''

    if hasattr(self.paysheet_model_module, self.model_id):
      self.paysheet_model_module.manage_delObjects([self.model_id])
    
    model_count_before_add = \
        len(self.paysheet_model_module.contentValues(portal_type=\
        self.paysheet_model_portal_type))

515 516 517 518 519 520 521 522
    self.model = self.createModel(self.model_id,
                                  self.model_title,
                                  self.person_id,
                                  self.person_title,
                                  self.person_career_grade,
                                  self.organisation_id,
                                  self.organisation_title,
                                  self.variation_settings_category_list,
523 524 525 526 527 528 529 530 531 532 533 534 535
                                  self.price_currency)

    model_count_after_add = \
        len(self.paysheet_model_module.contentValues(portal_type=\
        self.paysheet_model_portal_type))

    # check that the number of model_lines has been incremented
    self.assertEqual(model_count_before_add+1, model_count_after_add)

    #check model have been well created
    self.model = self.paysheet_model_module._getOb(self.model_id)
    self.assertEqual(self.model_id, self.model.getId())
    self.assertEqual(self.model_title, self.model.getTitle())
536 537
    self.assertEqual(self.organisation_title,
                     self.model.getDestinationSectionTitle())
538
    self.assertEqual(self.person_title, self.model.getSourceSectionTitle())
539 540
    self.assertEqual(self.variation_settings_category_list,
                     self.model.getVariationSettingsCategoryList(base=1))
541

542
  def test_02_addModelLine(self):
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    '''
      create a Model Line and test if it has been well created
    '''
    #model = self.createModel()
    self.addAllSlices(self.model)

    payroll_service_portal_type = 'Payroll Service'
    payroll_service_module = self.portal.getDefaultModule(\
                                    portal_type=payroll_service_portal_type)

    model_line_id = 'URSSAF'

    variation_category_list = self.urssaf_share_list + self.urssaf_slice_list

    model_line_count_before_add = len(self.model.contentValues(portal_type=\
        self.paysheet_model_line_portal_type))

560 561 562
    returned_model_line = self.createModelLine(model=self.model,
        id=model_line_id, variation_category_list=variation_category_list,
        resource=self.urssaf, share_list=self.urssaf_share_list,
563
        slice_list=self.urssaf_slice_list,
564
        values=[[[None, 0.01], [None, 0.02],[None, 0.03]], [[None, 0.04],
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
                 [None, 0.05], [None, 0.06]]])

    model_line_count_after_add = len(self.model.contentValues(portal_type=\
        self.paysheet_model_line_portal_type))

    # check that the number of model_lines has been incremented
    self.assertEqual(model_line_count_before_add+1, model_line_count_after_add)

    model_line = self.model._getOb(model_line_id)
    self.assertEqual(returned_model_line, model_line)
    self.assertEqual(model_line_id, model_line.getId())
    payroll_service_portal_type = 'Payroll Service'
    payroll_service_module = self.portal.getDefaultModule(\
        portal_type=payroll_service_portal_type)
    resource = payroll_service_module._getOb(self.urssaf_id)
    self.assertEqual(resource, model_line.getResourceValue())
581
    self.assertEqual(variation_category_list,
582 583
        model_line.getVariationCategoryList())

584
  def test_03_createPaySheet(self):
585 586 587 588 589 590 591 592 593 594 595
    '''
      create a Pay Sheet with the model specialisation and verify it was well
      created
    '''
    paysheet_id = 'my_paysheet'
    paysheet_returned = self.createPaySheet(self.model, paysheet_id)
    paysheet_module = self.portal.getDefaultModule(\
                          portal_type=self.paysheet_transaction_portal_type)
    paysheet = paysheet_module._getOb(paysheet_id)
    self.assertEqual(paysheet_returned, paysheet)
    self.assertEqual(paysheet_id, paysheet.getId())
596
    self.assertEqual(paysheet.getDestinationSectionTitle(),
597
        self.model.getDestinationSectionTitle())
598
    self.assertEqual(paysheet.getSourceSectionTitle(),
599
        self.model.getSourceSectionTitle())
600
    self.assertEqual(paysheet.getSpecialiseValue(), self.model)
601

602
  def test_04_paySheetCalculation(self):
603
    '''
604
      test if the scripts called by the 'Calculation of the Pay Sheet
605 606 607 608 609 610 611 612
      Transaction' action create the paysheet lines
    '''
    self.addAllSlices(self.model)

    model_line_id1 = 'urssaf'
    model_line_id2 = 'salary'
    base_salary = 10000

613 614
    urssaf_slice_list = [ 'salary_range/'+self.france_settings_slice_a,
                          'salary_range/'+self.france_settings_slice_b,
615 616
                          'salary_range/'+self.france_settings_slice_c]

617
    urssaf_share_list = [ 'tax_category/'+self.tax_category_employee_share,
618 619 620 621 622 623 624 625
                          'tax_category/'+self.tax_category_employer_share]

    salary_slice_list = ['salary_range/'+self.france_settings_forfait,]
    salary_share_list = ['tax_category/'+self.tax_category_employee_share,]

    variation_category_list_urssaf = urssaf_share_list + urssaf_slice_list
    variation_category_list_salary = salary_share_list + salary_slice_list

626
    model_line1 = self.createModelLine(model=self.model,
627
        id=model_line_id1,
628 629
        variation_category_list=variation_category_list_urssaf,
        resource=self.urssaf, share_list=self.urssaf_share_list,
630
        slice_list=self.urssaf_slice_list,
631
        values=[[[None, 0.01], [None, 0.02], [None, 0.03]], [[None, 0.04],
632 633
          [None, 0.05], [None, 0.06]]])

634
    model_line2 = self.createModelLine(model=self.model,
635
        id=model_line_id2,
636 637
        variation_category_list=variation_category_list_salary,
        resource=self.labour, share_list=self.salary_share_list,
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657
        slice_list=salary_slice_list, base_amount_list=[],
        values=[[[base_salary, None]],])

    pay_sheet_line_count = len(self.model.contentValues(portal_type=\
        self.paysheet_line_portal_type)) + 2 # because in this test, 2 lines
                                             # are added

    paysheet = self.createPaySheet(self.model)

    paysheet_line_count_before_calculation = \
        len(paysheet.contentValues(portal_type= \
        self.paysheet_line_portal_type))

    # calculate the pay sheet
    pay_sheet_line_list = self.calculatePaySheet(paysheet=paysheet)

    paysheet_line_count_after_calculation = \
        len(paysheet.contentValues(portal_type= \
        self.paysheet_line_portal_type))
    self.assertEqual(paysheet_line_count_before_calculation, 0)
658
    self.assertEqual(paysheet_line_count_after_calculation,
659 660 661 662 663 664 665
        pay_sheet_line_count)

    # check the amount in the cells of the created paysheet lines
    for pay_sheet_line in pay_sheet_line_list:
      service = pay_sheet_line.getResourceId()
      if service == self.urssaf_id:
        i = 1
666
        correct_value_slice_list = [0, self.plafond, self.plafond*4,
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
                                    self.plafond*8]

        self.assertEqualAmounts(pay_sheet_line, correct_value_slice_list,
            base_salary, i)

      elif service == self.labour_id:
        cell = pay_sheet_line.getCell(\
            'tax_category/'+ self.tax_category_employee_share,
            'salary_range/'+ self.france_settings_forfait)
        value = cell.getTotalPrice()
        self.assertEqual(base_salary, value)

      else:
        self.fail("Unknown service for line %s" % pay_sheet_line)

682
  def test_05_caculationWithANonNullMinimumValueSlice(self):
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697
    '''
      if the is only slice B (without previous slice A), test that
      the amount paid for this tax is correct
    '''
    self.addAllSlices(self.model)

    model_line_id1 = 'urssaf'
    model_line_id2 = 'salary'
    base_salary = 10000

    urssaf_slice_list = ['salary_range/'+self.france_settings_slice_b,]
    variation_category_list_urssaf = self.urssaf_share_list + urssaf_slice_list
    variation_category_list_salary = self.salary_share_list + \
        self.salary_slice_list

698
    model_line1 = self.createModelLine(model=self.model,
699
        id=model_line_id1,
700 701
        variation_category_list=variation_category_list_urssaf,
        resource=self.urssaf, share_list=self.urssaf_share_list,
702 703 704
        slice_list=urssaf_slice_list,
        values=[[[None, 0.03]], [[None, 0.04]],])

705
    model_line2 = self.createModelLine(model=self.model,
706
        id=model_line_id2,
707 708
        variation_category_list=variation_category_list_salary,
        resource=self.labour, share_list=self.salary_share_list,
709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        slice_list=self.salary_slice_list, base_amount_list=[],
        values=[[[base_salary, None]],])

    pay_sheet_line_count = len(self.model.contentValues(portal_type=\
        self.paysheet_line_portal_type)) + 2 # because in this test, 2 lines
                                             # are added

    paysheet = self.createPaySheet(self.model)

    paysheet_line_count_before_calculation = \
        len(paysheet.contentValues(portal_type= \
        self.paysheet_line_portal_type))

    # calculate the pay sheet
    pay_sheet_line_list = self.calculatePaySheet(paysheet=paysheet)

    paysheet_line_count_after_calculation = \
        len(paysheet.contentValues(portal_type= \
        self.paysheet_line_portal_type))
    self.assertEqual(paysheet_line_count_before_calculation, 0)
729
    self.assertEqual(paysheet_line_count_after_calculation,
730 731 732 733 734 735 736
        pay_sheet_line_count)
    
    # check the amount in the cells of the created paysheet lines
    for pay_sheet_line in pay_sheet_line_list:
      service = pay_sheet_line.getResourceId()
      if service == self.urssaf_id:
        i = 2 # the begining max slice
737
        correct_value_slice_list = [0, self.plafond, self.plafond*4,
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
                                    self.plafond*8]

        self.assertEqualAmounts(pay_sheet_line, correct_value_slice_list,
            base_salary, i)

      elif service == self.labour_id:
        cell = pay_sheet_line.getCell('tax_category/'+\
            self.tax_category_employee_share,
            'salary_range/'+ self.france_settings_forfait)
        value = cell.getTotalPrice()
        self.assertEqual(base_salary, value)

      else:
        self.fail("Unknown service for line %s" % pay_sheet_line)

753
  def test_06_model_inheritance(self):
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
    '''
      check that a model can inherite some datas from another
      the ineritance rules are the following :
       - a DATA could be a model_line, annotation_line, ratio_line or
         payement_condition (XXX -> this last one haven't yet reference)
       - a model_line, annotation_line and a ratio_line have a REFERENCE
       - a model can have some DATA's
       - a model can inherite from another, that's mean :
         o At the calculation step, each DATA of the parent model will be
           checked : the DATA with a REFERENCE that's already in the child 
           model will not entered in the calcul. The other will.
         o This will be repeated on each parent model and on each parent of 
           the parent model,... until there is no parent model to inherite 
           (or until a max loop number has been reached).
    '''
    # create 3 models
    model_employee = self.paysheet_model_module.newContent(id='model_employee',
        portal_type='Pay Sheet Model')

    model_company = self.paysheet_model_module.newContent(id='model_company',
        portal_type='Pay Sheet Model')

    model_country = self.paysheet_model_module.newContent(id='model_country',
        portal_type='Pay Sheet Model')

    # add some content in the models
    model_employee.newContent(id='over_time_duration',
                              title='over_time_duration',
782
                              portal_type='Annotation Line',
783 784 785 786
                              reference='over_time_duration',)

    model_company.newContent( id='worked_time_duration',
                              title='worked_time_duration',
787
                              portal_type='Annotation Line',
788 789 790 791
                              reference='worked_time_duration',)

    model_country.newContent( id='social_insurance',
                              title='social_insurance',
792
                              portal_type='Annotation Line',
793 794 795 796 797 798 799 800
                              reference='social_insurance',)

    # inherite from each other
    model_employee.setSpecialiseValue(model_company)
    model_company.setSpecialiseValue(model_country)

    # return a list of data that should contain data from all model
    portal_type_list = ['Annotation Line', ]
801 802
    model_reference_dict = model_employee.getInheritanceModelReferenceDict(\
        portal_type_list=portal_type_list)
803 804 805 806 807 808 809


    # check data's are corrected
    number_of_different_references = []
    for model in model_reference_dict.keys():
      number_of_different_references.extend(model_reference_dict[model])

810
    self.assertEqual(len(number_of_different_references), 3) # here, there is
811 812 813 814
                                                # 3 differents annotation line

    # check the model number
    self.assertEqual(len(model_reference_dict), 3)
815
    self.assertEqual(model_reference_dict[model_employee.getRelativeUrl()],
816
        ['over_time_duration',])
817
    self.assertEqual(model_reference_dict[model_company.getRelativeUrl()],
818
        ['worked_time_duration',])
819
    self.assertEqual(model_reference_dict[model_country.getRelativeUrl()],
820 821 822 823 824
        ['social_insurance',])

    # check with more values on each model
    # employee :
    model_employee.newContent(id='1',
825
                              portal_type='Annotation Line',
826 827 828
                              reference='1',)
    # company :
    model_company.newContent( id='1',
829
                              portal_type='Annotation Line',
830 831
                              reference='1',)
    model_company.newContent( id='2',
832
                              portal_type='Annotation Line',
833 834 835
                              reference='2',)
    # country :
    model_country.newContent( id='1',
836
                              portal_type='Annotation Line',
837 838
                              reference='1',)
    model_country.newContent( id='2',
839
                              portal_type='Annotation Line',
840 841
                              reference='2',)
    model_country.newContent( id='3',
842
                              portal_type='Annotation Line',
843 844
                              reference='3',)
    model_country.newContent( id='4',
845
                              portal_type='Annotation Line',
846 847 848 849 850 851
                              reference='4',)

    # return a list of data that should contain data from all model
    portal_type_list = ['Annotation Line', ]
    model_reference_dict = {}
    model_reference_dict = model_employee.getInheritanceModelReferenceDict(\
852
        portal_type_list=portal_type_list)
853 854 855 856 857 858 859 860

    # check that if a reference is already present in the model_employee,
    # and the model_company contain a data with the same one, the data used at
    # the calculation step is the model_employee data.
    number_of_different_references = []
    for model in model_reference_dict.keys():
      number_of_different_references.extend(model_reference_dict[model])

861
    self.assertEqual(len(number_of_different_references), 7) # here, there is
862 863 864
    # 4 differents annotation lines, and with the 3 ones have been had before
    # that's make 7 !

865 866


867 868
    # check the model number
    self.assertEqual(len(model_reference_dict), 3)
869
    self.assertEqual(set(model_reference_dict[model_employee.getRelativeUrl()]),
870
        set(['1', 'over_time_duration']))
871
    self.assertEqual(set(model_reference_dict[model_company.getRelativeUrl()]),
872
        set(['2', 'worked_time_duration']))
873
    self.assertEqual(set(model_reference_dict[model_country.getRelativeUrl()]),
874
        set(['3','4', 'social_insurance']))
875 876 877


    # same test with a multi model inheritance
878
    model_a = self.paysheet_model_module.newContent(id='model_a',
Fabien Morin's avatar
typo  
Fabien Morin committed
879
        title='model_a', portal_type='Pay Sheet Model')
880
    model_b = self.paysheet_model_module.newContent(id='model_b',
Fabien Morin's avatar
typo  
Fabien Morin committed
881
        title='model_b', portal_type='Pay Sheet Model')
882
    model_c = self.paysheet_model_module.newContent(id='model_c',
Fabien Morin's avatar
typo  
Fabien Morin committed
883
        title='model_c', portal_type='Pay Sheet Model')
884
    model_d = self.paysheet_model_module.newContent(id='model_d',
Fabien Morin's avatar
typo  
Fabien Morin committed
885
        title='model_d', portal_type='Pay Sheet Model')
886 887 888 889 890 891 892 893 894 895 896 897

    # check with more values on each model
    # a :
    model_a.newContent(id='5', portal_type='Annotation Line', reference='5')
    # b :
    model_b.newContent(id='5',portal_type='Annotation Line', reference='5')
    model_b.newContent(id='6',portal_type='Annotation Line', reference='6')
    # c :
    model_c.newContent(id='5', portal_type='Annotation Line', reference='5')
    model_c.newContent(id='6', portal_type='Annotation Line', reference='6')
    model_c.newContent(id='7', portal_type='Annotation Line', reference='7')
    model_c.newContent(id='8', portal_type='Annotation Line', reference='8')
898 899 900 901
    # d :
    model_d.newContent(id='5',portal_type='Annotation Line', reference='5')
    model_d.newContent(id='6',portal_type='Annotation Line', reference='6')

902 903 904

    # inherite from each other
    model_a.setSpecialiseValue(model_c)
905
    model_country.setSpecialiseValue(model_d)
906 907 908
    model_company.setSpecialiseValueList([model_country, model_a, model_b])
    model_employee.setSpecialiseValue(model_company)

Fabien Morin's avatar
typo  
Fabien Morin committed
909 910
    # get a list of data that should contain data from all model inheritance
    # dependances tree
911 912 913
    portal_type_list = ['Annotation Line', ]
    model_reference_dict = {}
    model_reference_dict = model_employee.getInheritanceModelReferenceDict(\
914
        portal_type_list=portal_type_list)
915 916 917 918 919 920 921


    # check data's are corrected
    number_of_different_references = []
    for model in model_reference_dict.keys():
      number_of_different_references.extend(model_reference_dict[model])

922
    self.assertEqual(len(number_of_different_references), 11) # here, there is
923 924 925 926
    # 8 differents annotation lines, and with the 3 ones have been had before
    # that's make 11 !
    
    # check the model number
927 928 929 930
    self.assertEqual(len(model_reference_dict), 6) # there is 7 model, but the
    # model_d is not take into account because it have no annotation line wich
    # are not already added by other models

931 932 933 934 935 936 937 938 939 940 941 942 943 944

    # the inheritance tree look like this :

#                                model_employee
#                           ('overtime_duration', '1')
#                                      |
#                                      |
#                                      |
#                                model_company
#                      ('worked_time_duration', '1', '2')
#                         /            |            \
#                        /             |             \
#                       /              |              \
#            model_country           model_a          model_b
Fabien Morin's avatar
typo  
Fabien Morin committed
945 946
#         ('social_insurance',       ('5',)          ('5', '6')
#          '1', '2', '3', '4')         |
947 948 949
#                  |                   |
#                  |                   |
#               model_d             model_c
Fabien Morin's avatar
typo  
Fabien Morin committed
950
#            ('5', '6')       ('5', '6', '7', '8')
951 952 953 954




Fabien Morin's avatar
typo  
Fabien Morin committed
955
    self.assertEqual(set(model_reference_dict[model_employee.getRelativeUrl()]),
956
        set(['1', 'over_time_duration']))
957
    self.assertEqual(set(model_reference_dict[model_company.getRelativeUrl()]),
958
        set(['2', 'worked_time_duration']))
959
    self.assertEqual(set(model_reference_dict[model_country.getRelativeUrl()]),
960
        set(['3','4', 'social_insurance']))
961 962
    self.assertEqual(model_reference_dict[model_a.getRelativeUrl()], ['5',])
    self.assertEqual(model_reference_dict[model_b.getRelativeUrl()], ['6',])
963
    self.assertEqual(set(model_reference_dict[model_c.getRelativeUrl()]),
964
        set(['7', '8']))
965

966

Fabien Morin's avatar
typo  
Fabien Morin committed
967
    # get all sub objects from a paysheet witch inherite of model_employee
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
    # create a paysheet
    id = 'inheritance_paysheet'
    paysheet_module = self.portal.getDefaultModule(\
                            portal_type=self.paysheet_transaction_portal_type)
    if hasattr(paysheet_module, id):
      paysheet_module.manage_delObjects([id])
    paysheet = paysheet_module.newContent(\
        portal_type               = self.paysheet_transaction_portal_type,
        id                        = id,
        title                     = id,
        specialise_value          = model_employee)

    # check heneritance works
    self.assertEqual(paysheet.getSpecialiseValue(), model_employee)

984
    # get a list of all this subObjects:
Fabien Morin's avatar
typo  
Fabien Morin committed
985
    sub_object_list = paysheet.getInheritedObjectValueList(portal_type_list)
986
    self.assertEqual(len(sub_object_list), 11)
987
    
988
  def test_07_model_getCell(self):
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
    '''
      Model objects have a overload method called getCell. This method first
      call the XMLMatrix.getCell and if the cell is not found, call
      getCell method in all it's inherited model until the cell is found or
      the cell have been searched on all inherited models.

      TODO : Currently, the method use a Depth-First Search algorithm, it will
      be better to use Breadth-First Search one.
      more about this on :
        - http://en.wikipedia.org/wiki/Breadth-first_search
        - http://en.wikipedia.org/wiki/Depth-first_search
    '''
    # create 3 models
    model_employee = self.paysheet_model_module.newContent(id='model_employee',
        portal_type='Pay Sheet Model')
    model_employee.edit(variation_settings_category_list=
        self.variation_settings_category_list)

    model_company = self.paysheet_model_module.newContent(id='model_company',
        portal_type='Pay Sheet Model')
    model_company.edit(variation_settings_category_list=
        self.variation_settings_category_list)

1012 1013 1014 1015 1016 1017
    model_company_alt = self.paysheet_model_module.newContent(
        id='model_company_alt',
        portal_type='Pay Sheet Model')
    model_company_alt.edit(variation_settings_category_list=
        self.variation_settings_category_list)

1018 1019 1020 1021 1022 1023 1024 1025
    model_country = self.paysheet_model_module.newContent(id='model_country',
        portal_type='Pay Sheet Model')
    model_country.edit(variation_settings_category_list=
        self.variation_settings_category_list)

    # add some cells in the models
    model_employee.updateCellRange(base_id='cell')
    self.addSlice(model_employee, 'salary_range/%s' % \
1026
        self.france_settings_slice_a, 0, 1)
1027 1028 1029

    model_company.updateCellRange(base_id='cell')
    self.addSlice(model_company, 'salary_range/%s' % \
1030
        self.france_settings_slice_b, 2, 3)
1031 1032 1033

    model_company_alt.updateCellRange(base_id='cell')
    self.addSlice(model_company_alt, 'salary_range/%s' % \
1034
        self.france_settings_forfait, 20, 30)
1035 1036 1037

    model_country.updateCellRange(base_id='cell')
    self.addSlice(model_country, 'salary_range/%s' % \
1038
        self.france_settings_slice_c, 4, 5)
1039 1040
    
    # inherite from each other
1041
    model_employee.setSpecialiseValueList((model_company, model_company_alt))
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051
    model_company.setSpecialiseValue(model_country)


    # check getCell results

    # check model_employee could access all cells
    cell_a = model_employee.getCell('salary_range/%s' % \
                        self.france_settings_slice_a)
    self.assertNotEqual(cell_a, None)
    self.assertEqual(cell_a.getQuantityRangeMin(), 0)
1052
    self.assertEqual(cell_a.getQuantityRangeMax(), 1)
1053 1054 1055 1056

    cell_b = model_employee.getCell('salary_range/%s' % \
                        self.france_settings_slice_b)
    self.assertNotEqual(cell_b, None)
1057 1058 1059 1060 1061 1062 1063 1064
    self.assertEqual(cell_b.getQuantityRangeMin(), 2)
    self.assertEqual(cell_b.getQuantityRangeMax(), 3)

    cell_forfait = model_employee.getCell('salary_range/%s' % \
                        self.france_settings_forfait)
    self.assertNotEqual(cell_forfait, None)
    self.assertEqual(cell_forfait.getQuantityRangeMin(), 20)
    self.assertEqual(cell_forfait.getQuantityRangeMax(), 30)
1065 1066 1067 1068

    cell_c = model_employee.getCell('salary_range/%s' % \
                        self.france_settings_slice_c)
    self.assertNotEqual(cell_c, None)
1069 1070
    self.assertEqual(cell_c.getQuantityRangeMin(), 4)
    self.assertEqual(cell_c.getQuantityRangeMax(), 5)
1071

1072 1073
    # check model_company and model_company_alt could access just it's own cell
    # and this of the country model
1074 1075 1076 1077 1078 1079 1080
    cell_a = model_company.getCell('salary_range/%s' % \
                        self.france_settings_slice_a)
    self.assertEqual(cell_a, None)

    cell_b = model_company.getCell('salary_range/%s' % \
                        self.france_settings_slice_b)
    self.assertNotEqual(cell_b, None)
1081 1082 1083
    self.assertEqual(cell_b.getQuantityRangeMin(), 2)
    self.assertEqual(cell_b.getQuantityRangeMax(), 3)

1084
    cell_forfait = model_company_alt.getCell('salary_range/%s' % \
1085 1086 1087 1088
                        self.france_settings_forfait)
    self.assertNotEqual(cell_forfait, None)
    self.assertEqual(cell_forfait.getQuantityRangeMin(), 20)
    self.assertEqual(cell_forfait.getQuantityRangeMax(), 30)
1089 1090 1091 1092

    cell_c = model_company.getCell('salary_range/%s' % \
                        self.france_settings_slice_c)
    self.assertNotEqual(cell_c, None)
1093 1094
    self.assertEqual(cell_c.getQuantityRangeMin(), 4)
    self.assertEqual(cell_c.getQuantityRangeMax(), 5)
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105

    # check model_country could access just it's own cell
    # model
    cell_a = model_country.getCell('salary_range/%s' % \
                        self.france_settings_slice_a)
    self.assertEqual(cell_a, None)

    cell_b = model_country.getCell('salary_range/%s' % \
                        self.france_settings_slice_b)
    self.assertEqual(cell_b, None)

1106 1107 1108 1109
    cell_forfait = model_country.getCell('salary_range/%s' % \
                        self.france_settings_forfait)
    self.assertEqual(cell_forfait, None)

1110 1111 1112
    cell_c = model_country.getCell('salary_range/%s' % \
                        self.france_settings_slice_c)
    self.assertNotEqual(cell_c, None)
1113 1114
    self.assertEqual(cell_c.getQuantityRangeMin(), 4)
    self.assertEqual(cell_c.getQuantityRangeMax(), 5)
1115

1116

1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154
  def test_PaySheetTransaction_getMovementList(self):
    # Tests PaySheetTransaction_getMovementList script
    pay_sheet = self.createPaySheet(self.model)
    # when pay sheet has no line, the script returns an empty list
    self.assertEquals(pay_sheet.PaySheetTransaction_getMovementList(), [])
    # we add a line, then it is returned in the list
    line = pay_sheet.newContent(portal_type='Pay Sheet Line')
    #self.assertEquals(1, len(pay_sheet.PaySheetTransaction_getMovementList()))

    # if the line has cells with different tax categories, new properties are
    # added to this line.
    line.setResourceValue(self.urssaf)
    line.setVariationCategoryList(['tax_category/employee_share',
                                   'tax_category/employer_share'])
    line.updateCellRange(base_id='movement')
    cell0 = line.newCell('tax_category/employee_share',
                         portal_type='Pay Sheet Cell', base_id='movement')
    cell0.setMappedValuePropertyList(['quantity', 'price'])
    cell0.setPrice(2)
    cell0.setQuantity(3)
    cell0.setTaxCategory('employee_share')
    cell1 = line.newCell('tax_category/employer_share',
                         portal_type='Pay Sheet Cell', base_id='movement')
    cell1.setMappedValuePropertyList(['quantity', 'price'])
    cell1.setPrice(4)
    cell1.setQuantity(5)
    cell1.setTaxCategory('employer_share')
    
    movement_list = pay_sheet.PaySheetTransaction_getMovementList()
    self.assertEquals(1, len(movement_list))
    movement = movement_list[0]
    self.assertEquals(2, movement.employee_share_price)
    self.assertEquals(3, movement.employee_share_quantity)
    self.assertEquals(2*3, movement.employee_share_total_price)
    self.assertEquals(4, movement.employer_share_price)
    self.assertEquals(5, movement.employer_share_quantity)
    self.assertEquals(4*5, movement.employer_share_total_price)

1155 1156 1157 1158 1159 1160 1161 1162
  def test_createEditablePaySheetLine(self):
    # test the creation of lines with editable lines in the model
    line = self.model.newContent(
          id='line',
          portal_type='Pay Sheet Model Line',
          resource_value=self.labour,
          variation_category_list=['tax_category/employee_share'],
          editable=1)
1163 1164 1165
    # Note that it is required that the editable line contains at least one
    # cell, to know which tax_category is used (employee share or employer
    # share).
1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
    line.updateCellRange(base_id='movement')
    cell = line.newCell('tax_category/employee_share',
                        portal_type='Pay Sheet Cell',
                        base_id='movement')
    cell.setMappedValuePropertyList(('quantity', 'price'))
    cell.setPrice(1)

    pay_sheet = self.createPaySheet(self.model)
    
    # PaySheetTransaction_getEditableObjectLineList is the script used as list
    # method to display editable lines in the dialog listbox
    editable_line_list = pay_sheet\
          .PaySheetTransaction_getEditableObjectLineList()
    self.assertEquals(1, len(editable_line_list))
    editable_line = editable_line_list[0]
    self.assertEquals(1, editable_line.employee_share_price)
    self.assertEquals(0, editable_line.employee_share_quantity)
    self.assertEquals('paysheet_model_module/model_one/line',
                      editable_line.model_line)
    self.assertEquals(None, editable_line.salary_range_relative_url)
    
    # PaySheetTransaction_createAllPaySheetLineList is the script used to create line and cells in the
    # paysheet using the listbox input
    pay_sheet.PaySheetTransaction_createAllPaySheetLineList(
      listbox=[dict(listbox_key='0',
                    employee_share_price=1,
                    employee_share_quantity=2,
                    model_line='paysheet_model_module/model_one/line',
                    salary_range_relative_url='',)])
    pay_sheet_line_list = pay_sheet.contentValues(portal_type='Pay Sheet Line')
    self.assertEquals(1, len(pay_sheet_line_list))
    pay_sheet_line = pay_sheet_line_list[0]
    self.assertEquals(self.labour, pay_sheet_line.getResourceValue())
    cell = pay_sheet_line.getCell('tax_category/employee_share',
                                  base_id='movement')
    self.assertNotEquals(None, cell)
    self.assertEquals(1, cell.getPrice())
    self.assertEquals(2, cell.getQuantity())
    
    # if the script is called again, previous content is erased.
    pay_sheet.PaySheetTransaction_createAllPaySheetLineList(
      listbox=[dict(listbox_key='0',
                    employee_share_price=0.5,
                    employee_share_quantity=10,
                    model_line='paysheet_model_module/model_one/line',
                    salary_range_relative_url='',)])
    pay_sheet_line_list = pay_sheet.contentValues(portal_type='Pay Sheet Line')
    self.assertEquals(1, len(pay_sheet_line_list))
    pay_sheet_line = pay_sheet_line_list[0]
    self.assertEquals(self.labour, pay_sheet_line.getResourceValue())
    cell = pay_sheet_line.getCell('tax_category/employee_share',
                                  base_id='movement')
    self.assertNotEquals(None, cell)
    self.assertEquals(0.5, cell.getPrice())
    self.assertEquals(10, cell.getQuantity())
    
    # If the user enters a null quantity, the line will not be created
    pay_sheet.PaySheetTransaction_createAllPaySheetLineList(
      listbox=[dict(listbox_key='0',
                    employee_share_price=1,
                    employee_share_quantity=0,
                    model_line='paysheet_model_module/model_one/line',
                    salary_range_relative_url='',)])
    pay_sheet_line_list = pay_sheet.contentValues(portal_type='Pay Sheet Line')
    self.assertEquals(0, len(pay_sheet_line_list))
  
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
  def test_paysheet_consistency(self):
    # minimal test for checkConsistency on a Pay Sheet Transaction and its
    # subdocuments (may have to be updated when we'll add more constraints).
    paysheet = self.createPaySheet(self.model)
    paysheet.setResourceValue(self.portal.currency_module.EUR)
    paysheet.newContent(portal_type='Pay Sheet Line')
    paysheet.newContent(portal_type='Pay Sheet Transaction Line')
    paysheet.newContent(portal_type='Annotation Line')
    paysheet.newContent(portal_type='Pay Sheet Model Ratio Line')
    paysheet.newContent(portal_type='Payment Condition')
    self.assertEquals([], paysheet.checkConsistency())
  
  def test_paysheet_model_consistency(self):
    # minimal test for checkConsistency on a Pay Sheet Model and its
    # subdocuments (may have to be updated when we'll add more constraints).
    model = self.model
    model.newContent(portal_type='Pay Sheet Model Line') # XXX this one needs a
                                                         # resource
    model.newContent(portal_type='Annotation Line')
    model.newContent(portal_type='Pay Sheet Model Ratio Line')
    model.newContent(portal_type='Payment Condition')
    self.assertEquals([], model.checkConsistency())

  def test_payroll_service_consistency(self):
    # minimal test for checkConsistency on a Payroll Service
    service = self.portal.payroll_service_module.newContent(
                           portal_type='Payroll Service')
    service.setBaseAmountList(('bonus', 'gross_salary'))
    service.setVariationBaseCategoryList(['tax_category'])
    service.setVariationCategoryList(['tax_category/employee_share'])
    self.assertEquals([], service.checkConsistency())
1263

Jérome Perrin's avatar
Jérome Perrin committed
1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282
  def test_apply_model(self):
    eur = self.portal.currency_module.EUR
    employee = self.portal.person_module.newContent(
                      portal_type='Person',
                      title='Employee')
    employer = self.portal.organisation_module.newContent(
                      portal_type='Organisation',
                      title='Employer')
    model = self.portal.paysheet_model_module.newContent(
                      portal_type='Pay Sheet Model',
                      source_section_value=employee,
                      destination_section_value=employer,
                      price_currency_value=eur,
                      payment_condition_payment_date=DateTime(2008, 1, 1),
                      work_time_annotation_line_quantity=10)
    paysheet = self.portal.accounting_module.newContent(
                      portal_type='Pay Sheet Transaction',
                      specialise_value=model)
    
1283
    paysheet.PaySheetTransaction_applyModel()
Jérome Perrin's avatar
Jérome Perrin committed
1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300
    self.assertEquals(employee, paysheet.getSourceSectionValue())
    self.assertEquals(employer, paysheet.getDestinationSectionValue())
    self.assertEquals(eur, paysheet.getResourceValue())
    self.assertEquals(eur, paysheet.getPriceCurrencyValue())
    self.assertEquals(DateTime(2008, 1, 1),
                      paysheet.getPaymentConditionPaymentDate())
    self.assertEquals(10, paysheet.getWorkTimeAnnotationLineQuantity())

    # if not found on the first model, values are searched recursivly in the
    # model hierarchy
    other_model = self.portal.paysheet_model_module.newContent(
                      portal_type='Pay Sheet Model',
                      specialise_value=model)
    paysheet = self.portal.accounting_module.newContent(
                      portal_type='Pay Sheet Transaction',
                      specialise_value=other_model)
    
1301
    paysheet.PaySheetTransaction_applyModel()
Jérome Perrin's avatar
Jérome Perrin committed
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
    self.assertEquals(employee, paysheet.getSourceSectionValue())
    self.assertEquals(employer, paysheet.getDestinationSectionValue())
    self.assertEquals(eur, paysheet.getResourceValue())
    self.assertEquals(eur, paysheet.getPriceCurrencyValue())
    self.assertEquals(DateTime(2008, 1, 1),
                      paysheet.getPaymentConditionPaymentDate())
    self.assertEquals(10, paysheet.getWorkTimeAnnotationLineQuantity())

    # applying twice does not copy subdocument twice
    self.assertEquals(2, len(paysheet.contentValues()))
1312
    paysheet.PaySheetTransaction_applyModel()
Jérome Perrin's avatar
Jérome Perrin committed
1313 1314
    self.assertEquals(2, len(paysheet.contentValues()))

1315

1316 1317 1318 1319 1320
import unittest
def test_suite():
  suite = unittest.TestSuite()
  suite.addTest(unittest.makeSuite(TestPayroll))
  return suite