TestERP5BankingMixin.py 61.3 KB
Newer Older
1
#############################################################################
2
#
3
# Copyright (c) 2006-2010 Nexedi SA and Contributors. All Rights Reserved.
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
#                    Aurelien Calonne <aurel@nexedi.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.
#
##############################################################################

from DateTime import DateTime
30
from Products.ERP5Type.tests.ERP5TypeTestCase import ERP5TypeTestCase
Aurel's avatar
Aurel committed
31 32 33

def isSameSet(a, b):
  for i in a:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
34 35
    if i not in b:
      return False
Aurel's avatar
Aurel committed
36
  for i in b:
Nicolas Dumazet's avatar
Nicolas Dumazet committed
37 38 39
    if i not in a:
      return False
  return len(a) == len(b)
Aurel's avatar
Aurel committed
40

41
class TestERP5BankingMixin(ERP5TypeTestCase):
42 43 44 45
  """
  Mixin class for unit test of banking operations
  """

46 47 48 49 50 51 52
  def getBusinessTemplateList(self):
    """
      Return the list of business templates we need to run the test.
      This method is called during the initialization of the unit test by
      the unit test framework in order to know which business templates
      need to be installed to run the test on.
    """
53 54
    return ('erp5_core_proxy_field_legacy',
            'erp5_base',
55
            'erp5_pdm',
56 57 58 59 60
            'erp5_trade',
            'erp5_accounting',
            'erp5_banking_core',
            'erp5_banking_inventory',
            'erp5_banking_cash',
61 62
            'erp5_banking_check',
    )
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

  def enableLightInstall(self):
    """
      Return if we should do a light install (1) or not (0)
      Light install variable is used at installation of categories in business template
      to know if we wrap the category or not, if 1 we don't use and installation is faster
    """
    return 1 # here we want a light install for a faster installation

  def enableActivityTool(self):
    """
      Return if we should create (1) or not (0) an activity tool
      This variable is used at the creation of the site to know if we use
      the activity tool or not
    """
    return 1 # here we want to use the activity tool

  def checkUserFolderType(self):
    """
      Check the type of user folder to let the test working with both NuxUserGroup and PAS.
    """
    self.user_folder = self.getUserFolder()
    self.PAS_installed = 0
    if self.user_folder.meta_type == 'Pluggable Auth Service':
      # we use PAS
      self.PAS_installed = 1

90
  def updateRoleMappings(self, portal_type_list=None):
91 92 93 94 95 96 97 98
    """Update the local roles in existing objects.
    """
    portal_catalog = self.portal.portal_catalog
    for portal_type in portal_type_list:
      for brain in portal_catalog(portal_type = portal_type):
        obj = brain.getObject()
        userdb_path, user_id = obj.getOwnerTuple()
        obj.assignRoleToSecurityGroup(user_name = user_id)
99

100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
  def assignPASRolesToUser(self, user_name, role_list):
    """
      Assign a list of roles to one user with PAS.
    """
    for role in role_list:
      if role not in self.user_folder.zodb_roles.listRoleIds():
        self.user_folder.zodb_roles.addRole(role)
      self.user_folder.zodb_roles.assignRoleToPrincipal(role, user_name)

  def createManagerAndLogin(self):
    """
      Create a simple user in user_folder with manager rights.
      This user will be used to initialize data in the method afterSetup
    """
    self.getUserFolder()._doAddUser('manager', '', ['Manager'], [])
    self.login('manager')

  def createERP5Users(self, user_dict):
    """
      Create all ERP5 users needed for the test.
      ERP5 user = Person object + Assignment object in erp5 person_module.
    """
    for user_login, user_data in user_dict.items():
      user_roles = user_data[0]
      # Create the Person.
125
      main_site = '/'.join(user_data[4].split('/')[0:2])
126
      person = self.person_module.newContent(id=user_login,
127 128
          portal_type='Person', reference=user_login, career_role="internal",
          site=main_site)
129 130 131
      # Create the Assignment.
      assignment = person.newContent( portal_type       = 'Assignment'
                                    , destination_value = user_data[1]
132 133
                                    , function          = "function/%s" %user_data[2]
                                    , group             = "group/%s" %user_data[3]
134
                                    , site              = "%s" %user_data[4]
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
                                    , start_date        = '01/01/1900'
                                    , stop_date         = '01/01/2900'
                                    )
      if self.PAS_installed and len(user_roles) > 0:
        # In the case of PAS, if we want global roles on user, we have to do it manually.
        self.assignPASRolesToUser(user_login, user_roles)
      elif not self.PAS_installed:
        # The user_folder counterpart of the erp5 user must be
        #   created manually in the case of NuxUserGroup.
        self.user_folder.userFolderAddUser( name     = user_login
                                          , password = ''
                                          , roles    = user_roles
                                          , domains  = []
                                          )
      # User assignment to security groups is also required, but is taken care of
      #   by the assignment workflow when NuxUserGroup is used and
      #   by ERP5Security PAS plugins in the context of PAS use.
      assignment.open()
153

154 155 156 157 158 159 160
    if self.PAS_installed:
      # reindexing is required for the security to work
      self.tic()



  def getUserFolder(self):
161
    return self.getPortal().acl_users
162 163

  def getPersonModule(self):
164
    return self.getPortal().person_module
165

166
  def getOrganisationModule(self):
167
    return self.getPortal().organisation_module
168

169
  def getCurrencyCashModule(self):
170
    return self.getPortal().currency_cash_module
171 172

  def getCashInventoryModule(self):
173
    return self.getPortal().cash_inventory_module
174 175

  def getBankAccountInventoryModule(self):
176
    return self.getPortal().bank_account_inventory_module
177

178
  def getCurrencyModule(self):
179
    return self.getPortal().currency_module
180

181
  def getCategoryTool(self):
182
    return self.getPortal().portal_categories
183

184
  def getWorkflowTool(self):
185
    return self.getPortal().portal_workflow
186

187
  def getSimulationTool(self):
188
    return self.getPortal().portal_simulation
189 190

  def getCheckPaymentModule(self):
191
    return self.getPortal().check_payment_module
192

193
  def getStopPaymentModule(self):
194
    return self.getPortal().stop_payment_module
195

196
  def getCheckDepositModule(self):
197
    return self.getPortal().check_deposit_module
198

199
  def getCheckbookModule(self):
200
    return self.getPortal().checkbook_module
201

202
  def getCheckbookModelModule(self):
203
    return self.getPortal().checkbook_model_module
204 205

  def getCheckbookReceptionModule(self):
206
    return self.getPortal().checkbook_reception_module
207 208

  def getCheckbookVaultTransferModule(self):
209
    return self.getPortal().checkbook_vault_transfer_module
210

Sebastien Robin's avatar
Sebastien Robin committed
211
  def getCheckbookUsualCashTransferModule(self):
212
    return self.getPortal().checkbook_usual_cash_transfer_module
Sebastien Robin's avatar
Sebastien Robin committed
213

214
  def getCheckbookDeliveryModule(self):
215
    return self.getPortal().checkbook_delivery_module
216

217
  def getCheckModule(self):
218
    return self.getPortal().check_module
219

220
  def getAccountingDateModule(self):
221
    return self.getPortal().accounting_date_module
222

223
  def getCounterDateModule(self):
224
    return self.getPortal().counter_date_module
225 226

  def getCounterModule(self):
227
    return self.getPortal().counter_module
228

229
  def getCashMovementModule(self):
230 231 232
    return self.getPortal().cash_movement_module

  def getCashMovementNewNotEmittedModule(self):
233
    return self.getPortal().cash_movement_new_not_emitted_module
234 235

  def getMonetaryReceptionModule(self):
236
    return self.getPortal().monetary_reception_module
237 238

  def getMonetaryIssueModule(self):
239
    return self.getPortal().monetary_issue_module
240 241

  def getAccountingCancellationModule(self):
