def upload_report(self, cr, uid, report_id, file_sxw, file_type, context=None): ''' Untested function ''' sxwval = StringIO(base64.decodestring(file_sxw)) if file_type == 'sxw': fp = open( get_module_resource('base_report_designer', 'openerp_sxw2rml', 'normalized_oo2rml.xsl'), 'rb') if file_type == 'odt': fp = open( get_module_resource('base_report_designer', 'openerp_sxw2rml', 'normalized_odt2rml.xsl'), 'rb') report = self.pool['ir.actions.report.xml'].write( cr, uid, [report_id], { 'report_sxw_content': base64.decodestring(file_sxw), 'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read())), }) return True
def sxwtorml(self, cr, uid, file_sxw, file_type): ''' The use of this function is to get rml file from sxw file. ''' sxwval = StringIO(base64.decodestring(file_sxw)) if file_type=='sxw': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb') if file_type=='odt': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb') return {'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read()))}
def upload_report(self, cr, uid, report_id, file_sxw, file_type, context=None): ''' Untested function ''' sxwval = StringIO(base64.decodestring(file_sxw)) if file_type=='sxw': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb') if file_type=='odt': fp = open(get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb') report = self.pool['ir.actions.report.xml'].write(cr, uid, [report_id], { 'report_sxw_content': base64.decodestring(file_sxw), 'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read())), }) return True
def test_ods_success(self): Import = self.registry('base_import.import') ods_file_path = get_module_resource('base_import', 'tests', 'test.ods') file_content = open(ods_file_path, 'rb').read() id = Import.create(self.cr, self.uid, { 'res_model': 'base_import.tests.models.preview', 'file': file_content, 'file_type': 'application/vnd.oasis.opendocument.spreadsheet' }) result = Import.parse_preview(self.cr, self.uid, id, { 'headers': True, }) self.assertIsNone(result.get('error')) self.assertEqual(result['matches'], {0: ['name'], 1: ['somevalue'], 2: None}) self.assertEqual(result['headers'], ['name', 'Some Value', 'Counter']) self.assertItemsEqual(result['fields'], [ ID_FIELD, {'id': 'name', 'name': 'name', 'string': 'Name', 'required':False, 'fields': [], 'type': 'char'}, {'id': 'somevalue', 'name': 'somevalue', 'string': 'Some Value', 'required':True, 'fields': [], 'type': 'integer'}, {'id': 'othervalue', 'name': 'othervalue', 'string': 'Other Variable', 'required':False, 'fields': [], 'type': 'integer'}, ]) self.assertEqual(result['preview'], [ ['foo', '1', '2'], ['bar', '3', '4'], ['aux', '5', '6'], ]) # Ensure we only have the response fields we expect self.assertItemsEqual(result.keys(), ['matches', 'headers', 'fields', 'preview', 'headers_type', 'options', 'debug'])
def test_ofx_file_import(self): try: from ofxparse import OfxParser as ofxparser except ImportError: #the Python library isn't installed on the server, the OFX import is unavailable and the test cannot be run return True cr, uid = self.cr, self.uid ofx_file_path = get_module_resource( 'account_bank_statement_import_ofx', 'test_ofx_file', 'test_ofx.ofx') ofx_file = open(ofx_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create( cr, uid, dict(data_file=ofx_file, )) self.statement_import_model.import_file(cr, uid, [bank_statement_id]) statement_id = self.bank_statement_model.search( cr, uid, [('name', '=', '000000123')])[0] bank_st_record = self.bank_statement_model.browse( cr, uid, statement_id) # Checking equality of floating point amounts is a recipe for disaster: # self.assertEquals(bank_st_record.balance_start, 2516,56) # self.assertEquals(bank_st_record.balance_end_real, 2156.56) self.assertTrue( abs(bank_st_record.balance_start - 2516.56) < 0.00001, 'Start balance %f not equal to 2516.56' % bank_st_record.balance_start) self.assertTrue( abs(bank_st_record.balance_end_real - 2156.56) < 0.00001, 'Real end balance %f not equal to 2156.56' % bank_st_record.balance_end_real)
def test_ofx_file_import(self): try: from ofxparse import OfxParser as ofxparser except ImportError: #the Python library isn't installed on the server, the OFX import is unavailable and the test cannot be run return True ofx_file_path = get_module_resource( 'account_bank_statement_import_ofx', 'test_ofx_file', 'test_ofx.ofx') ofx_file = open(ofx_file_path, 'rb').read().encode('base64') import_wizard = self.statement_import_model.create( dict(data_file=ofx_file)) create_journal_wizard = self.env['account.bank.statement.import.journal.creation']\ .with_context(statement_import_transient_id=import_wizard.id)\ .create({'name': 'Bank 123456', 'currency_id': self.env.ref("base.USD").id, 'account_number': '123456'}) create_journal_wizard.create_journal() # Note: also finishes import bank_st_record = self.bank_statement_model.search([('name', '=', '000000123')])[0] self.assertEqual(bank_st_record.balance_start, 2516.56) self.assertEqual(bank_st_record.balance_end_real, 2156.56) line = bank_st_record.line_ids[-1] self.assertEqual(line.name, 'Agrolait') self.assertEqual(line.ref, '219378') self.assertEqual(line.partner_id.id, self.ref('base.res_partner_2')) self.assertEqual( line.bank_account_id.id, self.ref('account_bank_statement_import.ofx_partner_bank_1'))
def index(self, req, s_action=None, data=None, **kw): #if req.httprequest.remote_addr in ['127.0.0.1']: # pass #else: # return Response('Not authorized', mimetype='text/html') if 'db' in kw: dbname=kw['db'] else: dbname='pjb_live' html_ret="" uid=1 registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) if 'query_id' in kw: query_id=int( kw['query_id'] ) template_path = get_module_resource('html_reports', '', 'sql_query.html') url_ctx={'req':req, 'dbname':dbname, 'get_query_list_url':get_query_list_url } ctx = pool.get("analysis.sql.query").get_html_context(cr,uid,query_id) ctx.update( url_ctx ) html_ret = render_mako_file(template_path, ctx) else: pass return Response(html_ret, mimetype='text/html')
def _get_pain_file_name(self, pain_name, pain_flavor): """Manage variant schema (i.e. Italian banks in CBI) based on pain xsd file name. Pain_name MUST BE in form 'pain' or 'pain(variant)' Standard pain name is 'pain.001.001.VV.xsd' where VV is pain version, variant name is 'pain.001.001.VV-LLL.xsd' where LLL is variant name. If variant file does not exist, standard file is used""" xsd_file, variant = self._get_name_n_params(pain_name) module_path = 'account_banking_sepa_credit_transfer' if variant: if variant.find('used') >= 0: x = variant.split(' ') variant = x[-1] if variant == 'Italy': variant = 'CBI-IT' xsd_file = '%s-%s.xsd' % (pain_flavor, variant) else: xsd_file = '%s.xsd' % pain_flavor xsd_file = get_module_resource(module_path, 'data', xsd_file) if xsd_file: pain_xsd_file = xsd_file else: pain_xsd_file = '%s/%s/%s.xsd' % (module_path, 'data', pain_flavor) return pain_xsd_file, variant
def _test_return_import(self, module_name, file_name, return_name, local_account=False, date=False, transactions=None): """Test correct creation of single return.""" import_model = self.env['payment.return.import'] return_model = self.env['payment.return'] return_path = get_module_resource(module_name, 'test_files', file_name) return_file = open(return_path, 'rb').read().encode('base64') bank_return_id = import_model.create(dict(data_file=return_file, )) bank_return_id.import_file() if local_account: bank_account_id = import_model._find_bank_account_id(local_account) journal_id = import_model._get_journal(bank_account_id) self.assertTrue( journal_id, 'Bank account %s has not journal assigned' % local_account) ids = return_model.search([('name', '=', return_name)]) self.assertTrue( ids, 'Payment return %s not found after parse.' % return_name) return_obj = ids[0] if date: self.assertEqual( return_obj.date, date, 'Date %s not equal to expected %s' % (return_obj.date, date)) if transactions: for transaction in transactions: self._test_transaction(return_obj, **transaction)
def getAttacment(self, name): path = get_module_resource('l10n_it_fatturapa_out', 'tests', 'data', 'attah_base.pdf') currDir = os.path.dirname(path) new_file = '%s/%s' % (currDir, name) shutil.copyfile(path, new_file) return self.getFilePath(new_file)
def test_coda_file_import(self): cr, uid = self.cr, self.uid bank_temp_ref = self.registry('ir.model.data').get_object_reference( cr, uid, 'account', 'conf_bnk') partner_id_ref = self.registry('ir.model.data').get_object_reference( cr, uid, 'base', 'main_partner') company_id_ref = self.registry('ir.model.data').get_object_reference( cr, uid, 'base', 'main_company') self.bank_temp_id = bank_temp_ref and bank_temp_ref[1] or False self.partner_id = partner_id_ref and partner_id_ref[1] or False self.company_id = company_id_ref and company_id_ref[1] or False coda_file_path = get_module_resource( 'l10n_be_coda', 'test_coda_file', 'Ontvangen_CODA.2013-01-11-18.59.15.txt') coda_file = open(coda_file_path, 'rb').read().encode('base64') bank_account_id = self.registry('res.partner.bank').create( cr, uid, dict(state='bank', acc_number='BE33737018595246', bank_name='Reserve', partner_id=self.partner_id, company_id=self.company_id)) bank_statement_id = self.statement_import_model.create( cr, uid, dict( file_type='coda', data_file=coda_file, )) self.statement_import_model.parse_file(cr, uid, [bank_statement_id]) statement_id = self.bank_statement_model.search( cr, uid, [('name', '=', '135')])[0] bank_st_record = self.bank_statement_model.browse( cr, uid, statement_id) self.assertEquals(bank_st_record.balance_start, 11812.70) self.assertEquals(bank_st_record.balance_end_real, 13527.81)
def index(self, req, s_action=None, data=None, **kw): if 'db' in kw: dbname=kw['db'] else: dbname='pjb_live' html_ret="" uid=1 print "XXXXXXXXXXXXXXXXXXXXXXXXXXXX" registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) chart_ids=pool.get("analysis.chart").search(cr,uid,[]) charts = pool.get("analysis.chart").browse(cr,uid,chart_ids) image_path=get_module_path('html_reports') for chart in charts: fn="%d.png" % chart.id image_file=os.path.join(image_path,fn) chart.write({"image_file":image_file}) #pool.get('analysis.chart').generate_bar_charts(cr, uid, chart_ids) pool.get('analysis.chart').generate_chart(cr, uid, chart.id) ctx={'title' : "List of Charts", 'charts': charts, 'fn':fn, 'get_image_url': get_image_url, 'req':req, 'dbname':dbname, } template_path = get_module_resource('html_reports', '', 'chart_list.html') html_ret = render_mako_file(template_path, ctx) return Response(html_ret, mimetype='text/html')
def test_ofx_file_import(self): try: from ofxparse import OfxParser as ofxparser except ImportError: #the Python library isn't installed on the server, the OFX import is unavailable and the test cannot be run return True cr, uid = self.cr, self.uid creation_wiz_obj = self.registry( 'account.bank.statement.import.journal.creation') ofx_file_path = get_module_resource( 'account_bank_statement_import_ofx', 'test_ofx_file', 'test_ofx.ofx') ofx_file = open(ofx_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create( cr, uid, dict(data_file=ofx_file, )) res = self.statement_import_model.import_file(cr, uid, [bank_statement_id]) self.assertEquals(res['res_model'], 'account.bank.statement.import.journal.creation', 'boom') ctx = res.get('context', {}).copy() wiz_id = creation_wiz_obj.create(cr, uid, {}, context=ctx) wiz = creation_wiz_obj.browse(cr, uid, [wiz_id], context=ctx) wiz.create_journal() statement_id = self.bank_statement_model.search( cr, uid, [('name', '=', '000000123')]) bank_st_record = self.bank_statement_model.browse( cr, uid, statement_id) self.assertEquals(bank_st_record.balance_start, 2516.56) self.assertEquals(bank_st_record.balance_end_real, 2156.56)
def index(self, req, s_action=None, data=None, **kw): #if req.httprequest.remote_addr in ['127.0.0.1']: # pass #else: # return Response('Not authorized', mimetype='text/html') if 'db' in kw: dbname = kw['db'] else: dbname = 'pjb_live' html_ret = "" uid = 1 registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) if 'query_id' in kw: query_id = int(kw['query_id']) template_path = get_module_resource('html_reports', '', 'sql_query.html') url_ctx = { 'req': req, 'dbname': dbname, 'get_query_list_url': get_query_list_url } ctx = pool.get("analysis.sql.query").get_html_context( cr, uid, query_id) ctx.update(url_ctx) html_ret = render_mako_file(template_path, ctx) else: pass return Response(html_ret, mimetype='text/html')
def test_qif_file_import(self): from openerp.tools import float_compare cr, uid = self.cr, self.uid qif_file_path = get_module_resource( 'account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create( cr, uid, dict(data_file=qif_file, )) context = { 'journal_id': self.registry('ir.model.data').get_object_reference( cr, uid, 'account', 'bank_journal')[1], 'allow_auto_create_journal': True, } self.statement_import_model.import_file(cr, uid, [bank_statement_id], context=context) line_id = self.bank_statement_line_model.search( cr, uid, [('name', '=', 'YOUR LOCAL SUPERMARKET')])[0] statement_id = self.bank_statement_line_model.browse( cr, uid, line_id).statement_id.id bank_st_record = self.bank_statement_model.browse( cr, uid, statement_id) assert float_compare(bank_st_record.balance_end_real, -1896.09, 2) == 0
def test_coda_file_import(self): cr, uid = self.cr, self.uid bank_temp_ref = self.registry('ir.model.data').get_object_reference(cr, uid, 'account', 'conf_bnk') partner_id_ref = self.registry('ir.model.data').get_object_reference(cr, uid, 'base', 'main_partner') company_id_ref = self.registry('ir.model.data').get_object_reference(cr, uid, 'base', 'main_company') self.bank_temp_id = bank_temp_ref and bank_temp_ref[1] or False self.partner_id = partner_id_ref and partner_id_ref[1] or False self.company_id = company_id_ref and company_id_ref[1] or False coda_file_path = get_module_resource('l10n_be_coda', 'test_coda_file', 'Ontvangen_CODA.2013-01-11-18.59.15.txt') coda_file = open(coda_file_path, 'rb').read().encode('base64') bank_account_id = self.registry('res.partner.bank').create(cr, uid, dict( state = 'bank', acc_number = 'BE33737018595246', bank_name = 'Reserve', partner_id = self.partner_id, company_id = self.company_id )) bank_statement_id = self.statement_import_model.create(cr, uid, dict( file_type = 'coda', data_file = coda_file, )) self.statement_import_model.parse_file(cr, uid, [bank_statement_id]) statement_id = self.bank_statement_model.search(cr, uid, [('name', '=', '135')])[0] bank_st_record = self.bank_statement_model.browse(cr, uid, statement_id) self.assertEquals(bank_st_record.balance_start, 11812.70) self.assertEquals(bank_st_record.balance_end_real, 13527.81)
def test_ods_success(self): Import = self.registry('base_import.import') ods_file_path = get_module_resource('base_import', 'tests', 'test.ods') file_content = open(ods_file_path, 'rb').read() id = Import.create(self.cr, self.uid, { 'res_model': 'base_import.tests.models.preview', 'file': file_content, 'file_type': 'application/vnd.oasis.opendocument.spreadsheet' }) result = Import.parse_preview(self.cr, self.uid, id, { 'headers': True, }) self.assertIsNone(result.get('error')) self.assertEqual(result['matches'], {0: ['name'], 1: ['somevalue'], 2: None}) self.assertEqual(result['headers'], ['name', 'Some Value', 'Counter']) self.assertItemsEqual(result['fields'], [ ID_FIELD, {'id': 'name', 'name': 'name', 'string': 'Name', 'required':False, 'fields': []}, {'id': 'somevalue', 'name': 'somevalue', 'string': 'Some Value', 'required':True, 'fields': []}, {'id': 'othervalue', 'name': 'othervalue', 'string': 'Other Variable', 'required':False, 'fields': []}, ]) self.assertEqual(result['preview'], [ ['foo', '1', '2'], ['bar', '3', '4'], ['aux', '5', '6'], ]) # Ensure we only have the response fields we expect self.assertItemsEqual(result.keys(), ['matches', 'headers', 'fields', 'preview'])
def test_statement_import(self): """Test correct creation of single statement.""" import_model = self.registry('account.bank.statement.import') statement_model = self.registry('account.bank.statement') cr, uid = self.cr, self.uid statement_path = get_module_resource( 'bank_statement_parse_camt', 'test_files', 'test-camt053.xml' ) statement_file = open( statement_path, 'rb').read().encode('base64') bank_statement_id = import_model.create( cr, uid, dict( data_file=statement_file, ) ) import_model.import_file(cr, uid, [bank_statement_id]) ids = statement_model.search( cr, uid, [('name', '=', '1234Test/1')]) self.assertTrue(ids, 'Statement not found after parse.') statement_id = ids[0] statement_obj = statement_model.browse( cr, uid, statement_id) self.assertTrue( abs(statement_obj.balance_start - 15568.27) < 0.00001, 'Start balance %f not equal to 15568.27' % statement_obj.balance_start ) self.assertTrue( abs(statement_obj.balance_end_real - 15121.12) < 0.00001, 'Real end balance %f not equal to 15121.12' % statement_obj.balance_end_real )
def getFile(self, filename): path = get_module_resource('l10n_it_fatturapa_out', 'tests', 'data', filename) with open(path) as test_data: with tempfile.TemporaryFile() as out: base64.encode(test_data, out) out.seek(0) return path, out.read()
def index(self, req, s_action=None, data=None, **kw): if 'image' in kw: image=kw['image'] else: image='pie.png' image_file=get_module_resource('html_reports', '', image) return Response(file(image_file).read(), mimetype='image/png')
def index(self, req, s_action=None, data=None, **kw): if 'image' in kw: image = kw['image'] else: image = 'pie.png' image_file = get_module_resource('html_reports', '', image) return Response(file(image_file).read(), mimetype='image/png')
def _get_default_image(self, cr, uid, context=None): url_image = context.get('url_image') if url_image not in ('',False,None): raw_data = base64.b64encode(cStringIO.StringIO(urllib.urlopen(url_image).read()).getvalue()) else: image_path = get_module_resource('hr', 'static/src/img', 'default_image.png') raw_data = open(image_path, 'rb').read().encode('base64') return tools.image_resize_image_big(raw_data)
def test_qif_file_import(self): from openerp.tools import float_compare qif_file_path = get_module_resource('account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_id = self.BankStatementImport.create(dict(data_file=qif_file,)) journal = self.env['account.journal'].create({'type': 'bank', 'name': 'bank QIF', 'code': 'BNK67'}) bank_statement_id.with_context(journal_id=journal.id).import_file() line = self.BankStatementLine.search([('name', '=', 'YOUR LOCAL SUPERMARKET')], limit=1) assert float_compare(line.statement_id.balance_end_real, -1896.09, 2) == 0
def create_single_pdf(self, cursor, uid, ids, data, report_xml, context=None): """generate the PDF""" if context is None: context={} htmls = [] if report_xml.report_type != 'webkit': return super(HeaderFooterTextWebKitParser,self).create_single_pdf(cursor, uid, ids, data, report_xml, context=context) self.parser_instance = self.parser(cursor, uid, self.name2, context=context) self.pool = pooler.get_pool(cursor.dbname) objs = self.getObjects(cursor, uid, ids, context) self.parser_instance.set_context(objs, data, ids, report_xml.report_type) template = False if report_xml.report_file: path = get_module_resource(*report_xml.report_file.split(os.path.sep)) if os.path.exists(path): template = file(path).read() if not template and report_xml.report_webkit_data: template = report_xml.report_webkit_data if not template: raise except_osv(_('Error!'), _('Webkit Report template not found !')) header = report_xml.webkit_header.html footer = report_xml.webkit_header.footer_html if not header and report_xml.header: raise except_osv( _('No header defined for this Webkit report!'), _('Please set a header in company settings') ) css = report_xml.webkit_header.css if not css: css = '' user = self.pool.get('res.users').browse(cursor, uid, uid) #default_filters=['unicode', 'entity'] can be used to set global filter body_mako_tpl = mako_template(template) helper = WebKitHelper(cursor, uid, report_xml.id, context) if report_xml.precise_mode: for obj in objs: self.parser_instance.localcontext['objects'] = [obj] try: html = body_mako_tpl.render(helper=helper, css=css, _=self.translate_call, **self.parser_instance.localcontext) htmls.append(html) except Exception, e: msg = exceptions.text_error_template().render() _logger.error(msg) raise except_osv(_('Webkit render'), msg)
def index(self, req, mod=None, **kwargs): ms = module.get_modules() manifests = dict( (name, desc) for name, desc in zip(ms, map(self.load_manifest, ms)) if desc # remove not-actually-openerp-modules ) if not mod: return NOMODULE_TEMPLATE.render(modules=( (manifest['name'], name) for name, manifest in manifests.iteritems() if any(testfile.endswith('.js') for testfile in manifest['test']) )) sorted_mods = module_topological_sort(dict( (name, manifest.get('depends', [])) for name, manifest in manifests.iteritems() )) # to_load and to_test should be zippable lists of the same length. # A falsy value in to_test indicate nothing to test at that index (just # load the corresponding part of to_load) to_test = sorted_mods if mod != '*': if mod not in manifests: return req.not_found(NOTFOUND.render(module=mod)) idx = sorted_mods.index(mod) to_test = [None] * len(sorted_mods) to_test[idx] = mod tests_candicates = [ filter(lambda path: path.endswith('.js'), manifests[mod]['test'] if mod else []) for mod in to_test] # remove trailing test-less modules tests = reversed(list( itertools.dropwhile( operator.not_, reversed(tests_candicates)))) files = [ (mod, manifests[mod]['js'], tests, manifests[mod]['qweb']) for mod, tests in itertools.izip(sorted_mods, tests) ] # if all three db_info parameters are present, send them to the page db_info = dict((k, v) for k, v in kwargs.iteritems() if k in ['source', 'supadmin', 'password']) if len(db_info) != 3: db_info = None return TESTING.render(files=files, dependencies=json.dumps( [name for name in sorted_mods if module.get_module_resource(name, 'static') if manifests[name]['js']]), db_info=json.dumps(db_info))
def _get(self, cr, uid, ids, field_name, arg, context=None): res = {} for f in self.browse(cr, uid, ids): #path = get_module_resource('hr', 'static/src/img', 'default_image.png') t = f.template_id path = get_module_resource(t.module, t.path, t.fn) if 1: #'active_id' in context: obj = self.pool.get(t.model).browse(cr, uid, f.res_id) if t.type in ['template', 'bash']: ctx = { #'context':context, 'o': obj, 't': t, 'to_ascii': to_ascii, 'value': value, 'to_ascii': to_ascii, #'html_indent':html_indent, } #print ctx try: ret = render_mako_file(path, ctx) except: logging.exception('Got exception on main handler') ret = '%s,%s,%s,%s' % (t, obj, ctx, path) elif t.type in ['python']: ret = file(path).read() ctx2 = {'o': obj} try: out_file = render_mako_str(str(t.out_fn), ctx2) except: out_file = "%s,%s" % (t, ctx2) file_ctx = {'f': f, 'o': obj} res[f.id] = { 'content_generated': ret, 'source_fn': path, 'file_generated': out_file, 'who': f.user_id.who, 'user': render_mako_str(f.template_id.target_user, file_ctx), 'group': render_mako_str(f.template_id.target_group, file_ctx), } else: res[f.id] = { 'content_generated': file(path).read(), 'source_fn': path, 'file_generated': '', 'who': f.user_id.who, 'user': render_mako_str(f.template_id.target_user, file_ctx), 'group': render_mako_str(f.template_id.target_group, file_ctx) } #fp = misc.file_open(pathname) return res
def master_data_export(self, cr, uid, ids, context=None): for m in self.browse(cr, uid, ids): path = get_module_resource(m.name, '', '__openerp__.py') mod_meta = eval(file(path).read()) files = mod_meta['update_xml'] for f in files: p, fn = os.path.split(f) #fn.split('.') model = fn[:-4] #.split('.') dest_fn = get_module_resource(m.name, p, fn) export_data(self.pool, cr, uid, model, dest_fn, db_only=True, module=m.name) #print p,fn return {'ok': 'done'}
def setUp(self): super(TestCodaFile, self).setUp() cr, uid = self.cr, self.uid self.statement_import_model = self.registry("account.bank.statement.import") self.bank_statement_model = self.registry("account.bank.statement") coda_file_path = get_module_resource("l10n_be_coda", "test_coda_file", "Ontvangen_CODA.2013-01-11-18.59.15.txt") self.coda_file = open(coda_file_path, "rb").read().encode("base64") self.context = { "journal_id": self.registry("ir.model.data").get_object_reference(cr, uid, "account", "bank_journal")[1] } self.bank_statement_id = self.statement_import_model.create(cr, uid, dict(data_file=self.coda_file))
def __init__(self, xsd_path=_DEFAULT_XSD_PATH, tmpl_dirs=None, tmpl_name=_DEFAULT_TMPL_NAME): '''tmpl_path : path to mako template''' if tmpl_dirs is None: tmpl_dirs = [] dirs = [get_module_resource('l10n_ch_sepa', self._BASE_TMPL_DIR)] for tmpl_dir in tmpl_dirs: dirs += [get_module_resource('l10n_ch_sepa', tmpl_dir)] lookup = TemplateLookup(directories=dirs, input_encoding='utf-8', output_encoding='unicode', default_filters=['unicode', 'x']) self.mako_tpl = lookup.get_template(tmpl_name) self._xml_data = None xsd_path = get_module_resource('l10n_ch_sepa', xsd_path) super(Pain001, self).__init__(xsd_path)
def create_report(self, cr, uid, res_ids, report_name=False, file_name=False): if not report_name or not res_ids: return (False, Exception("Report name and Resources ids are required !!!")) try: ret_file_name = get_module_resource("survey", "report") + file_name + ".pdf" result, format = openerp.report.render_report(cr, uid, res_ids, report_name[len("report.") :], {}, {}) fp = open(ret_file_name, "wb+") fp.write(result) fp.close() except Exception, e: print "Exception in create report:", e return (False, str(e))
def index(self, req, mod=None, **kwargs): ms = module.get_modules() manifests = dict((name, desc) for name, desc in zip(ms, map(self.load_manifest, ms)) if desc # remove not-actually-openerp-modules ) if not mod: return NOMODULE_TEMPLATE.render( modules=((manifest['name'], name) for name, manifest in manifests.iteritems() if any( testfile.endswith('.js') for testfile in manifest['test']))) sorted_mods = module_topological_sort( dict((name, manifest.get('depends', [])) for name, manifest in manifests.iteritems())) # to_load and to_test should be zippable lists of the same length. # A falsy value in to_test indicate nothing to test at that index (just # load the corresponding part of to_load) to_test = sorted_mods if mod != '*': if mod not in manifests: return req.not_found(NOTFOUND.render(module=mod)) idx = sorted_mods.index(mod) to_test = [None] * len(sorted_mods) to_test[idx] = mod tests_candicates = [ filter(lambda path: path.endswith('.js'), manifests[mod]['test'] if mod else []) for mod in to_test ] # remove trailing test-less modules tests = reversed( list(itertools.dropwhile(operator.not_, reversed(tests_candicates)))) files = [(mod, manifests[mod]['js'], tests, manifests[mod]['qweb']) for mod, tests in itertools.izip(sorted_mods, tests)] # if all three db_info parameters are present, send them to the page db_info = dict((k, v) for k, v in kwargs.iteritems() if k in ['source', 'supadmin', 'password']) if len(db_info) != 3: db_info = None return TESTING.render( files=files, dependencies=json.dumps([ name for name in sorted_mods if module.get_module_resource(name, 'static') if manifests[name]['js'] ]), db_info=json.dumps(db_info))
def create_report(self, cr, uid, res_ids, report_name=False, file_name=False): if not report_name or not res_ids: return (False, Exception('Report name and Resources ids are required !!!')) try: ret_file_name = get_module_resource('survey', 'report') + file_name + '.pdf' result, format = openerp.report.render_report(cr, uid, res_ids, report_name[len('report.'):], {}, {}) fp = open(ret_file_name, 'wb+'); fp.write(result); fp.close(); except Exception,e: print 'Exception in create report:',e return (False, str(e))
def test_qif_file_import(self): from openerp.tools import float_compare qif_file_path = get_module_resource('account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_id = self.BankStatementImport.create(dict( data_file=qif_file, )) company = self.env.user.company_id journal_vals = self.env['account.journal']._prepare_bank_journal(company, {'account_type': 'bank', 'acc_name': 'Bank Account (test import qif)'}) journal = self.env['account.journal'].create(journal_vals) bank_statement_id.with_context(journal_id=journal.id).import_file() line = self.BankStatementLine.search([('name', '=', 'YOUR LOCAL SUPERMARKET')], limit=1) assert float_compare(line.statement_id.balance_end_real, -1896.09, 2) == 0
def test_qif_file_import(self): from openerp.tools import float_compare qif_file_path = get_module_resource( 'account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_improt = self.statement_import_model.with_context( journal_id=self.ref('account.bank_journal')).create( dict(data_file=qif_file)) bank_statement_improt.import_file() bank_statement = self.statement_line_model.search( [('name', '=', 'YOUR LOCAL SUPERMARKET')], limit=1)[0].statement_id assert float_compare(bank_statement.balance_end_real, -1896.09, 2) == 0
def update_banks(self): """ Force the update of the banks from the XML file """ data_obj = self.env['ir.model.data'] entries = data_obj.search([('module', '=', MODULE), ('model', '=', 'res.bank')]) # If the records in 'ir.model.data' have noupdate to True, # the XML records won't be updated entries.write({'noupdate': False}) filepath = get_module_resource(MODULE, 'bank.xml') with closing(misc.file_open(filepath)) as fp: force_xml_import(self.env.cr, fp) entries.write({'noupdate': True}) return True
def _test_statement_import( self, module_name, file_name, statement_name, local_account=False, start_balance=False, end_balance=False, transactions=None): """Test correct creation of single statement.""" import_model = self.env['account.bank.statement.import'] partner_bank_model = self.env['res.partner.bank'] statement_model = self.env['account.bank.statement'] statement_path = get_module_resource( module_name, 'test_files', file_name ) statement_file = open( statement_path, 'rb').read().encode('base64') bank_statement_id = import_model.create( dict( data_file=statement_file, ) ) bank_statement_id.import_file() # Check wether bank account has been created: if local_account: bids = partner_bank_model.search( [('acc_number', '=', local_account)]) self.assertTrue( bids, 'Bank account %s not created from statement' % local_account ) # statement name is account number + '-' + date of last 62F line: ids = statement_model.search([('name', '=', statement_name)]) self.assertTrue( ids, 'Statement %s not found after parse.' % statement_name ) statement_obj = ids[0] if start_balance: self.assertTrue( abs(statement_obj.balance_start - start_balance) < 0.00001, 'Start balance %f not equal to expected %f' % (statement_obj.balance_start, start_balance) ) if end_balance: self.assertTrue( abs(statement_obj.balance_end_real - end_balance) < 0.00001, 'End balance %f not equal to expected %f' % (statement_obj.balance_end_real, end_balance) ) # Maybe we need to test transactions? if transactions: for transaction in transactions: self._test_transaction(statement_obj, **transaction)
def _get(self, cr, uid, ids, field_name, arg, context=None): res = {} for t in self.browse(cr, uid, ids): #path = get_module_resource('hr', 'static/src/img', 'default_image.png') if t.module and t.path and t.fn: path = get_module_resource(t.module, t.path, t.fn) if os.path.isfile(path): source = file(path).read() else: source = '' res[t.id] = {'source': source, 'source_fn': path} else: res[t.id] = {'source': 'na', 'source_fn': 'na'} return res
def test_qif_file_import(self): from openerp.tools import float_compare cr, uid = self.cr, self.uid qif_file_path = get_module_resource('account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create(cr, uid, dict( file_type='qif', data_file=qif_file, )) self.statement_import_model.parse_file(cr, uid, [bank_statement_id]) line_id = self.bank_statement_line_model.search(cr, uid, [('name', '=', 'YOUR LOCAL SUPERMARKET')])[0] statement_id = self.bank_statement_line_model.browse(cr, uid, line_id).statement_id.id bank_st_record = self.bank_statement_model.browse(cr, uid, statement_id) assert float_compare(bank_st_record.balance_end_real, -1896.09, 2) == 0
def test_aml_file_import(self): cr, uid = self.cr, self.uid aml_file_path = get_module_resource(self.module_name, 'tests', 'test_account_move_lines.csv') aml_data = open(aml_file_path, 'rb').read().encode('base64') aml_import_id = self.aml_import_model.create(cr, uid, { 'aml_data': aml_data, 'csv_separator': ';', 'decimal_separator': ',' }) self.aml_import_model.aml_import(cr, uid, [aml_import_id], {'active_id': self.am_id}) am = self.am_model.browse(cr, uid, self.am_id) self.assertEquals(am.amount, 5000.00)
def render(self, ref,mako_template,template_module='html_reports'): query=self.get(ref) template_path = get_module_resource(template_module, '', mako_template) html_ret="" if query: #self.pool.get('analysis.chart').generate_chart(self.cr, self.uid, query.id) #cr.execute( query.query ) #data=[x for x in cr.fetchall()] ctx=self.pool.get('analysis.sql.query').get_html_context(self.cr, self.uid,query.id) html_ret = render_mako_file(template_path, ctx) #image=self.pool.get('analysis.chart').browse(self.cr, self.uid, image.id) #image_url=get_image_url(self.req,'%d.png'%image.id ) #ret='<img src="%s" alt="%s"/>' % (image_url, image.name) return html_ret
def setUpClass(cls): super(L10nEsAccountBankStatementImportN43, cls).setUpClass() cls.partner = cls.env['res.partner'].create({'name': 'Test partner'}) cls.journal = cls.env['account.journal'].create({ 'type': 'bank', 'name': 'Test N43 bank', 'code': 'BNKN43', }) n43_file_path = get_module_resource( 'l10n_es_account_bank_statement_import_n43', 'tests', 'test.n43') n43_file = open(n43_file_path, 'rb').read().encode('base64') cls.import_wizard = cls.env['account.bank.statement.import'].create({ 'data_file': n43_file, })
def setUp(self): super(TestCodaFile, self).setUp() self.env['res.partner.bank'].create({ 'state': 'bank', 'acc_number': 'BE46737018594236', 'bank_bic': 'KREDBEBB', 'journal_id': self.ref('account.bank_journal'), 'partner_id': self.ref('base.main_partner'), }) fy = self.env['account.fiscalyear'].create({ 'name': 'FY 2012', 'code': '2012', 'date_start': '2012-01-01', 'date_stop': '2012-12-31', 'company_id': self.ref('base.main_company'), }) self.env['account.period'].create({ 'name': 'FP 2012-01', 'code': '2012-01', 'date_start': '2012-01-01', 'date_stop': '2012-01-31', 'fiscalyear_id': fy.id, 'company_id': self.ref('base.main_company'), }) self.statement_import_model = self.env['account.bank.statement.import'] self.bank_statement_model = self.env['account.bank.statement'] coda_file_path = get_module_resource( 'account_bank_statement_import_coda', 'test_coda_file', 'Ontvangen_CODA.2012-01-11-18.59.15.txt') self.coda_file = open(coda_file_path, 'rb').read().encode('base64') self.context = {'journal_id': self.ref('account.bank_journal')} self.bank_statement_import = self.statement_import_model.create( {'data_file': self.coda_file})
def test_aml_file_import(self): cr, uid = self.cr, self.uid aml_file_path = get_module_resource( 'account_move_import', 'tests', 'test_account_move_lines.csv') aml_data = open(aml_file_path, 'rb').read().encode('base64') aml_import_id = self.aml_import_model.create( cr, uid, {'aml_data': aml_data, 'csv_separator': ';', 'decimal_separator': ','}) self.aml_import_model.aml_import( cr, uid, [aml_import_id], {'active_id': self.am_id}) am = self.am_model.browse(cr, uid, self.am_id) self.assertEquals(am.amount, 5000.00)
def test_frances_file_import(self): from openerp.tools import float_compare frances_file_path = get_module_resource( 'account_bank_statement_import_frances', 'test_qif_file', 'test_frances.csv') frances_file = open(frances_file_path, 'rb').read().encode('base64') bank_statement_import = self.statement_import_model.with_context( journal_id=self.ref('account.bank_journal')).create( dict(data_file=frances_file)) bank_statement_import.import_file() bank_statement = self.statement_line_model.search( [('name', '=', 'TRANSFERENCIA XX0000001266940 / 100 - FRANCES NET') ], limit=1)[0].statement_id assert float_compare(bank_statement.balance_end_real, -1484.81, 2) == 0
def install_translation_po_files(self, cr, uid, module_name, config): """ Load and update all po files in the directory i18n EX: - module_name: 'sr_module' - config = {'fr_FR': [ 'fr_base.po', 'fr_hr.po', 'fr_sr_module.po', ] } """ # step 1: read po files base_language_import_obj = self.pool['base.language.import'] module_directory_path = get_module_resource(module_name.strip()) i18n_directory_path = module_directory_path + '/i18n' for key, value in config.iteritems(): # key is language code data = {} for po_file_name in value: dir_entry_path = i18n_directory_path + '/' + po_file_name if os.path.isfile(dir_entry_path): with open(dir_entry_path, 'rb') as my_file: binary_string = my_file.read().encode('base64') data[po_file_name] = binary_string # step 2: for each po file, create a record of model # base.language.import base_language_import_ids = [] for po_data in data.values(): vals = { 'code': key, 'data': po_data, 'name': key, 'overwrite': True } new_id = base_language_import_obj.create(cr, uid, vals) if new_id: base_language_import_ids.append(new_id) # step 3: for each record of model base.language.import, call # function import_lang for base_language_import_id in base_language_import_ids: base_language_import_obj.import_lang( cr, uid, [base_language_import_id]) return True
def test_qif_file_import(self): from openerp.tools import float_compare cr, uid = self.cr, self.uid qif_file_path = get_module_resource('account_bank_statement_import_qif', 'test_qif_file', 'test_qif.qif') qif_file = open(qif_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create(cr, uid, dict( data_file=qif_file, )) context = { 'journal_id': self.registry('ir.model.data').get_object_reference(cr, uid, 'account', 'bank_journal')[1] } self.statement_import_model.import_file(cr, uid, [bank_statement_id], context=context) line_id = self.bank_statement_line_model.search(cr, uid, [('name', '=', 'YOUR LOCAL SUPERMARKET')])[0] statement_id = self.bank_statement_line_model.browse(cr, uid, line_id).statement_id.id bank_st_record = self.bank_statement_model.browse(cr, uid, statement_id) assert float_compare(bank_st_record.balance_end_real, -1896.09, 2) == 0
def index(self, req, s_action=None, data=None, **kw): if 'db' in kw: dbname=kw['db'] else: dbname='pjb_live' html_ret="" uid=1 registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) ctx={'image':image( req, dbname, pool, cr, uid ), 'table':table( req, dbname, pool, cr, uid ), } template_path = get_module_resource('html_reports', '', 'kpi.html') html_ret = render_mako_file(template_path, ctx) return Response(html_ret, mimetype='text/html')
def index(self, req, s_action=None, data=None, **kw): image=kw['image'] #if 'db' in kw: # dbname=kw['db'] #else: # dbname='pjb_live' # #print '/get_image', image #uid=1 #registry = openerp.modules.registry.Registry(dbname) #with registry.cursor() as cr: # pool = pooler.get_pool(dbname) # img_content = pool.get('analysis.chart').generate_chart(cr, uid, int(image) ) image_file=get_module_resource('galtys_analysis', '', image+'.png') print 'image_file', image_file img_content=file(image_file).read() return Response(img_content, mimetype='image/png')
def create_single_pdf(self, cursor, uid, ids, data, report_xml, context=None): """generate the PDF""" if context is None: context={} if report_xml.report_type != 'tex': return super(LatexParser,self).create_single_pdf(cursor, uid, ids, data, report_xml, context=context) self.parser_instance = self.parser(cursor, uid, self.name2, context=context) self.pool = pooler.get_pool(cursor.dbname) objs = self.getObjects(cursor, uid, ids, context) self.parser_instance.set_context(objs, data, ids, report_xml.report_type) template = False resource_path = None if report_xml.report_file : # backward-compatible if path in Windows format report_path = report_xml.report_file.replace("\\", "/") path = get_module_resource(*report_path.split('/')) if path and os.path.exists(path) : resource_path = os.path.dirname(path) template = file(path).read() if not template : raise osv.except_osv(_('Error!'), _('Latex report template not found!')) body_mako_tpl = mako_template(template) helper = LatexHelper(cursor, uid, report_xml.id, context) try : tex = body_mako_tpl.render(helper=helper, _=self.translate_call, tex=helper.texescape, **self.parser_instance.localcontext) except Exception: msg = exceptions.text_error_template().render() _logger.error(msg) raise osv.except_osv(_('Latex render!'), msg) finally: _logger.info("Removing temporal directory from helper.") del helper bin = self.get_lib(cursor, uid) pdf = self.generate_pdf(bin, report_xml, tex, resource_path=resource_path) return (pdf, 'pdf')
def test_ofx_file_import(self): try: from ofxparse import OfxParser as ofxparser except ImportError: #the Python library isn't installed on the server, the OFX import is unavailable and the test cannot be run return True cr, uid = self.cr, self.uid ofx_file_path = get_module_resource('account_bank_statement_import_ofx', 'test_ofx_file', 'test_ofx.ofx') ofx_file = open(ofx_file_path, 'rb').read().encode('base64') bank_statement_id = self.statement_import_model.create(cr, uid, dict( data_file=ofx_file, )) self.statement_import_model.import_file(cr, uid, [bank_statement_id]) statement_id = self.bank_statement_model.search(cr, uid, [('name', '=', '000000123')])[0] bank_st_record = self.bank_statement_model.browse(cr, uid, statement_id) self.assertEquals(bank_st_record.balance_start, 2156.56) self.assertEquals(bank_st_record.balance_end_real, 1796.56)
def _get_resource_paths(self, filter_fn=None): """ Get full path of each one of the resources (files) in module :filter (function): filter function `fn(parents, name, contents)` :return: list with full resource paths """ paths = [] tree = get_module_filetree(self.name, dir='.') pyc_args_list = self._get_paths_args(tree, filter_fn) for pyc_args in pyc_args_list: rel_path = dir_sep.join(pyc_args) full_path = get_module_resource(self.name, rel_path) paths.append(full_path) return paths
def test_ofx_file_import(self): ofx_file_path = get_module_resource( 'account_bank_statement_import_ofx', 'test_ofx_file', 'test_ofx.ofx') ofx_file = open(ofx_file_path, 'rb').read().encode('base64') bank_statement = self.statement_import_model.create( dict(data_file=ofx_file)) bank_statement.import_file() bank_st_record = self.bank_statement_model.search( [('name', '=', '000000123')])[0] self.assertEquals(bank_st_record.balance_start, 2156.56) self.assertEquals(bank_st_record.balance_end_real, 1796.56) line = bank_st_record.line_ids[0] self.assertEquals(line.name, 'Agrolait') self.assertEquals(line.ref, '219378') self.assertEquals(line.partner_id.id, self.ref('base.res_partner_2')) self.assertEquals( line.bank_account_id.id, self.ref('account_bank_statement_import.ofx_partner_bank_1'))
def test_statement_import(self): """Test correct creation of single statement.""" import_model = self.registry("account.bank.statement.import") statement_model = self.registry("account.bank.statement") cr, uid = self.cr, self.uid statement_path = get_module_resource("bank_statement_parse_camt", "test_files", "test-camt053.xml") statement_file = open(statement_path, "rb").read().encode("base64") bank_statement_id = import_model.create(cr, uid, dict(data_file=statement_file)) import_model.import_file(cr, uid, [bank_statement_id]) ids = statement_model.search(cr, uid, [("name", "=", "1234Test/1")]) self.assertTrue(ids, "Statement not found after parse.") statement_id = ids[0] statement_obj = statement_model.browse(cr, uid, statement_id) self.assertTrue( abs(statement_obj.balance_start - 15568.27) < 0.00001, "Start balance %f not equal to 15568.27" % statement_obj.balance_start, ) self.assertTrue( abs(statement_obj.balance_end_real - 15121.12) < 0.00001, "Real end balance %f not equal to 15121.12" % statement_obj.balance_end_real, )
def index(self, req, s_action=None, data=None, **kw): if 'db' in kw: dbname=kw['db'] else: dbname='pjb_live' html_ret="" uid=1 registry = openerp.modules.registry.Registry(dbname) with registry.cursor() as cr: pool = pooler.get_pool(dbname) query_ids=pool.get("analysis.sql.query").search(cr,uid,[]) queries = pool.get("analysis.sql.query").browse(cr,uid,query_ids) ctx={'title' : "List of SQL Queries", 'sql_queries': queries, 'get_query_url': get_query_url, 'req':req, 'dbname':dbname, } template_path = get_module_resource('html_reports', '', 'sql_query_list.html') html_ret = render_mako_file(template_path, ctx) return Response(html_ret, mimetype='text/html')
def _check_xml_id_unachievable(self, xmlid): """Check a unachievable xml_id referenced """ self.ensure_one() module = self.env['ir.module.module'] imd_new = get_file_info() module_curr_str = imd_new.get('module_real') module_ref_str = xmlid.split('.')[0] if not module_curr_str or not module_ref_str or \ module_ref_str == module_curr_str: return True # TODO: Add a cache of tree of depends module_curr = module.search([('name', '=', module_curr_str)], limit=1) module_curr_dep_ids = module_curr._get_module_upstream_dependencies( module_curr.ids, exclude_states=['uninstallable', 'to remove']) module_curr_deps = module.browse(module_curr_dep_ids).mapped('name') for mod_autinst in module.search([ ('auto_install', '=', True), ('name', 'not in', module_curr_deps)]): # TODO: Get recursively the auto_install of auto_install modules mod_autinst_deps = mod_autinst.dependencies_id.mapped('name') if not mod_autinst_deps or \ set(mod_autinst_deps).issubset(set(module_curr_deps)): module_curr_deps.append(mod_autinst.name) if module_curr_deps and module_ref_str not in module_curr_deps: file_path = os.path.join( get_module_resource(imd_new['module_real']), imd_new['file_name']) # TODO: Use a cache of file content file_content = open(file_path).read() # TODO: Validate all xmlid cases, e.g. model_ in csv if xmlid in file_content: # Many times a ref id is used from a default or inherit method # If the xml_id is in the content of the file, then is a real _logger.warning("The xml_id '%s' is unachievable.", xmlid) return False return True
def _search_in_files(self, mod_name, files, identifier): """ Returns the path of the first file in list which contains the given external identifier (name) :param mod_name (bool): module name to get root path :param files ([basestring]): XML file paths list :param identifier (basestring): external identifier without module :return: path of the file or None """ mod_name = mod_name xpath = './/record[@id=\'{}\']'.format(identifier) for f in files: path = get_module_resource(mod_name, f) tree = ElementTree.parse(path) root = tree.getroot() if root.findall(xpath): return f return None