def get_cursor(self, create_session_store_db=True): db_name = config.get('session_store_db', 'session_store') try: con = db_connect(db_name) cr = con.cursor() except: if not create_session_store_db: raise db_connect('postgres') with closing(db_connect('postgres').cursor()) as cr: cr.autocommit(True) # avoid transaction block cr.execute( """CREATE DATABASE "%s" ENCODING 'unicode' TEMPLATE "%s" """ % (db_name, config['db_template'])) return self.get_cursor(create_session_store_db=False) cr.execute(""" CREATE TABLE IF NOT EXISTS sessionstore ( id varchar(40), data bytea ); """) cr.commit() return cr
def test_00_payment_advice_flow(self): # I create a new Payment Advice with NEFT Transaction Enable payment_advice = self.Advice.create({ 'name': 'NEFT Advice', 'bank_id': self.bank_1.id, 'line_ids': [(0, 0, { 'employee_id': self.employee_fp.id, 'name': '90125452552', 'ifsc_code': 'abn45215145', 'bysal': 25000.00, }), (0, 0, { 'employee_id': self.employee_al.id, 'name': '00014521111232', 'ifsc_code': 'sbi45452145', 'bysal': 20000.00, })], }) # I check that the Payment Advice is in "Draft" self.assertEqual(payment_advice.state, 'draft') # Now I confirm Payment Advice payment_advice.confirm_sheet() # I check that the Payment Advice state is "Confirmed" self.assertEqual(payment_advice.state, 'confirm') # In order to test the PDF report defined on a Payment Advice, we will print a Print Advice Report when NEFT is checked data, data_format = self.env.ref('l10n_in_hr_payroll.payroll_advice').render(payment_advice.ids) if config.get('test_report_directory'): open(os.path.join(config['test_report_directory'], 'l10n_in_hr_payroll_summary_report' + data_format), 'wb+').write(data)
def _geoip_setup_resolver(cls): # Lazy init of GeoIP resolver if flectra._geoip_resolver is not None: return geofile = config.get('geoip_database') try: flectra._geoip_resolver = GeoIPResolver.open(geofile) or False except Exception as e: _logger.warning('Cannot load GeoIP: %s', ustr(e))
def _import_image_by_url(self, url, session, field, line_number): """ Imports an image by URL :param str url: the original field value :param requests.Session session: :param str field: name of the field (for logging/debugging) :param int line_number: 0-indexed line number within the imported file (for logging/debugging) :return: the replacement value :rtype: bytes """ maxsize = int(config.get("import_image_maxbytes", DEFAULT_IMAGE_MAXBYTES)) _logger.debug("Trying to import image from URL: %s into field %s, at line %s" % (url, field, line_number)) try: response = session.get(url, timeout=int(config.get("import_image_timeout", DEFAULT_IMAGE_TIMEOUT))) response.raise_for_status() if response.headers.get('Content-Length') and int(response.headers['Content-Length']) > maxsize: raise ValueError(_("File size exceeds configured maximum (%s bytes)", maxsize)) content = bytearray() for chunk in response.iter_content(DEFAULT_IMAGE_CHUNK_SIZE): content += chunk if len(content) > maxsize: raise ValueError(_("File size exceeds configured maximum (%s bytes)", maxsize)) image = Image.open(io.BytesIO(content)) w, h = image.size if w * h > 42e6: # Nokia Lumia 1020 photo resolution raise ValueError( u"Image size excessive, imported images must be smaller " u"than 42 million pixel") return base64.b64encode(content) except Exception as e: _logger.exception(e) raise ValueError(_("Could not retrieve URL: %(url)s [%(field_name)s: L%(line_number)d]: %(error)s") % { 'url': url, 'field_name': field, 'line_number': line_number + 1, 'error': e })
def _get_sys_logs(self): """ Utility method to send a publisher warranty get logs messages. """ msg = self._get_message() arguments = {'arg0': ustr(msg), "action": "update"} url = config.get("publisher_warranty_url") r = requests.post(url, data=arguments, timeout=30) r.raise_for_status() return literal_eval(r.text)
def registries(cls): """ A mapping from database names to registries. """ size = config.get('registry_lru_size', None) if not size: # Size the LRU depending of the memory limits if os.name != 'posix': # cannot specify the memory limit soft on windows... size = 42 else: # A registry takes 10MB of memory on average, so we reserve # 10Mb (registry) + 5Mb (working memory) per registry avgsz = 15 * 1024 * 1024 size = int(config['limit_memory_soft'] / avgsz) return LRU(size)
def _geoip_setup_resolver(cls): # Lazy init of GeoIP resolver if flectra._geoip_resolver is not None: return try: import GeoIP # updated database can be downloaded on MaxMind website # http://dev.maxmind.com/geoip/legacy/install/city/ geofile = config.get('geoip_database') if os.path.exists(geofile): flectra._geoip_resolver = GeoIP.open(geofile, GeoIP.GEOIP_STANDARD) else: flectra._geoip_resolver = False _logger.warning('GeoIP database file %r does not exists, apt-get install geoip-database-contrib or download it from http://dev.maxmind.com/geoip/legacy/install/city/', geofile) except ImportError: flectra._geoip_resolver = False
def _parse_import_data_recursive(self, model, prefix, data, import_fields, options): # Get fields of type date/datetime all_fields = self.env[model].fields_get() for name, field in all_fields.items(): name = prefix + name if field['type'] in ('date', 'datetime') and name in import_fields: index = import_fields.index(name) self._parse_date_from_data(data, index, name, field['type'], options) # Check if the field is in import_field and is a relational (followed by /) # Also verify that the field name exactly match the import_field at the correct level. elif any(name + '/' in import_field and name == import_field.split('/')[prefix.count('/')] for import_field in import_fields): # Recursive call with the relational as new model and add the field name to the prefix self._parse_import_data_recursive(field['relation'], name + '/', data, import_fields, options) elif field['type'] in ('float', 'monetary') and name in import_fields: # Parse float, sometimes float values from file have currency symbol or () to denote a negative value # We should be able to manage both case index = import_fields.index(name) self._parse_float_from_data(data, index, name, options) elif field['type'] == 'binary' and field.get('attachment') and any(f in name for f in IMAGE_FIELDS) and name in import_fields: index = import_fields.index(name) with requests.Session() as session: session.stream = True for num, line in enumerate(data): if re.match(config.get("import_image_regex", DEFAULT_IMAGE_REGEX), line[index]): if not self.env.user._can_import_remote_urls(): raise AccessError(_("You can not import images via URL, check with your administrator or support for the reason.")) line[index] = self._import_image_by_url(line[index], session, name, num) else: try: base64.b64decode(line[index], validate=True) except binascii.Error: raise ValueError(_("Found invalid image data, images should be imported as either URLs or base64-encoded data.")) return data
import uuid import logging from flectra import api, fields, models from flectra.tools import config, ormcache, mute_logger, pycompat _logger = logging.getLogger(__name__) """ A dictionary holding some configuration parameters to be initialized when the database is created. """ _default_parameters = { "database.secret": lambda: pycompat.text_type(uuid.uuid4()), "database.uuid": lambda: pycompat.text_type(uuid.uuid1()), "database.create_date": fields.Datetime.now, "web.base.url": lambda: "http://localhost:%s" % config.get('http_port'), "base_setup.send_statistics": lambda: "true", } class IrConfigParameter(models.Model): """Per-database storage of configuration key-value pairs.""" _name = 'ir.config_parameter' _rec_name = 'key' key = fields.Char(required=True, index=True) value = fields.Text(required=True) _sql_constraints = [('key_uniq', 'unique (key)', 'Key must be unique.')] @api.model_cr
def test_00_payslip_flow(self): """ Testing payslip flow and report printing """ # I create an employee Payslip richard_payslip = self.env['hr.payslip'].create({ 'name': 'Payslip of Richard', 'employee_id': self.richard_emp.id }) payslip_input = self.env['hr.payslip.input'].search([ ('payslip_id', '=', richard_payslip.id) ]) # I assign the amount to Input data payslip_input.write({'amount': 5.0}) # I verify the payslip is in draft state self.assertEqual(richard_payslip.state, 'draft', 'State not changed!') context = { "lang": "en_US", "tz": False, "active_model": "ir.ui.menu", "department_id": False, "section_id": False, "active_ids": [self.ref("hr_payroll.menu_department_tree")], "active_id": self.ref("hr_payroll.menu_department_tree") } # I click on 'Compute Sheet' button on payslip richard_payslip.with_context(context).compute_sheet() # Then I click on the 'Confirm' button on payslip richard_payslip.action_payslip_done() # I verify that the payslip is in done state self.assertEqual(richard_payslip.state, 'done', 'State not changed!') # I want to check refund payslip so I click on refund button. richard_payslip.refund_sheet() # I check on new payslip Credit Note is checked or not. payslip_refund = self.env['hr.payslip'].search([ ('name', 'like', 'Refund: ' + richard_payslip.name), ('credit_note', '=', True) ]) self.assertTrue(bool(payslip_refund), "Payslip not refunded!") # I want to generate a payslip from Payslip run. payslip_run = self.env['hr.payslip.run'].create({ 'date_end': '2011-09-30', 'date_start': '2011-09-01', 'name': 'Payslip for Employee' }) # I create record for generating the payslip for this Payslip run. payslip_employee = self.env['hr.payslip.employees'].create( {'employee_ids': [(4, self.richard_emp.id)]}) # I generate the payslip by clicking on Generat button wizard. payslip_employee.with_context(active_id=payslip_run.id).compute_sheet() # I open Contribution Register and from there I print the Payslip Lines report. self.env['payslip.lines.contribution.register'].create({ 'date_from': '2011-09-30', 'date_to': '2011-09-01' }) # I print the payslip report data, data_format = self.env.ref( 'hr_payroll.action_report_payslip').render(richard_payslip.ids) if config.get('test_report_directory'): open( os.path.join(config['test_report_directory'], 'hr_payroll-payslip.' + data_format), 'wb+').write(data) # I print the payslip details report data, data_format = self.env.ref( 'hr_payroll.payslip_details_report').render(richard_payslip.ids) if config.get('test_report_directory'): open( os.path.join(config['test_report_directory'], 'hr_payroll-payslipdetails.' + data_format), 'wb+').write(data) # I print the contribution register report context = { 'model': 'hr.contribution.register', 'active_ids': [self.ref('hr_payroll.hr_houserent_register')] } test_reports.try_report_action( self.env.cr, self.env.uid, 'action_payslip_lines_contribution_register', context=context, our_module='hr_payroll')