242
    return self.getPortal().accounting_cancellation_module
243 244

  def getCashBalanceRegulationModule(self):
245
    return self.getPortal().cash_balance_regulation_module
246 247

  def getCashSortingModule(self):
248
    return self.getPortal().cash_sorting_module
249 250

  def getCashExchangeModule(self):
251
    return self.getPortal().cash_exchange_module
252 253

  def getCashToCurrencyPurchaseModule(self):
254
    return self.getPortal().cash_to_currency_purchase_module
255 256

  def getClassificationSurveyModule(self):
257
    return self.getPortal().classification_survey_module
258 259

  def getCounterRenderingModule(self):
260
    return self.getPortal().counter_rendering_module
261 262

  def getDestructionSurveyModule(self):
263
    return self.getPortal().destruction_survey_module
264 265

  def getForeignCashReceptionModule(self):
266
    return self.getPortal().foreign_cash_reception_module
267 268

  def getInternalMoneyDepositModule(self):
269
    return self.getPortal().internal_money_deposit_module
270 271

  def getInternalMoneyPaymentModule(self):
272
    return self.getPortal().internal_money_payment_module
273 274

  def getMonetaryDestructionModule(self):
275
    return self.getPortal().monetary_destruction_module
276 277

  def getMonetaryRecallModule(self):
278
    return self.getPortal().monetary_recall_module
279 280

  def getMonetarySurveyModule(self):
281
    return self.getPortal().monetary_survey_module
282 283

  def getMoneyDepositModule(self):
284
    return self.getPortal().money_deposit_module
285 286

  def getMoneyDepositRenderingModule(self):
287
    return self.getPortal().money_deposit_rendering_module
288 289

  def getMutilatedBanknoteModule(self):
290
    return self.getPortal().mutilated_banknote_module
291 292

  def getTravelerCheckPurchaseModule(self):
293
    return self.getPortal().traveler_check_purchase_module
294 295

  def getTravelerCheckSaleModule(self):
296
    return self.getPortal().traveler_check_sale_module
297 298

  def getUsualCashRenderingModule(self):
299
    return self.getPortal().usual_cash_rendering_module
300 301

  def getUsualCashTransferModule(self):
302
    return self.getPortal().usual_cash_transfer_module
303 304

  def getVaultTransferModule(self):
305
    return self.getPortal().vault_transfer_module
306

307
  def createCurrency(self, currency_list=(('EUR', 'Euro', 1/652., 1/650., 'USD'), ('USD', 'USD', 652, 650., 'EUR')), only_currency=False):
308
    # create the currency document for euro inside the currency module
309 310
    #currency_list = (('EUR', 'Euro', 1/650., 'USD'), ('USD', 'Dollar', 650., 'EUR'))
    # first create currency
311
    for currency_id, title, base_price, cell_price, price_currency in currency_list:
312 313
      currency = self.getCurrencyModule().newContent(id=currency_id, title=title, reference=currency_id)

314 315 316
    if only_currency:
      return
    
317
    # second, create exchange lines
318
    for currency_id, title, base_price, cell_price, price_currency in currency_list:
319 320
      currency = self.getCurrencyModule()[currency_id]
      exchange_line = None
321
      exchange_line = currency.newContent(portal_type='Currency Exchange Line',
Grégory Wisniewski's avatar
Grégory Wisniewski committed
322
                                          start_date='01/01/1900', stop_date='01/01/2900',
323
                                          base_price=base_price,
Aurel's avatar
Aurel committed
324 325 326
                                          currency_exchange_type_list=['currency_exchange_type/sale',
                                                                       'currency_exchange_type/purchase',
                                                                       'currency_exchange_type/transfer'],
327
                                          )
328
      exchange_line.setPriceCurrencyValue(self.getCurrencyModule()[price_currency])
329
      cell_list = exchange_line.objectValues()
Grégory Wisniewski's avatar
Grégory Wisniewski committed
330
      self.assertEquals(len(cell_list), 3)
331
      for cell in cell_list:
332
        cell.setBasePrice(cell_price)
333

334 335 336
      exchange_line.confirm()
      exchange_line.validate()

337
      
338

339
  def _createBanknotesAndCoins(self):
340 341 342 343 344 345
    """
    Create some banknotes and coins
    """
    # Define static values (only use prime numbers to prevent confusions like 2 * 6 == 3 * 4)
    # variation list is the list of years for banknotes and coins
    self.variation_list = ('variation/1992', 'variation/2003')
Grégory Wisniewski's avatar
Grégory Wisniewski committed
346
    self.usd_variation_list = ('variation/not_defined', )
347 348 349 350 351 352 353 354 355 356 357 358 359 360
    # quantity of banknotes of 10000 :
    self.quantity_10000 = {}
    # 2 banknotes of 10000 for the year 1992
    self.quantity_10000[self.variation_list[0]] = 2
    # 3 banknotes of 10000 for the year of 2003
    self.quantity_10000[self.variation_list[1]] = 3

    # quantity of coin of 200
    self.quantity_200 = {}
    # 5 coins of 200 for the year 1992
    self.quantity_200[self.variation_list[0]] = 5
    # 7 coins of 200 for the year 2003
    self.quantity_200[self.variation_list[1]] = 7

Sebastien Robin's avatar
Sebastien Robin committed
361 362 363 364 365 366 367
    # quantity of coin of 100
    self.quantity_100 = {}
    # 5 coins of 100 for the year 1992
    self.quantity_100[self.variation_list[0]] = 4
    # 7 coins of 100 for the year 2003
    self.quantity_100[self.variation_list[1]] = 6

368 369 370 371 372 373 374
    # quantity of banknotes of 5000
    self.quantity_5000 = {}
    # 11 banknotes of 5000 for hte year 1992
    self.quantity_5000[self.variation_list[0]] = 11
    # 13 banknotes of 5000 for the year 2003
    self.quantity_5000[self.variation_list[1]] = 13

375 376 377 378
    # quantity of usd banknote of 200
    self.quantity_usd_200 = {}
    # 2 banknotes of 200
    self.quantity_usd_200['variation/not_defined'] = 2
379 380 381 382
    # quantity of usd banknote of 100
    self.quantity_usd_100 = {}
    # 2 banknotes of 100
    self.quantity_usd_100['variation/not_defined'] = 2
383 384 385 386 387 388 389 390 391
    # quantity of usd banknote of 50
    self.quantity_usd_50 = {}
    # 3 banknotes of 50
    self.quantity_usd_50['variation/not_defined'] = 3
    # quantity of usd banknote of 20
    self.quantity_usd_20 = {}
    # 5 banknotes of 20
    self.quantity_usd_20['variation/not_defined'] = 5

392 393 394
    # Now create required category for banknotes and coin
    self.cash_status_base_category = getattr(self.category_tool, 'cash_status')
    # add the category valid in cash_status which define status of banknotes and coin
395 396 397 398 399 400 401 402
    self.cash_status_valid = self._maybeNewContent(self.cash_status_base_category, id='valid', portal_type='Category')
    self.cash_status_to_sort = self._maybeNewContent(self.cash_status_base_category, id='to_sort', portal_type='Category')
    self.cash_status_cancelled = self._maybeNewContent(self.cash_status_base_category, id='cancelled', portal_type='Category')
    self.cash_status_not_defined = self._maybeNewContent(self.cash_status_base_category, id='not_defined', portal_type='Category')
    self.cash_status_mutilated = self._maybeNewContent(self.cash_status_base_category, id='mutilated', portal_type='Category')
    self.cash_status_retired = self._maybeNewContent(self.cash_status_base_category, id='retired', portal_type='Category')
    self.cash_status_new_not_emitted = self._maybeNewContent(self.cash_status_base_category, id='new_not_emitted', portal_type='Category')
    self.cash_status_mixed = self._maybeNewContent(self.cash_status_base_category, id='mixed', portal_type='Category')
403

404 405
    self.emission_letter_base_category = getattr(self.category_tool, 'emission_letter')
    # add the category k in emission letter that will be used fo banknotes and coins
406 407 408 409 410 411
    self.emission_letter_p = self._maybeNewContent(self.emission_letter_base_category, id='p', portal_type='Category')
    self.emission_letter_s = self._maybeNewContent(self.emission_letter_base_category, id='s', portal_type='Category')
    self.emission_letter_b = self._maybeNewContent(self.emission_letter_base_category, id='b', portal_type='Category')
    self.emission_letter_k = self._maybeNewContent(self.emission_letter_base_category, id='k', portal_type='Category')
    self.emission_letter_mixed = self._maybeNewContent(self.emission_letter_base_category, id='mixed', portal_type='Category')
    self.emission_letter_not_defined = self._maybeNewContent(self.emission_letter_base_category, id='not_defined', portal_type='Category')
412 413 414

    self.variation_base_category = getattr(self.category_tool, 'variation')
    # add the category 1992 in variation
415
    self.variation_1992 = self._maybeNewContent(self.variation_base_category, id='1992', portal_type='Category')
416
    # add the category 2003 in variation
417
    self.variation_2003 = self._maybeNewContent(self.variation_base_category, id='2003', portal_type='Category')
418
    # add the category not_defined in variation
419
    self.variation_not_defined = self._maybeNewContent(self.variation_base_category, id='not_defined',
420
                                      portal_type='Category')
421

Aurel's avatar
Aurel committed
422 423 424
    # Now create required category for region and coin
    self.region_base_category = getattr(self.category_tool, 'region')
    # add the category valid in cash_status which define status of banknotes and coin
425 426
    self.region_france = self._maybeNewContent(self.region_base_category, id='france', title="France", portal_type='Category')
    self.region_spain = self._maybeNewContent(self.region_base_category, id='spain', title="Spain", portal_type='Category')
Aurel's avatar
Aurel committed
427

428 429 430 431
    # Create Resources Document (Banknotes & Coins)
    # get the currency cash module
    self.currency_cash_module = self.getCurrencyCashModule()
    # Create Resources Document (Banknotes & Coins)
432 433
    self.createCurrency()
    self.currency_1 = self.currency_module['EUR']
434
    # create document for banknote of 10000 euros from years 1992 and 2003
Aurel's avatar
Aurel committed
435 436 437
    self.billet_10000 = self.currency_cash_module.newContent(id='billet_10000',
         portal_type='Banknote', base_price=10000,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
438
         quantity_unit_value=self.unit)
439
    # create document for banknote of 500 euros from years 1992 and 2003
Aurel's avatar
Aurel committed
440 441 442
    self.billet_5000 = self.currency_cash_module.newContent(id='billet_5000',
         portal_type='Banknote', base_price=5000,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
443
         quantity_unit_value=self.unit)
444
    # create document for coin of 200 euros from years 1992 and 2003
Aurel's avatar
Aurel committed
445 446 447
    self.piece_200 = self.currency_cash_module.newContent(id='piece_200',
         portal_type='Coin', base_price=200,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
Sebastien Robin's avatar
Sebastien Robin committed
448 449
         quantity_unit_value=self.unit)
    # create document for coin of 200 euros from years 1992 and 2003
Aurel's avatar
Aurel committed
450 451 452
    self.piece_100 = self.currency_cash_module.newContent(id='piece_100',
         portal_type='Coin', base_price=100,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
453
         quantity_unit_value=self.unit)
454
    # create document for banknote of 200 euros from years 1992 and 2003
Aurel's avatar
Aurel committed
455 456 457
    self.billet_200 = self.currency_cash_module.newContent(id='billet_200',
         portal_type='Banknote', base_price=200,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
458
         quantity_unit_value=self.unit)
Sebastien Robin's avatar
Sebastien Robin committed
459 460 461 462 463
    # create document for banknote of 200 euros from years 1992 and 2003
    self.billet_100 = self.currency_cash_module.newContent(id='billet_100',
         portal_type='Banknote', base_price=100,
         price_currency_value=self.currency_1, variation_list=('1992', '2003'),
         quantity_unit_value=self.unit)
464
    # Create Resources Document (Banknotes & Coins) in USD
465
    self.currency_2 = self.currency_module['USD']
466
    # create document for banknote of 100 USD
467
    self.usd_billet_100 = self.currency_cash_module.newContent(id='usd_billet_100',
Aurel's avatar
Aurel committed
468
         portal_type='Banknote', base_price=100,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
469
         price_currency_value=self.currency_2, variation_list=('not_defined', ),
470
         quantity_unit_value=self.unit)
471 472 473
    # create document for banknote of 200 USD
    self.usd_billet_200 = self.currency_cash_module.newContent(id='usd_billet_200',
         portal_type='Banknote', base_price=200,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
474
         price_currency_value=self.currency_2, variation_list=('not_defined', ),
475
         quantity_unit_value=self.unit)
476
    # create document for banknote of 50 USD
Aurel's avatar
Aurel committed
477 478
    self.usd_billet_50 = self.currency_cash_module.newContent(id='usd_billet_50',
         portal_type='Banknote', base_price=50,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
479
         price_currency_value=self.currency_2, variation_list=('not_defined', ),
480 481
         quantity_unit_value=self.unit)
    # create document for banknote of 20 USD
Aurel's avatar
Aurel committed
482 483
    self.usd_billet_20 = self.currency_cash_module.newContent(id='usd_billet_20',
         portal_type='Banknote', base_price=20,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
484
         price_currency_value=self.currency_2, variation_list=('not_defined', ),
485
         quantity_unit_value=self.unit)
486

487 488 489 490 491 492 493
  def _maybeNewContent(self, container, id, **kw):
    try:
      result = container[id]
    except KeyError:
      result = container.newContent(id=id, **kw)
    return result

494
  def createFunctionGroupSiteCategory(self, no_site=0, site_list=None):
495 496 497
    """
    Create site group function category that can be used for security
    """
498
    if site_list is None:
499
      site_list = ["paris", 'madrid', 'siege']
500

501 502
    # add category unit in quantity_unit which is the unit that will be used for banknotes and coins
    self.variation_base_category = getattr(self.category_tool, 'quantity_unit')
503
    self.unit = self._maybeNewContent(self.variation_base_category, id='unit', title='Unit')
504

505
    self._maybeNewContent(self.category_tool.role, id='internal', portal_type='Category')
506

507
    # add category for currency_exchange_type
Grégory Wisniewski's avatar
Grégory Wisniewski committed
508
    self.currency_exchange_type = getattr(self.category_tool, 'currency_exchange_type')
509 510 511
    self._maybeNewContent(self.currency_exchange_type, id='sale')
    self._maybeNewContent(self.currency_exchange_type, id='purchase')
    self._maybeNewContent(self.currency_exchange_type, id='transfer')
512

513 514 515
    # get the base category function
    self.function_base_category = getattr(self.category_tool, 'function')
    # add category banking in function which will hold all functions neccessary in a bank (at least for this unit test)
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
    self.banking = self._maybeNewContent(self.function_base_category, id='banking', portal_type='Category', codification='BNK')
    self.caissier_principal = self._maybeNewContent(self.banking, id='caissier_principal', portal_type='Category', codification='CCP')
    self.controleur_caisse = self._maybeNewContent(self.banking, id='controleur_caisse', portal_type='Category', codification='CCT')
    self.void_function = self._maybeNewContent(self.banking, id='void_function', portal_type='Category', codification='VOID')
    self.gestionnaire_caisse_courante = self._maybeNewContent(self.banking, id='gestionnaire_caisse_courante', portal_type='Category', codification='CCO')
    self.gestionnaire_caveau = self._maybeNewContent(self.banking, id='gestionnaire_caveau', portal_type='Category', codification='CCV')
    self.caissier_particulier = self._maybeNewContent(self.banking, id='caissier_particulier', portal_type='Category', codification='CGU')
    self.controleur_caisse_courante = self._maybeNewContent(self.banking, id='controleur_caisse_courante', portal_type='Category', codification='CCC')
    self.controleur_caveau = self._maybeNewContent(self.banking, id='controleur_caveau', portal_type='Category', codification='CCA')
    self.comptable = self._maybeNewContent(self.banking, id='comptable', portal_type='Category', codification='FXF')
    self.commis_comptable = self._maybeNewContent(self.banking, id='commis_comptable', portal_type='Category', codification='CBM')
    self.commis_caisse = self._maybeNewContent(self.banking, id='commis_caisse', portal_type='Category', codification='CCM')
    self.chef_section_comptable = self._maybeNewContent(self.banking, id='chef_section_comptable', portal_type='Category', codification='CSB')
    self.chef_comptable = self._maybeNewContent(self.banking, id='chef_comptable', portal_type='Category', codification='CCB')
    self.chef_de_tri = self._maybeNewContent(self.banking, id='chef_de_tri', portal_type='Category', codification='CTR')
    self.chef_caisse = self._maybeNewContent(self.banking, id='chef_caisse', portal_type='Category', codification='CCP')
    self.chef_section = self._maybeNewContent(self.banking, id='chef_section', portal_type='Category', codification='FXS')
    self.chef_section_financier = self._maybeNewContent(self.banking, id='chef_section_financier', portal_type='Category', codification='FXA')
    self.financier_a = self._maybeNewContent(self.banking, id='financier_a', portal_type='Category', codification='FNA')
    self.financier_b = self._maybeNewContent(self.banking, id='financier_b', portal_type='Category', codification='FNB')
    self.chef_financier = self._maybeNewContent(self.banking, id='chef_financier', portal_type='Category', codification='FCF')
    self.admin_local = self._maybeNewContent(self.banking, id='administrateur_local', portal_type='Category', codification='ADL')
    self.agent_saisie_sref = self._maybeNewContent(self.banking, id='agent_saisie_sref', portal_type='Category', codification='SSREF')
    self.chef_sref = self._maybeNewContent(self.banking, id='chef_sref', portal_type='Category', codification='CSREF')
    self.analyste_sref = self._maybeNewContent(self.banking, id='analyste_sref', portal_type='Category', codification='ASREF')
    self.gestionnaire_devise_a = self._maybeNewContent(self.banking, id='gestionnaire_cours_devise_a', portal_type='Category', codification='GCA')
    self.gestionnaire_devise_b = self._maybeNewContent(self.banking, id='gestionnaire_cours_devise_b', portal_type='Category', codification='GCB')
    self.comptable_inter_site = self._maybeNewContent(self.banking, id='comptable_inter_site', portal_type='Category', codification='FXFIS')
544 545 546

    # get the base category group
    self.group_base_category = getattr(self.category_tool, 'group')
547
    self.baobab_group = self._maybeNewContent(self.group_base_category, id='baobab', portal_type='Category', codification='BAOBAB')
548 549 550
    # get the base category site
    self.site_base_category = getattr(self.category_tool, 'site')
    # add the category testsite in the category site which hold vaults situated in the bank
551
    self.testsite = self._maybeNewContent(self.site_base_category, id='testsite', portal_type='Category', codification='TEST')
552 553 554 555 556
    site_reference_from_codification_dict = {
      'P10': ('FR', '000', '11111', '000000000000', '25'),
      'S10': ('SP', '000', '11111', '000000000000', '08'),
      'HQ1': ('FR', '000', '11112', '000000000000', '69'),
    }
557
    site_region_from_codification_dict = {
558 559 560
      'P10': 'france', # paris
      'S10': 'spain',  # madrid
      'HQ1': 'france', # main
561
    }
562 563 564
    self.paris = self._maybeNewContent(self.testsite, id='paris', portal_type='Category', codification='P10',  vault_type='site')
    self.madrid = self._maybeNewContent(self.testsite, id='madrid', portal_type='Category', codification='S10',  vault_type='site')
    self.siege = self._maybeNewContent(self.site_base_category, id='siege', portal_type='Category', codification='HQ1',  vault_type='site')
565
    created_site_list = [self.paris, self.madrid, self.siege]
566 567 568

    self._createBanknotesAndCoins()

569
    if len(site_list) != 0:
570 571
      for site in site_list:
        if isinstance(site, tuple):
572
          container = self.site_base_category
573
          if len(site) > 2:
574 575 576
            for category_id in site[2].split('/'):
              contained = getattr(container, category_id, None)
              if contained is None:
577
                contained = self._maybeNewContent(container, id=category_id, portal_type='Category')
578
              container = contained
579
            if len(site) > 3:
580
              site_reference_from_codification_dict[site[1]] = site[3]
581 582
              if len(site) > 4:
                site_region_from_codification_dict[site[1]] = site[4]
583 584
          codification = site[1]
          site = site[0]
585
        if site not in ("paris", 'madrid', 'siege'):
586
          site = self._maybeNewContent(container, id=site, portal_type='Category',  codification=codification, vault_type='site')
587
          created_site_list.append(site)
588 589

    # Create organisation + bank account for each site category.
590 591
    organisation_module = self.organisation_module
    newContent = organisation_module.newContent
592 593
    for site in created_site_list:
      codification = site.getCodification()
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618
      organisation_id = 'site_%s' % (codification, )
      try:
        organisation_module[organisation_id]
      except KeyError:
        organisation = newContent(
          portal_type='Organisation',
          id=organisation_id,
          site=site.getRelativeUrl(),
          region=site_region_from_codification_dict.get(codification),
          group='baobab',
          role='internal',
          function='banking')
        site_reference = site_reference_from_codification_dict.get(codification)
        if site_reference is not None:
          self.createBankAccount(
            person=organisation,
            account_id='account_%s' % (codification, ),
            currency=self.currency_1,
            amount=0,
            bank_country_code=site_reference[0],
            bank_code=site_reference[1],
            branch=site_reference[2],
            bank_account_number=site_reference[3],
            bank_account_key=site_reference[4],
          )
619

620
    self.vault_type_base_category = getattr(self.category_tool, 'vault_type')
621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
    site_vault_type = self._maybeNewContent(self.vault_type_base_category, id='site')
    surface_vault_type = self._maybeNewContent(site_vault_type, 'surface')
    bi_vault_type = self._maybeNewContent(surface_vault_type, 'banque_interne')
    co_vault_type = self._maybeNewContent(surface_vault_type, 'caisse_courante')
    de_co_vault_type = self._maybeNewContent(co_vault_type, 'encaisse_des_devises')
    guichet_bi_vault_type = self._maybeNewContent(bi_vault_type, 'guichet')
    gp_vault_type = self._maybeNewContent(surface_vault_type, 'gros_paiement')
    guichet_gp_vault_type = self._maybeNewContent(gp_vault_type, 'guichet')
    gv_vault_type = self._maybeNewContent(surface_vault_type, 'gros_versement')
    guichet_gv_vault_type = self._maybeNewContent(gv_vault_type, 'guichet')
    op_vault_type = self._maybeNewContent(surface_vault_type, 'operations_diverses')
    guichet_op_vault_type = self._maybeNewContent(op_vault_type, 'guichet')
    caveau_vault_type = self._maybeNewContent(site_vault_type, 'caveau')
    auxiliaire_vault_type = self._maybeNewContent(caveau_vault_type, 'auxiliaire')
    self._maybeNewContent(auxiliaire_vault_type, 'auxiliaire_vault_type')
    self._maybeNewContent(auxiliaire_vault_type, 'encaisse_des_devises')
    externe = self._maybeNewContent(auxiliaire_vault_type, 'encaisse_des_externes')
    self._maybeNewContent(externe, 'transit')
    self._maybeNewContent(caveau_vault_type, 'reserve')
    serre = self._maybeNewContent(caveau_vault_type, 'serre')
    self._maybeNewContent(serre, 'transit')
    self._maybeNewContent(serre, 'retire')
    salle_tri = self._maybeNewContent(surface_vault_type, 'salle_tri')
644
      
645
    if not no_site:
646
      destination_site_list = [x.getId() for x in created_site_list]
647
      for c in created_site_list: #self.testsite.getCategoryChildValueList():
648 649 650
        # create bank structure for each agency
        site = c.getId()
        # surface
651 652 653 654 655 656
        surface = self._maybeNewContent(c, id='surface', portal_type='Category', codification='',  vault_type='site/surface')
        caisse_courante = self._maybeNewContent(surface, id='caisse_courante', portal_type='Category', codification='',  vault_type='site/surface/caisse_courante')
        self._maybeNewContent(caisse_courante, id='encaisse_des_billets_et_monnaies', portal_type='Category', codification='',  vault_type='site/surface/caisse_courante')
        self._maybeNewContent(caisse_courante, id='billets_mutiles', portal_type='Category', codification='',  vault_type='site/surface/caisse_courante')
        self._maybeNewContent(caisse_courante, id='billets_macules', portal_type='Category', codification='',  vault_type='site/surface/caisse_courante')
        encaisse_des_devises = self._maybeNewContent(caisse_courante, id='encaisse_des_devises', portal_type='Category', codification='',  vault_type='site/surface/caisse_courante/encaisse_des_devises')
657
        # create counter for surface
Sebastien Robin's avatar
Sebastien Robin committed
658
        for s in ['banque_interne', 'gros_versement', 'gros_paiement']:
659 660 661 662 663 664 665
          vault_codification = c.getCodification()
          if s == 'banque_interne':
            vault_codification += 'BI'
          elif s == 'gros_versement':
            vault_codification += 'GV'
          elif s == 'gros_paiement':
            vault_codification += 'GP'
666
          s = self._maybeNewContent(surface, id='%s' % (s, ), portal_type='Category', codification=vault_codification,  vault_type='site/surface/%s' % (s, ))
667
          for ss in ['guichet_1', 'guichet_2']:
668
            final_vault_codification = vault_codification + ss[-1]
669
            ss =  self._maybeNewContent(s, id='%s' % (ss, ), portal_type='Category', codification=final_vault_codification,  vault_type='site/surface/%s/guichet' % (s.getId(), ))
Grégory Wisniewski's avatar
Grégory Wisniewski committed
670
            for sss in ['encaisse_des_billets_et_monnaies']:
671
              sss =  self._maybeNewContent(ss, id='%s' % (sss, ), portal_type='Category', codification='',  vault_type='site/surface/%s/guichet' % (s.getId(), ))
672
              for ssss in ['entrante', 'sortante']:
673
                self._maybeNewContent(sss, id='%s' % (ssss, ), portal_type='Category', codification='',  vault_type='site/surface/%s/guichet' % (s.getId(), ))
Grégory Wisniewski's avatar
Grégory Wisniewski committed
674
            for sss in ['encaisse_des_devises']:
675
              sss =  self._maybeNewContent(ss, id='%s' % (sss, ), portal_type='Category', codification='',  vault_type='site/surface/%s/guichet' % (s.getId(), ))
676
              for currency in ['usd']:
677
                currency_cat = self._maybeNewContent(sss, id='%s' % (currency, ), portal_type='Category', codification='',  vault_type='site/surface/%s' % (ss.getId(), ))
678
                for ssss in ['entrante', 'sortante']:
679
                  self._maybeNewContent(currency_cat, id='%s' % (ssss, ), portal_type='Category', codification='',  vault_type='site/surface/%s/guichet' % (s.getId(), ))
680
        # create sort room
681
        salle_tri = self._maybeNewContent(surface, id='salle_tri', portal_type='Category', codification='',  vault_type='site/surface/salle_tri')
682
        for ss in ['encaisse_des_billets_et_monnaies', 'encaisse_des_billets_recus_pour_ventilation', 'encaisse_des_differences', 'encaisse_des_externes']:
683
          ss =  self._maybeNewContent(salle_tri, id='%s' % (ss, ), portal_type='Category', codification='',  vault_type='site/surface/salle_tri')
684
          if 'ventilation' in ss.getId():
685
            for country in destination_site_list:
686
              if country[0] != c.getCodification()[0]:
687
                self._maybeNewContent(ss, id='%s' % (country, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
688
        # caveau
689
        caveau =  self._maybeNewContent(c, id='caveau', portal_type='Category', codification='',  vault_type='site/caveau')
690
        for s in ['auxiliaire', 'reserve', 'serre']:
691
          s = self._maybeNewContent(caveau, id='%s' % (s, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s, ))
692
          if s.getId() == 'serre':
Grégory Wisniewski's avatar
Grégory Wisniewski committed
693
            for ss in ['encaisse_des_billets_neufs_non_emis', 'encaisse_des_billets_retires_de_la_circulation', 'encaisse_des_billets_detruits', 'encaisse_des_billets_neufs_non_emis_en_transit_allant_a']:
694
              ss =  self._maybeNewContent(s, id='%s' % (ss, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
695
              if 'transit' in ss.getId():
696
                for country in destination_site_list:
697
                  if country[0] != c.getCodification()[0]:
698
                    self._maybeNewContent(ss, id='%s' % (country, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
699 700 701

          else:
            for ss in ['encaisse_des_billets_et_monnaies', 'encaisse_des_externes',
Grégory Wisniewski's avatar
Grégory Wisniewski committed
702
                       'encaisse_des_billets_recus_pour_ventilation', 'encaisse_des_devises']:
703
              ss =  self._maybeNewContent(s, id='%s' % (ss, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
704
              if 'ventilation' in ss.getId():
705
                for country in destination_site_list:
706
                  if country[0] != c.getCodification()[0]:
707
                    self._maybeNewContent(ss, id='%s' % (country, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
708
              if 'devises' in ss.getId():
Grégory Wisniewski's avatar
Grégory Wisniewski committed
709
                for currency in ['eur', 'usd']:
710
                  self._maybeNewContent(ss, id='%s' % (currency, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (ss.getId(), ))
711
              if 'encaisse_des_externes' in ss.getId():
712
                self._maybeNewContent(ss, id='transit', portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
713 714 715
              #if ss.getId()=='encaisse_des_devises':
              #  for
            if s.getId() == 'auxiliaire':
716
              for ss in ['encaisse_des_billets_a_ventiler_et_a_detruire', 'encaisse_des_billets_ventiles_et_detruits', 'billets_detenus_par_des_tiers', 'encaisse_des_billets_recus_pour_ventilation_venant_de']:
717
                self._maybeNewContent(s, id='%s' % (ss, ), portal_type='Category', codification='',  vault_type='site/caveau/%s' % (s.getId(), ))
718 719
        # Create forreing currency entries in encaisse_des_devises.
        for currency in ['usd', ]:
720
          self._maybeNewContent(caisse_courante.encaisse_des_devises, id=currency, portal_type='Category', codification='', vault_type='site/surface/caisse_courante/encaisse_des_devises')
721

722 723
    return created_site_list

724 725
  def _openDate(self, date=None, site=None, id=None, open=True, container=None, 
                portal_type=None, force_check=0):
726 727
    if date is None:
      date = DateTime().Date()
728 729
    if not isinstance(date, str):
      date = date.Date()
730 731
    if site is None:
      site = self.testsite
732 733
    date_object = container.newContent(id=id, portal_type=portal_type,
                                       site_value = site, start_date = date)
734
    if open:
735
      if force_check and date_object.getPortalType() == 'Counter Date':
736 737 738 739 740
        self.workflow_tool.doActionFor(date_object, 'open_action', 
                                     wf_id='counter_date_workflow',
                                     your_check_date_is_today=0)
      else:
        date_object.open()
741
    setattr(self, id, date_object)
742
    date_object.assignRoleToSecurityGroup()
743 744 745 746 747 748 749

  def openAccountingDate(self, date=None, site=None, id='accounting_date_1', open=True):
    """
    open an accounting date for the given date
    by default use the current date
    """
    self._openDate(date=date, site=site, id=id, open=open, container=self.getAccountingDateModule(), portal_type='Accounting Date')
750

751
  def openCounterDate(self, date=None, site=None, id='counter_date_1', open=True, force_check=0):
752 753 754 755
    """
    open a couter date for the given date
    by default use the current date
    """
756 757 758 759
    self._openDate(date=date, site=site, id=id, open=open, 
                   container=self.getCounterDateModule(), 
                   portal_type='Counter Date',
                   force_check=force_check)
760

761
  def openCounter(self, site=None, id='counter_1'):
762 763 764 765
    """
    open a counter for the givent site
    """
    # create a counter
766
    counter_module = self.getCounterModule()
767 768
    while "guichet" not in site.getId():
      site = site.getParentValue()
769
    counter = counter_module.newContent(id=id, site_value=site)
770
    # open it
771
    counter.open()
772

Aurel's avatar
Aurel committed
773 774 775 776 777 778 779
  def closeCounterDate(self, id):
    """
    close the counter date
    """
    module = self.getCounterDateModule()
    counter_date = module[id]
    counter_date.close()
780 781 782 783 784 785 786

  def initDefaultVariable(self):
    """
    init some default variable use in all test
    """
    # the erp5 site
    self.portal = self.getPortal()
787

788 789 790 791 792 793 794 795 796 797 798 799 800 801
    # Make sure movement table does not exist
    sql_connection = self.getSQLConnection()
    sql_connection.manage_test("DROP TABLE IF EXISTS movement")
    # Delete also all ZSQL Methods related to movement table
    catalog = self.portal.portal_catalog.getSQLCatalog()
    catalog.manage_delObjects(ids=["z0_drop_movement",
                                   "z0_uncatalog_movement",
                                   "z_catalog_movement_list",
                                   "z_create_movement",
                                   ])
    # Update properties of catalog
    sql_catalog_object_list = list(catalog.sql_catalog_object_list)
    sql_uncatalog_object = list(catalog.sql_uncatalog_object)
    sql_clear_catalog = list(catalog.sql_clear_catalog)
802
    sql_search_tables = list(catalog.sql_search_tables)
803 804 805 806 807

    sql_catalog_object_list.remove("z_catalog_movement_list")
    sql_uncatalog_object.remove("z0_uncatalog_movement")
    sql_clear_catalog.remove("z0_drop_movement")
    sql_clear_catalog.remove("z_create_movement")
808
    sql_search_tables.remove("movement")
809 810 811 812

    catalog.sql_catalog_object_list = tuple(sql_catalog_object_list)
    catalog.sql_uncatalog_object = tuple(sql_uncatalog_object)
    catalog.sql_clear_catalog = tuple(sql_clear_catalog)
813
    catalog.sql_search_tables = tuple(sql_search_tables)
814

815
    # the default currency for the site
816
    if not self.portal.hasProperty('reference_currency_id'):
817
      self.portal.manage_addProperty('reference_currency_id', 'EUR', type='string')
818 819 820 821
    # not working days
    if not self.portal.hasProperty('not_working_days'):
      self.portal.manage_addProperty('not_working_days', '', type='string')
    else:
822
      self.portal.not_working_days = ''
Grégory Wisniewski's avatar
Grégory Wisniewski committed
823
    setattr(self.portal, 'functionnal_test_mode', 1)
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
    # the person module
    self.person_module = self.getPersonModule()
    # the organisation module
    self.organisation_module = self.getOrganisationModule()
    # the category tool
    self.category_tool = self.getCategoryTool()
    # the workflow tool
    self.workflow_tool = self.getWorkflowTool()
    # nb use for bank account inventory
    self.account_inventory_number = 0
    # the cash inventory module
    self.cash_inventory_module = self.getCashInventoryModule()
    # the bank inventory module
    self.bank_account_inventory_module = self.getBankAccountInventoryModule()
    # simulation tool
    self.simulation_tool = self.getSimulationTool()
    # get the currency module
    self.currency_module = self.getCurrencyModule()
842
    self.checkbook_model_module = self.portal.checkbook_model_module
Sebastien Robin's avatar
Sebastien Robin committed
843 844
    # a default date
    self.date = DateTime()
845

846 847 848 849 850
  def setDocumentSourceReference(self, doc):
    """
    Compute and set the source reference for a document
    """
    # document must have a date defined
851 852
    if doc.getStartDate() is None:
      doc.edit(start_date=DateTime())
853 854
    # call script to set source reference
    doc.Baobab_getUniqueReference()
855 856


Grégory Wisniewski's avatar
Grégory Wisniewski committed
857
  def createPerson(self, id, first_name, last_name, site=None):
858 859 860
    """
    Create a person
    """
861
    if site is None:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
862
      site = "testsite/paris"
863 864 865
    return self.person_module.newContent(id = id,
                                         portal_type = 'Person',
                                         first_name = first_name,
866 867
                                         last_name = last_name,
                                         site=site)
868

869

870
  def createBankAccount(self, person, account_id, currency, amount, inv_date=None, **kw):
871 872 873
    """
    Create and initialize a bank account for a person
    """
874 875 876 877 878 879 880 881 882 883
    if not kw.has_key('bank_country_code'):
      kw['bank_country_code'] = 'k'
    if not kw.has_key('bank_code'):
      kw['bank_code'] = '1234'
    if not kw.has_key('branch'):
      kw['branch'] = '12345'
    if not kw.has_key('bank_account_number'):
      kw['bank_account_number'] = '123456789012'
    if not kw.has_key('bank_account_key'):
      kw['bank_account_key'] = '12'
884
    if not kw.has_key('internal_bank_account_number'):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
885
      kw['internal_bank_account_number'] = 'k%11s' % (12341234512 + self.account_inventory_number, )
886
      #kw['internal_bank_account_number'] = 'k12341234512'
887
    bank_account = person.newContent(id = account_id,
Aurel's avatar
Aurel committed
888 889 890
                                     portal_type = 'Bank Account',
                                     price_currency_value = currency,
                                     **kw)
891 892 893 894 895 896 897 898 899
    if not kw.has_key('reference') and bank_account.getReference() is None:
      # If there is no automatic getter-time calculation of the reference and
      # no reference has been explicitely set, generate one composed of all
      # bank codes and a static prefix - to avoid collisions as much as
      # possible.
      bank_account.edit(reference='ref_%s%s%s%s%s' % (kw['bank_country_code'],
        kw['bank_code'], kw['branch'], kw['bank_account_number'],
        kw['bank_account_key']))
      
900 901
    # validate this bank account for payment
    bank_account.validate()
902 903 904 905 906 907
    if amount:
      # we need to put some money on this bank account
      self.createBankAccountInventory(bank_account, amount, inv_date=inv_date)
    return bank_account

  def createBankAccountInventory(self, bank_account, amount, inv_date=None):
908
    if not hasattr(self, 'bank_account_inventory'):
909 910
      self.bank_account_inventory = self.bank_account_inventory_module.newContent(id='account_inventory_group',
                                                                                portal_type='Bank Account Inventory Group',
911
                                                                                site_value=self.testsite,
912 913
                                                                                stop_date=DateTime().Date())

914 915
    if inv_date is None:
      inv_date = DateTime()
916
    inventory = self.bank_account_inventory.newContent(id=bank_account.getInternalBankAccountNumber(),
917 918 919
                                                       portal_type='Bank Account Inventory',
                                                       destination_payment_value=bank_account,
                                                       stop_date=inv_date)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
920
    account_inventory_line_id = 'account_inventory_line_%s' % (self.account_inventory_number, )
921
    inventory_line = inventory.newContent(id=account_inventory_line_id,
922
                                          portal_type='Bank Account Inventory Line',
923
                                          resource_value=bank_account.getPriceCurrencyValue(),
924 925
                                          quantity=amount)

926

927 928 929 930
    # deliver the inventory
    if inventory.getSimulationState()!='delivered':
      inventory.deliver()

931 932
    self.account_inventory_number += 1

933
  def createCheckbook(self, id, vault, bank_account, min, max, date=None):
934 935 936 937 938
    """
    Create a checkbook for the given bank account
    """
    if date is None:
      date = DateTime().Date()
939 940 941 942 943 944 945 946 947
    return self.checkbook_module.newContent(
        id=id,
        portal_type='Checkbook',
        destination_value=vault,
        destination_payment_value=bank_account,
        reference_range_min=min,
        reference_range_max=max,
        start_date=date,
    )
948

949
  def createCheckbookModel(self, id, check_model, reference=None,
950
          unique_per_account=True):
951 952 953 954
    """
    Create a checkbook for the given bank account
    with 3 variations
    """
955 956 957 958 959 960 961
    model =  self.checkbook_model_module.newContent(
        id=id,
        portal_type='Checkbook Model',
        title='Generic',
        account_number_enabled=True,
        reference=reference,
        composition=check_model.getRelativeUrl(),
962
        unique_per_account=unique_per_account,
963
    )
Grégory Wisniewski's avatar
Grégory Wisniewski committed
964 965 966 967 968 969
    model.newContent(id='variant_1', portal_type='Checkbook Model Check Amount Variation',
                     quantity=50, title='50')
    model.newContent(id='variant_2', portal_type='Checkbook Model Check Amount Variation',
                     quantity=100, title='100')
    model.newContent(id='variant_3', portal_type='Checkbook Model Check Amount Variation',
                     quantity=200, title='200')
970 971
    return model

972

973
  def createCheckModel(self, id, reference='CCOP', unique_per_account=True):
974 975 976
    """
    Create a checkbook for the given bank account
    """
977 978 979 980 981 982
    return self.checkbook_model_module.newContent(
        id=id,
        portal_type='Check Model',
        title='Check',
        reference=reference,
        account_number_enabled=True,
983
        unique_per_account=unique_per_account,
984
    )
985

986 987 988 989 990 991
  def createCheckAndCheckbookModel(self):
    """
    create default checkbook and check models
    """
    self.check_model = self.createCheckModel(id='check_model')
    self.check_model_1 = self.check_model
992
    self.check_model_2 = self.createCheckModel(id='check_model_2', reference='CCCO')
993 994
    self.check_model_1_2 = self.createCheckModel(
        id='check_model_1_2',
995
        reference='CCOP',
996
        unique_per_account=False,
997 998 999
    )
    self.check_model_2_2 = self.createCheckModel(
        id='check_model_2_2',
1000
        reference='CCCO',
1001
        unique_per_account=False,
1002
    )
1003 1004 1005
    self.checkbook_model = self.createCheckbookModel(
           id='checkbook_model', check_model=self.check_model)
    self.checkbook_model_1 = self.checkbook_model
1006
    self.checkbook_model_2 = self.createCheckbookModel(
1007
           id='checkbook_model_2', check_model=self.check_model_2)
1008 1009 1010
    self.checkbook_model_1_2 = self.createCheckbookModel(
           id='checkbook_model_1_2',
           check_model=self.check_model_1_2,
1011
           unique_per_account=False,
1012 1013 1014 1015
    )
    self.checkbook_model_2_2 = self.createCheckbookModel(
           id='checkbook_model_2_2',
           check_model=self.check_model_2_2,
1016
           unique_per_account=False,
1017
    )
1018

1019
  def createCheck(self, id, reference, checkbook, bank_account=None,
1020
                        resource_value=None, destination_value=None):
1021 1022 1023 1024 1025
    """
    Create Check in a checkbook
    """
    check = checkbook.newContent(id=id,
                                 portal_type = 'Check',
1026
                                 reference=reference,
1027
                                 destination_payment_value=bank_account,
1028 1029
                                 resource_value=resource_value,
                                 destination_value=destination_value
1030
                                )
1031

1032 1033 1034 1035
    # mark the check as issued
    check.confirm()
    return check

1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
  def createTravelerCheckModel(self, id):
    """
    Create a checkbook for the given bank account
    """
    model = self.checkbook_model_module.newContent(id = id,
                                            title = 'USD Traveler Check',
                                            portal_type = 'Check Model',
                                            fixed_price = 1
                                            )
    variation = model.newContent(id='variant_1',
                                 portal_type='Check Model Type Variation',
                                 price=50)
1048
    model.setPriceCurrency(self.currency_2.getRelativeUrl())
1049 1050
    return model

Aurel's avatar
Aurel committed
1051
  def createCashContainer(self, document, container_portal_type, global_dict, line_list, delivery_line_type='Cash Delivery Line'):
Aurel's avatar
Aurel committed
1052 1053 1054 1055 1056
    """
    Create a cash container
    global_dict has keys :
      emission_letter, variation, cash_status, resource
    line_list is a list od dict with keys:
Aurel's avatar
Aurel committed
1057
      reference, range_start, range_stop, quantity, aggregate
Aurel's avatar
Aurel committed
1058 1059
    """
    # Container Creation
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1060
    base_list = ('emission_letter', 'variation', 'cash_status')
Aurel's avatar
Aurel committed
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
    category_list =  ('emission_letter/'+global_dict['emission_letter'], 'variation/'+global_dict['variation'], 'cash_status/'+global_dict['cash_status'] )
    resource_total_quantity = 0
    # create cash container
    for line_dict in line_list:
      movement_container = document.newContent(portal_type          = container_portal_type
                                               , reindex_object     = 1
                                               , reference                 = line_dict['reference']
                                               , cash_number_range_start   = line_dict['range_start']
                                               , cash_number_range_stop    = line_dict['range_stop']
                                               )
Aurel's avatar
Aurel committed
1071
      if line_dict.has_key('aggregate'):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1072
        movement_container.setAggregateValueList([line_dict['aggregate'], ])
Aurel's avatar
Aurel committed
1073 1074 1075 1076 1077 1078 1079 1080
      # create a cash container line
      container_line = movement_container.newContent(portal_type      = 'Container Line'
                                                     , reindex_object = 1
                                                     , resource_value = global_dict['resource']
                                                     , quantity       = line_dict['quantity']
                                                     )
      container_line.setResourceValue(global_dict['resource'])
      container_line.setVariationCategoryList(category_list)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1081
      container_line.updateCellRange(script_id='CashDetail_asCellRange', base_id="movement")
Aurel's avatar
Aurel committed
1082
      for key in container_line.getCellKeyList(base_id='movement'):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1083
        if isSameSet(key, category_list):
Aurel's avatar
Aurel committed
1084 1085 1086
          cell = container_line.newCell(*key)
          cell.setCategoryList(category_list)
          cell.setQuantity(line_dict['quantity'])
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1087
          cell.setMappedValuePropertyList(['quantity', 'price'])
Aurel's avatar
Aurel committed
1088 1089 1090 1091 1092 1093 1094 1095 1096
          cell.setMembershipCriterionBaseCategoryList(base_list)
          cell.setMembershipCriterionCategoryList(category_list)
          cell.edit(force_update = 1,
                    price = container_line.getResourceValue().getBasePrice())


      resource_total_quantity += line_dict['quantity']
    # create cash delivery movement
    movement_line = document.newContent(id               = "movement"
Aurel's avatar
Aurel committed
1097
                                        , portal_type    = delivery_line_type
Aurel's avatar
Aurel committed
1098 1099 1100 1101 1102 1103 1104
                                        , resource_value = global_dict['resource']
                                        , quantity_unit_value = self.getCategoryTool().quantity_unit.unit
                                        )
    movement_line.setVariationBaseCategoryList(base_list)
    movement_line.setVariationCategoryList(category_list)
    movement_line.updateCellRange(script_id="CashDetail_asCellRange", base_id="movement")
    for key in movement_line.getCellKeyList(base_id='movement'):
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1105
      if isSameSet(key, category_list):
Aurel's avatar
Aurel committed
1106 1107 1108
        cell = movement_line.newCell(*key)
        cell.setCategoryList(category_list)
        cell.setQuantity(resource_total_quantity)
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1109
        cell.setMappedValuePropertyList(['quantity', 'price'])
Aurel's avatar
Aurel committed
1110 1111 1112 1113 1114 1115
        cell.setMembershipCriterionBaseCategoryList(base_list)
        cell.setMembershipCriterionCategoryList(category_list)
        cell.edit(force_update = 1,
                  price = movement_line.getResourceValue().getBasePrice())


Grégory Wisniewski's avatar
Grégory Wisniewski committed
1116
  def createCashInventory(self, source, destination, currency, line_list=[], extra_id='',
1117
                          reset_quantity=0, start_date=None, quantity_factor=1):
1118 1119 1120 1121
    """
    Create a cash inventory group
    """
    # we need to have a unique inventory group id by destination
1122

1123
    inventory_group_id = 'inventory_group_%s_%s%s' % \
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1124
                         (destination.getParentValue().getUid(), destination.getId(), extra_id)
1125
    if start_date is None:
1126
      start_date = DateTime()-1
1127 1128 1129
    if not hasattr(self, inventory_group_id):
      inventory_group =  self.cash_inventory_module.newContent(id=inventory_group_id,
                                                               portal_type='Cash Inventory Group',
Aurel's avatar
Aurel committed
1130
                                                               destination_value=destination,
1131
                                                               start_date=start_date)
1132 1133 1134 1135 1136
      setattr(self, inventory_group_id, inventory_group)
    else:
      inventory_group = getattr(self, inventory_group_id)

    # get/create the inventory based on currency
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1137
    inventory_id = '%s_inventory_%s' % (inventory_group_id, currency.getId())
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
    if not hasattr(self, inventory_id):
      inventory = inventory_group.newContent(id=inventory_id,
                                             portal_type='Cash Inventory',
                                             price_currency_value=currency)
      setattr(self, inventory_id, inventory)
    else:
      inventory = getattr(self, inventory_id)

    # line data are given by a list of dict, dicts must have this key :
    # id :  line id
    # resource : banknote or coin
    # variation_id : list of variation id
    # variation_value : list of variation value (must be in the same order as variation_id
    # quantity
    for line in line_list:
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1153
      variation_list = line.get('variation_list', None)
1154 1155 1156 1157 1158 1159
      self.addCashLineToDelivery(inventory,
                                 line['id'],
                                 "Cash Inventory Line",
                                 line['resource'],
                                 line['variation_id'],
                                 line['variation_value'],
1160
                                 line['quantity'],
1161
                                 variation_list=variation_list,
1162 1163
                                 reset_quantity=reset_quantity,
                                 quantity_factor=quantity_factor)
1164 1165 1166
    # deliver the inventory
    if inventory.getSimulationState()!='delivered':
      inventory.deliver()
1167 1168 1169 1170
    return inventory_group


  def addCashLineToDelivery(self, delivery_object, line_id, line_portal_type, resource_object,
1171
          variation_base_category_list, variation_category_list, resource_quantity_dict,
1172
          variation_list=None, reset_quantity=0, quantity_factor=1):
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
    """
    Add a cash line to a delivery
     """
    base_id = 'movement'
    line_kwd = {'base_id':base_id}
    # create the cash line
    line = delivery_object.newContent( id                  = line_id
                                     , portal_type         = line_portal_type
                                     , resource_value      = resource_object # banknote or coin
                                     , quantity_unit_value = self.unit
                                     )
    # set base category list on line
    line.setVariationBaseCategoryList(variation_base_category_list)
    # set category list line
    line.setVariationCategoryList(variation_category_list)
    line.updateCellRange(script_id='CashDetail_asCellRange', base_id=base_id)
    cell_range_key_list = line.getCellRangeKeyList(base_id=base_id)
    if cell_range_key_list <> [[None, None]] :
      for k in cell_range_key_list:
        category_list = filter(lambda k_item: k_item is not None, k)
        c = line.newCell(*k, **line_kwd)
        mapped_value_list = ['price', 'quantity']
        c.edit( membership_criterion_category_list = category_list
              , mapped_value_property_list         = mapped_value_list
              , category_list                      = category_list
              , force_update                       = 1
              )
    # set quantity on cell to define quantity of bank notes / coins
1201 1202 1203
    if variation_list is None:
      variation_list = self.variation_list
    for variation in variation_list:
1204 1205 1206
      v1, v2 = variation_category_list[:2]
      cell = line.getCell(v1, variation, v2)
      if cell is not None:
1207 1208 1209
        quantity = resource_quantity_dict[variation]
        if reset_quantity:
          quantity = 0
1210
        cell.setQuantity(quantity*quantity_factor)
1211 1212 1213 1214 1215 1216 1217


  def checkResourceCreated(self):
    """
    Check that all have been create after setup
    """
    # check that Categories were created
1218
    self.assertEqual(self.paris.getPortalType(), 'Category')
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237

    # check that Resources were created
    # check portal type of billet_10000
    self.assertEqual(self.billet_10000.getPortalType(), 'Banknote')
    # check value of billet_10000
    self.assertEqual(self.billet_10000.getBasePrice(), 10000)
    # check currency value  of billet_10000
    self.assertEqual(self.billet_10000.getPriceCurrency(), 'currency_module/EUR')
    # check years  of billet_10000
    self.assertEqual(self.billet_10000.getVariationList(), ['1992', '2003'])

    # check portal type of billet_5000
    self.assertEqual(self.billet_5000.getPortalType(), 'Banknote')
    # check value of billet_5000
    self.assertEqual(self.billet_5000.getBasePrice(), 5000)
    # check currency value  of billet_5000
    self.assertEqual(self.billet_5000.getPriceCurrency(), 'currency_module/EUR')
    # check years  of billet_5000
    self.assertEqual(self.billet_5000.getVariationList(), ['1992', '2003'])
1238

1239 1240 1241 1242 1243 1244 1245 1246
    # check portal type of billet_200
    self.assertEqual(self.billet_200.getPortalType(), 'Banknote')
    # check value of billet_200
    self.assertEqual(self.billet_200.getBasePrice(), 200)
    # check currency value  of billet_200
    self.assertEqual(self.billet_200.getPriceCurrency(), 'currency_module/EUR')
    # check years  of billet_200
    self.assertEqual(self.billet_200.getVariationList(), ['1992', '2003'])
1247 1248 1249

  def resetInventory(self, 
               sequence=None, line_list=None, sequence_list=None, extra_id=None, 
1250
               destination=None, currency=None, start_date=None, **kwd):
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    """
    Make sure we can not close the counter date 
    when there is still some operations remaining
    """
    if extra_id is not None:
      extra_id = '_reset_%s' % extra_id
    else:
      extra_id = '_reset'
    # Before the test, we need to input the inventory
    self.createCashInventory(source=None, destination=destination, currency=currency,
Grégory Wisniewski's avatar
Grégory Wisniewski committed
1261
                             line_list=line_list, extra_id=extra_id, reset_quantity=1,
1262
                             start_date=start_date)
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272

  def stepDeleteResetInventory(self, sequence=None, sequence_list=None, **kwd):
    """
    Make sure we can not close the counter date 
    when there is still some operations remaining
    """
    inventory_module = self.getPortal().cash_inventory_module
    to_delete_id_list = [x for x in inventory_module.objectIds() 
                         if x.find('reset')>=0]
    inventory_module.manage_delObjects(ids=to_delete_id_list)
1273