Beispiel #1
0
 def upload_report(self,
                   cr,
                   uid,
                   report_id,
                   file_sxw,
                   file_type,
                   context=None):
     '''
     Untested function
     '''
     pool = pooler.get_pool(cr.dbname)
     sxwval = StringIO(base64.decodestring(file_sxw))
     if file_type == 'sxw':
         fp = open(
             addons.get_module_resource('base_report_designer',
                                        'openerp_sxw2rml',
                                        'normalized_oo2rml.xsl'), 'rb')
     if file_type == 'odt':
         fp = open(
             addons.get_module_resource('base_report_designer',
                                        'openerp_sxw2rml',
                                        'normalized_odt2rml.xsl'), 'rb')
     report = pool.get('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())),
         })
     pool.get('ir.actions.report.xml').register_all(cr)
     return True
Beispiel #2
0
    def update_translations(self, cr, uid, ids, filter_lang=None, context={}):
        logger = logging.getLogger('i18n')
        if not filter_lang:
            pool = pooler.get_pool(cr.dbname)
            lang_obj = pool.get('res.lang')
            lang_ids = lang_obj.search(cr, uid, [('translatable', '=', True)])
            filter_lang = [
                lang.code for lang in lang_obj.browse(cr, uid, lang_ids)
            ]
        elif not isinstance(filter_lang, (list, tuple)):
            filter_lang = [filter_lang]

        for mod in self.browse(cr, uid, ids):
            if mod.state != 'installed':
                continue
            modpath = addons.get_module_path(mod.name)
            if not modpath:
                # unable to find the module. we skip
                continue
            for lang in filter_lang:
                iso_lang = tools.get_iso_codes(lang)
                f = addons.get_module_resource(mod.name, 'i18n',
                                               iso_lang + '.po')
                context2 = context and context.copy() or {}
                if f and '_' in iso_lang:
                    iso_lang2 = iso_lang.split('_')[0]
                    f2 = addons.get_module_resource(mod.name, 'i18n',
                                                    iso_lang2 + '.po')
                    if f2:
                        logger.info(
                            'module %s: loading base translation file %s for language %s',
                            mod.name, iso_lang2, lang)
                        tools.trans_load(cr,
                                         f2,
                                         lang,
                                         verbose=False,
                                         context=context)
                        context2['overwrite'] = True
                # Implementation notice: we must first search for the full name of
                # the language derivative, like "en_UK", and then the generic,
                # like "en".
                if (not f) and '_' in iso_lang:
                    iso_lang = iso_lang.split('_')[0]
                    f = addons.get_module_resource(mod.name, 'i18n',
                                                   iso_lang + '.po')
                if f:
                    logger.info(
                        'module %s: loading translation file (%s) for language %s',
                        mod.name, iso_lang, lang)
                    tools.trans_load(cr,
                                     f,
                                     lang,
                                     verbose=False,
                                     context=context2)
                elif iso_lang != 'en':
                    logger.warning('module %s: no translation for language %s',
                                   mod.name, iso_lang)
        tools.trans_update_res_ids(cr)
 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(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb')
     if file_type=='odt':
         fp = open(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb')
     return  {'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read()))}
Beispiel #4
0
    def _translations_subdir(self, module):
        """ Returns the path to the subdirectory holding translations for the
        module files, or None if it can't find one

        :param module: a module object
        :type module: browse(ir.module.module)
        """
        subdir = addons.get_module_resource(module.name, 'po')
        if subdir: return subdir
        # old naming convention
        subdir = addons.get_module_resource(module.name, 'i18n')
        if subdir: return subdir
        return None
    def _translations_subdir(self, module):
        """ Returns the path to the subdirectory holding translations for the
        module files, or None if it can't find one

        :param module: a module object
        :type module: browse(ir.module.module)
        """
        subdir = addons.get_module_resource(module.name, 'po')
        if subdir: return subdir
        # old naming convention
        subdir = addons.get_module_resource(module.name, 'i18n')
        if subdir: return subdir
        return None
Beispiel #6
0
    def update_translations(self, cr, uid, ids, filter_lang=None, context=None):
        if context is None:
            context = {}
        logger = logging.getLogger('i18n')
        if not filter_lang:
            pool = pooler.get_pool(cr.dbname)
            lang_obj = pool.get('res.lang')
            lang_ids = lang_obj.search(cr, uid, [('translatable', '=', True)])
            filter_lang = [lang.code for lang in lang_obj.browse(cr, uid, lang_ids)]
        elif not isinstance(filter_lang, (list, tuple)):
            filter_lang = [filter_lang]

        msf_profile_id = self.pool.get('ir.module.module').search(cr, uid, [('name', '=', 'msf_profile')])
        if msf_profile_id and msf_profile_id[0] in ids:
            ids.remove(msf_profile_id[0])
            # load msf_profile file at the end (due to es.po file, terms are always overwritten)
            ids.append(msf_profile_id[0])

        for mod in self.browse(cr, uid, ids):
            if mod.state != 'installed':
                continue
            modpath = addons.get_module_path(mod.name)
            if not modpath:
                # unable to find the module. we skip
                continue
            for lang in filter_lang:
                iso_lang = tools.get_iso_codes(lang)
                f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
                context2 = context and context.copy() or {}
                if f and '_' in iso_lang:
                    iso_lang2 = iso_lang.split('_')[0]
                    f2 = addons.get_module_resource(mod.name, 'i18n', iso_lang2 + '.po')
                    if f2:
                        logger.info('module %s: loading base translation file %s for language %s', mod.name, iso_lang2, lang)
                        tools.trans_load(cr, f2, lang, verbose=False, context=context)
                        context2['overwrite'] = True
                # Implementation notice: we must first search for the full name of
                # the language derivative, like "en_UK", and then the generic,
                # like "en".
                if (not f) and '_' in iso_lang:
                    iso_lang = iso_lang.split('_')[0]
                    f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
                if f:
                    logger.info('module %s: loading translation file (%s) for language %s', mod.name, iso_lang, lang)
                    tools.trans_load(cr, f, lang, verbose=False, context=context2)
                elif iso_lang != 'en':
                    logger.warning('module %s: no translation for language %s', mod.name, iso_lang)
        tools.trans_update_res_ids(cr)
 def execute(self, cr, uid, ids, context=None):
     """Override of code in order to be able to link journal with account in XML"""
     res = super(WizardMultiChartsAccounts, self).execute(cr, uid, ids, context)
     path = addons.get_module_resource('l10n_ch','sterchi_chart','account_journal_rel.xml')
     tools.convert_xml_import(cr, 'l10n_ch', path, idref=None, mode='init', noupdate=True, report=None)
     res.update({'type': 'ir.actions.act_window_close'})
     return res
def get_7z():
    if os.name == 'nt':
        return get_module_resource('msf_homere_interface', 'wizard', '7za.exe')
    try:
        return which('7z')
    except:
        raise osv.except_osv(_('Error'), _('7z is not installed on the server. Please install the package p7zip-full'))
Beispiel #9
0
    def get_web(self, cr, uid, names, context=None):
        """Returns the web content of all the named addons.
        
        get_web(cr, uid, [module_name], context) -> [{name, depends, content}]

        The toplevel directory of the zipped content is called 'web',
        its final naming has to be managed by the client
        """
        mod_ids = self.search(cr, uid, [('name', 'in', names)], context=context)
        # TODO: browse_search
        if not mod_ids:
            return []
        res = []
        for module in self.browse(cr, uid, mod_ids, context=context):
            web_dir = addons.get_module_resource(module.name, 'web')
            if not web_dir:
                continue
            web_data = addons.zip_directory(web_dir, False)
            if self._translations_subdir(module):
                web_data = self._add_translations(module, web_data)
            res.append({
                'name': module.name,
                'version': module.installed_version,
                'depends': list(self._web_dependencies(
                            cr, uid, module, context=context)),
                'content': base64.encodestring(web_data)
            })
            
        self.__logger.debug('Sending web content of modules %s to web client',    
                    [ r['name'] for r in res])
        return res
Beispiel #10
0
 def create(self, cr, uid, ids, datas, context=None):
     pool = pooler.get_pool(cr.dbname)
     
     color = ''
     if datas['form']['data']['color']:
         color = 'COLOUR CODE : ' + datas['form']['data']['color']  
     
     result = {
               'no' : datas['form']['data']['no'],
               'urgent' : datas['form']['data']['urgent'],
               'weight' : datas['form']['data']['weight'],
               'measurement' : datas['form']['data']['measurement'],
               'name' : datas['form']['data']['name'],
               'attention' : datas['form']['data']['attention'],
               'date' : time.strftime('     %B %Y', time.strptime(datas['form']['data']['date'],'%Y-%m-%d %H:%M:%S')),
               'reference': datas['form']['data']['reference'],
               'purchase' : 'Purchase Order No.' + datas['form']['data']['purchase'] + ', Tgl. ' + time.strftime('%d/%m/%Y', time.strptime(datas['form']['data']['pur_date'],'%Y-%m-%d')),
               'color': color,
               'qty': datas['form']['data']['qty'],
               'product': datas['form']['data']['product'],
               'totalitem': 'Total :    Item',
               'totalbox': 'Total :    Box',
     }
     
     
     tmp_file = tempfile.mkstemp(".pdf")[1]
     try:
         fill_pdf(addons.get_module_resource('ad_delivery_note','report','paketA4.pdf'), tmp_file, result)
         with open(tmp_file, "r") as ofile:
             self.obj = external_pdf(ofile.read())
     finally:
         os.remove(tmp_file)    
     self.obj.render()
     return (self.obj.pdf, 'pdf')
 def get_relation_graph(self, cr, uid, module_name, context=None):
     if context is None: context = {}
     object_ids = self._get_module_objects(cr,
                                           uid,
                                           module_name,
                                           context=context)
     if not object_ids:
         return {'module_file': False}
     context.update({'level': 1})
     dots = self.get_graphical_representation(cr,
                                              uid,
                                              object_ids,
                                              context=context)
     # todo: use os.realpath
     file_path = addons.get_module_resource('base_module_doc_rst')
     path_png = file_path + "/module.png"
     for key, val in dots.items():
         path_dotfile = file_path + "/%s.dot" % (key, )
         fp = file(path_dotfile, "w")
         fp.write(val)
         fp.close()
     os.popen('dot -Tpng' + ' ' + path_dotfile + ' ' + '-o' + ' ' +
              path_png)
     fp = file(path_png, "r")
     x = fp.read()
     fp.close()
     os.popen('rm ' + path_dotfile + ' ' + path_png)
     return {'module_file': base64.encodestring(x)}
Beispiel #12
0
    def default_get(self, cr, uid, fields, context=None):
        pref_obj = self.pool.get('user.preference')
        pref_ids = pref_obj.browse(cr, uid ,context.get('rec_id',False), context=context)
        res = {}
        host = context.get('host')
        port = ''
        prefix = 'http://'
        if not config.get('xmlrpc'):
            if not config.get('netrpc'):
                prefix = 'https://'
                port = config.get('xmlrpcs_port', 8071)
            else:
                port = config.get('netrpc_port',8070)
        else:
            port = config.get('xmlrpc_port',8069)
        if not config.get_misc('webdav','enable',True):
            raise Exception("WebDAV is disabled, cannot continue")
        user_pool = self.pool.get('res.users')
        current_user = user_pool.browse(cr, uid, uid, context=context)
        #TODO write documentation
        res['description'] = self.__doc['other']
        if pref_ids:
            pref_ids = pref_ids[0]
            if pref_ids.device == 'iphone':
                url = host + ':' + str(port) + '/'+ pref_ids.service + '/' + cr.dbname + '/'+'calendars/'
            else :
                url = host + ':' + str(port) + '/'+ pref_ids.service + '/' + cr.dbname + '/'+'calendars/'+ 'users/'+ current_user.login + '/'+ pref_ids.collection.name+ '/'+ pref_ids.calendar.name

            res['description'] = self.__doc.get(pref_ids.device , self.__doc['other'])
        file = open(addons.get_module_resource('caldav','doc', 'caldav_doc.pdf'),'rb')
        res['caldav_doc_file'] = base64.encodestring(file.read())

        #res['doc_link'] = 'http://doc.openerp.com/'
        res['url'] = prefix+url
        return res
 def upload_report(self, cr, uid, report_id, file_sxw, file_type, context=None):
     '''
     Untested function
     '''
     pool = pooler.get_pool(cr.dbname)
     sxwval = StringIO(base64.decodestring(file_sxw))
     if file_type=='sxw':
         fp = open(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_oo2rml.xsl'),'rb')
     if file_type=='odt':
         fp = open(addons.get_module_resource('base_report_designer','openerp_sxw2rml', 'normalized_odt2rml.xsl'),'rb')
     report = pool.get('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())), 
     })
     pool.get('ir.actions.report.xml').register_all(cr)
     return True
Beispiel #14
0
 def create(self, cr, uid, ids, datas, context=None):
     pool = pooler.get_pool(cr.dbname)
     
     result = {
               'name' : datas['form']['data']['name'],
               'date' : time.strftime('%d %B %Y', time.strptime(datas['form']['data']['kontrakdate'],'%Y-%m-%d')),
               'tanggal' : time.strftime('%d %B %Y', time.strptime(datas['form']['data']['date'],'%Y-%m-%d')),
               'kirim' : time.strftime('%d %B %Y', time.strptime(datas['form']['data']['delivery_date'],'%Y-%m-%d')),
               'order': datas['form']['data']['kontrak'],
               'qty': datas['form']['data']['qty'],
               'partner': datas['form']['data']['partner_id'][1],
               'product': datas['form']['data']['product'].encode('latin9'),
               'creator': datas['form']['data']['creator'],
               'checker': datas['form']['data']['checker'],
               'approver': datas['form']['data']['approver']
     }
     
     
     tmp_file = tempfile.mkstemp(".pdf")[1]
     try:
         fill_pdf(addons.get_module_resource('sbm_spk_internal','report','perintahA4.pdf'), tmp_file, result)
         with open(tmp_file, "r") as ofile:
             self.obj = external_pdf(ofile.read())
     finally:
         os.remove(tmp_file)    
     self.obj.render()
     return (self.obj.pdf, 'pdf')
Beispiel #15
0
 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(
             addons.get_module_resource('base_report_designer',
                                        'openerp_sxw2rml',
                                        'normalized_oo2rml.xsl'), 'rb')
     if file_type == 'odt':
         fp = open(
             addons.get_module_resource('base_report_designer',
                                        'openerp_sxw2rml',
                                        'normalized_odt2rml.xsl'), 'rb')
     return {'report_rml_content': str(sxw2rml(sxwval, xsl=fp.read()))}
Beispiel #16
0
	def create_single_pdf(self, cr, uid, ids, data, report_xml, context=None):
		"""generate the PDF"""
		if context is None:
			context={}
		htmls = []
		self.parser_instance = self.parser(cr, uid, self.name2, context=context)

		self.pool = pooler.get_pool(cr.dbname)
		objs = self.getObjects(cr, uid, ids, context)
		self.parser_instance.set_context(objs, data, ids, report_xml.report_type)

		template =  False
		if report_xml.report_file :
			path = addons.get_module_resource(report_xml.report_file)
			if os.path.exists(path) :
				template = file(path).read()
		if not template and report_xml.m2pdf_data:
			template =  report_xml.m2pdf_data
		if not template :
			raise except_osv(_('Error!'), _('Report template not found!'))

		body_mako_tpl = mako_template(template)
		helper = WebXHtmlHelper(cr, uid, report_xml.id, context)

		css = ''
		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()
			raise except_osv(_('XHtml2Pdf render'), msg)
Beispiel #17
0
    def run_test(self, cr, uid, module_path):
        config_file_path = addons.get_module_resource('base_module_quality','pylint_test', 'pylint_test_config.txt')
        list_files = os.listdir(module_path)
        for i in list_files:
            path = os.path.join(module_path, i)
            if os.path.isdir(path):
                for j in os.listdir(path):
                    list_files.append(os.path.join(i, j))

        count = 0
        score = 0.0
        dict_py = {}
        flag = False
        self.result_details += '''<html><body><head>%s</head>'''%(self.get_style())
        for file_py in list_files:
            if file_py.split('.')[-1] == 'py' and not file_py.endswith('__init__.py') and not file_py.endswith('__openerp__.py'):
                if not flag:
                    flag = True
                file_path = os.path.join(module_path, file_py)
                try:
                    res = os.popen('pylint --rcfile=' + config_file_path + ' ' + file_path).read()
                except Exception:
                    self.error = True
                    self.log.exception("Cannot run pylint test for %s", file_path)
                    self.result += _("Error. Is pylint correctly installed? (http://pypi.python.org/pypi/pylint)")+"\n"
                    return None
                count += 1
                try:
                    scr = res.split("Your code has been rated at")[1].split("</div>")[0].split("/")[0]
                    score += float(scr)
                    dict_py[file_py] = [file_py, scr]
                except Exception:
                    self.log.warning("Cannot parse pylint result", exc_info=True)
                    score += 0
                    dict_py[file_py] = [file_py, _("Unable to parse the result. Check the details.")]
                replace_string = ''
                replace_string += res
                replace_string = replace_string.replace('''<div''', '''<div class="divstyle" ''')
                replace_string = replace_string.replace('''<h1''', '''<h1 style="font-size:188%" class="head" ''')
                replace_string = replace_string.replace('''<h2''', '''<h2 style="font-size:150%" class="head" ''')
                replace_string = replace_string.replace('''<h3''', '''<h3 style="font-size:132%" class="head" ''')
                replace_string = replace_string.replace('''<h4''', '''<h4 style="font-size:116%" class="head" ''')
                replace_string = replace_string.replace('''<h5''', '''<h5 style="font-size:100%" class="head" ''')
                replace_string = replace_string.replace('''<h6''', '''<h6 style="font-size:80%" class="head" ''')
                replace_string = replace_string.replace('''<table''', '''<table class="tablestyle" ''')
                replace_string = replace_string.replace('''<th''', '''<th class="tdatastyle" ''')
                replace_string = replace_string.replace('''<td''', '''<td class="tdatastyle" ''')
                self.result_details += replace_string

        if not flag:
            self.error = True
            self.result = _("No python file found")
            return None
        self.result_details += '</body></html>'
        average_score = count and score / count or score
        self.score = (max(average_score, 0)) / 10
        if self.score*100 < self.min_score:
            self.message = 'Score is below than minimal score(%s%%)' % self.min_score
        self.result = self.get_result(dict_py)
        return None
    def get_web(self, cr, uid, names, context=None):
        """ get_web(cr, uid, [module_name], context) -> [{name, depends, content}]

        Returns the web content of all the named addons.

        The toplevel directory of the zipped content is called 'web',
        its final naming has to be managed by the client
        """
        modules = self.browse(cr, uid,
            self.search(cr, uid, [('name', 'in', names)], context=context),
                              context=context)
        if not modules: return []
        self.__logger.info('Sending web content of modules %s '
                           'to web client', names)

        modules_data = []
        for module in modules:
            web_data = addons.zip_directory(
                addons.get_module_resource(module.name, 'web'), False)
            if self._translations_subdir(module):
                web_data = self._add_translations(module, web_data)
            modules_data.append({
                'name': module.name,
                'version': module.installed_version,
                'depends': list(self._web_dependencies(
                    cr, uid, module, context=context)),
                'content': base64.encodestring(web_data)
            })
        return modules_data
def pdf_fill(orig_pdf,vals):
    #vals = decode_vals(vals)
    orig_pdf_abs = os.path.join(os.getcwd(),orig_pdf)
    tmp = tempfile.mkstemp(".pdf")[1]
    print "========="
    print 'orig_pdf = ',orig_pdf
    print "========="
    print 'vals = ',vals
    print "========="
    print 'orig_pdf_abs = ',orig_pdf_abs
    print "========="
    tools.pdf_utils.fill_pdf(addons.get_module_resource('ad_account_indonesia','report','pdf','spt_masa_ppn_1111a.pdf'), tmp, vals)
    #tools.pdf_utils.fill_pdf(orig_pdf, tmp, vals)
    print 'rrrrrrrrrrrrrrrrrrr'

    try:
        tools.pdf_utils.fill_pdf(orig_pdf, tmp, vals)
        with open(tmp, "r") as ofile:
            self.obj = external_pdf(ofile.read())
    finally:
        try:
            os.remove(tmp_file)
        except:
            pass # nothing to do
    print "========="
    print "aaaaa"
    print "========="
    
    self.obj.render()
    pdf = self.obj.pdf
    return pdf
def parse_ovo_xls_file(xls_file,db,user,host,password,pricelist_name, wizard_obj):
    rb = xlrd.open_workbook(xls_file,formatting_info=False,encoding_override='utf-8-sig')
    final_lst = []
    
    for sheet in [0,1]:
        file = addons.get_module_resource('import_xls/csv_data', 'ovo_master.csv')
        worksheet = rb.sheet_by_index(sheet)
        region_values = [u'Region', u'P3 Better Energy standing charge', u'P3 Better Energy unit rate', u'P3 Greener Energy standing charge', u'P3 Greener Energy unit rate', u'P4 Better Energy standing charge', u'P4 Better Energy Day unit rate', u'P4 Better Energy Night unit rate', u'P4 Greener Energy standing charge', u'P4 Greener Energy Day unit rate', u'P4 Greener Energy Night unit rate', '', '', '', '']
        data_lst = []
        if sheet == 0:
            product_values = {
                              'Baserate':{
                                          '1 year Electricity' : [2,3,4,5,6,7,8,9,10,11,12,13,14,15
                                                                  ],
                                          '2 year Electricity' : [20,21,22,23,24,25,26,27,28,29,30,31,32,33
                                                                  ]
                                        },
                            }
            sheet_1_data = first_sheet.sheet_1_ovo_price(file,product_values, worksheet,region_values,pricelist_name,sheet)
            final_lst +=sheet_1_data

        elif sheet == 1:
            product_values = {
                              'Nightsaver':{
                                          '1 year Electricity' : [2,3,4,5,6,7,8,9,10,11,12,13,14,15
                                                                  ],
                                          '2 year Electricity' : [20,21,22,23,24,25,26,27,28,29,30,31,32,33
                                                                  ]
                                        },
                            }
            sheet_2_data = first_sheet.sheet_1_ovo_price(file,product_values, worksheet,region_values,pricelist_name,sheet)
            final_lst +=sheet_2_data
    pricelist.import_pricelist_ovo(db,user,host,password,final_lst)
    return final_lst
def parse_bg_ele_xls_file(xls_file,db,pricelist_name, wizard_obj):
    user = wizard_obj.postgres_config_id.db_user
    host = wizard_obj.postgres_config_id.host_name
    password = wizard_obj.postgres_config_id.db_user_pass
    utility_type = wizard_obj.categ_id and wizard_obj.categ_id.name or False 
    rb = xlrd.open_workbook(xls_file,formatting_info=False)
    final_lst = []
    for sheet in ['Range 1','Range 2','Range 3']:
        product_values = {
                        'ELECTRICITY 1 YEAR CONTRACT': {'start_col': 0,'end_col':7},
                        'ELECTRICITY 2 YEAR CONTRACT': {'start_col': 8,'end_col':15},
                          'ELECTRICITY 3 YEAR CONTRACT': {'start_col': 16,'end_col':23}
                          }
        if sheet == 'Range 1':
            min = 0.0
            max = 11999.00
        elif sheet == 'Range 2':
            min = 12000.00
            max = 50999.00
        elif sheet == 'Range 3':
            min = 51000.00
            max = 51000.00
        worksheet = rb.sheet_by_name(sheet)
        col_values = worksheet.row_values(1,start_colx=0, end_colx=7)
    #     print "________col_values______________",col_values
        data_lst = []
        file_gas = addons.get_module_resource('import_xls/csv_data', 'master_bg_ele.csv')
        sheet_1_data_gas,product_lst = first_sheet.sheet_1_bg_ele_price(file_gas,col_values,worksheet,pricelist_name,product_values,min,max)
#     product_import = pricelist.import_pricelist_bg_gas_product(db,user,host,password,product_lst,utility_type)
    pricelist.import_pricelist_bg_gas(db,user,host,password,sheet_1_data_gas,utility_type)
    final_lst += sheet_1_data_gas
    return final_lst
    def default_get(self, cr, uid, fields, context=None):
        pref_obj = self.pool.get('user.preference')
        pref_ids = pref_obj.browse(cr,
                                   uid,
                                   context.get('rec_id', False),
                                   context=context)
        res = {}
        host = context.get('host')
        if not config.get_misc('webdav', 'enable', True):
            raise Exception("WebDAV is disabled, cannot continue")
        user_pool = self.pool.get('res.users')
        current_user = user_pool.browse(cr, uid, uid, context=context)
        #TODO write documentation
        res['description'] = self.__doc['other']
        if pref_ids:
            pref_ids = pref_ids[0]
            if pref_ids.device == 'iphone':
                url = host + '/' + pref_ids.service + '/' + cr.dbname + '/' + 'calendars/'
            else:
                url = host + '/' + pref_ids.service + '/' + cr.dbname + '/' + 'calendars/' + 'users/' + current_user.login + '/' + pref_ids.collection.name + '/' + pref_ids.calendar.name

            res['description'] = self.__doc.get(pref_ids.device,
                                                self.__doc['other'])
        file = open(
            addons.get_module_resource('caldav', 'doc', 'caldav_doc.pdf'),
            'rb')
        res['caldav_doc_file'] = base64.encodestring(file.read())

        #res['doc_link'] = 'http://doc.openerp.com/'
        res['url'] = url
        return res
Beispiel #23
0
 def create(self, cr, uid, ids, datas, context=None):
     pool = pooler.get_pool(cr.dbname)
     
     kwitansi = '-'
     if datas['form']['data']['kwitansi']:
         kwitansi = datas['form']['data']['kwitansi']
         
     result = {
               'name' : 'INV : ' + kwitansi,
               'fakturpajak' : datas['form']['data']['faktur_pajak_no'],
               
               'supra' : datas['form']['data']['company_id'][1],
               'alamatsupra' : datas['form']['data']['alamatsupra'],  
               'npwpsupra' : datas['form']['data']['npwpsupra'],
               
               'customer' : datas['form']['data']['partner_id'][1],
               'alamatcustomer' : datas['form']['data']['alamatcustomer'],
               'npwpcustomer' : datas['form']['data']['npwpcustomer'],
               
               'no' : datas['form']['data']['no'],
               'qty': datas['form']['data']['qty'],
               'product': datas['form']['data']['product'].encode('latin9'),
               'valas' : datas['form']['data']['valas'],
               'rupiah' : datas['form']['data']['rupiah'],
               
               'vtotal' : datas['form']['data']['vtotal'],
               'vdiskon' : datas['form']['data']['vdiskon'],
               'vkenapajak' : datas['form']['data']['vtotal'],
               'vpajak' : datas['form']['data']['vpajak'],
               
               'rtotal' : datas['form']['data']['rtotal'],
               'rdiskon' : datas['form']['data']['rdiskon'],
               'rkenapajak' : datas['form']['data']['rtotal'],
               'rpajak' : datas['form']['data']['rpajak'],
               
               'kmk' : datas['form']['data']['kmk'],
               'kurs' : datas['form']['data']['kurs'],
               'matauang' : '1 ' + datas['form']['data']['currency_id'][1],
               'currency' : datas['form']['data']['currency_id'][1],
               
               'tanggal' : time.strftime('%d-%m-%Y', time.strptime(datas['form']['data']['date_invoice'],'%Y-%m-%d')),
               'orang' : datas['form']['data']['approver'][1],                  
     }
     
     filepdf = 'fakturpajakrupiah.pdf'
     if result['currency'] != 'IDR' :
         result['rtotal'] = False
         filepdf = 'fakturpajakvalas.pdf'
     
     
     tmp_file = tempfile.mkstemp(".pdf")[1]
     try:
         fill_pdf(addons.get_module_resource('ad_account_finance', 'report', filepdf), tmp_file, result)
         with open(tmp_file, "r") as ofile:
             self.obj = external_pdf(ofile.read())
     finally:
         os.remove(tmp_file)    
     self.obj.render()
     return (self.obj.pdf, 'pdf')
Beispiel #24
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(base_report_designer_installer,
                  self).default_get(cr, uid, fields, context=context)
     plugin_file = open(
         addons.get_module_resource('base_report_designer', 'plugin',
                                    'openerp_report_designer.zip'), 'rb')
     data['plugin_file'] = base64.encodestring(plugin_file.read())
     return data
Beispiel #25
0
def init_postgis(cursor):
    ## Create language may fail and it can be normal
    cursor.execute("SELECT tablename from pg_tables where tablename='spatial_ref_sys';")
    check = cursor.fetchone()
    if check:
        return {}
    db, pool = pooler.get_db_and_pool(cursor.dbname)
    mycursor = db.cursor()
    p = addons.get_module_resource('base_geoengine', 'postgis_sql','postgis.sql')
    postgis_sql = open(p).read()
    p = addons.get_module_resource('base_geoengine', 'postgis_sql','spatial_ref_sys.sql')
    spatial_ref_sys_sql = open(p).read()
    try:
        mycursor.execute('CREATE LANGUAGE plpgsql');
        mycursor.commit()
    except Exception, exc:
        mycursor.rollback()
        logger.warning('Can not create LANGUAGE plpgsql')
    def generate_payment_lines (self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        rec_list = ['name','percent','due_date','amount','so_id']
        file_path = join(addons.get_module_resource('sale_bagus_improvememt'),'files')
        record_obj = self.browse(cr, uid, ids[0], context)
        record_ids = record_obj.payment_line
        record_id = []
        so = ''

        for rec_id in record_ids:
            record_id.append(rec_id.id)
        record_line = self.pool.get('sale.pay').read(cr, uid, record_id, context=context)
        if not record_line:
            raise osv.except_osv(_('Warning!'), _('No payment lines defined!'))

        wb = xlrd.open_workbook(join(file_path,'format.xls'), encoding_override="cp1252", formatting_info=True)

        ws = copy(wb)
        row = 1
        column = 0
        style = easyxf(
                    'align: horizontal left , vertical center;font: bold on;font:height 250;border: right double, bottom double,left double,top double;',
                )
        style1 = easyxf(
                    'align: horizontal center , vertical center;font:height 250;',
                )
        style2 = easyxf(
                    'align: horizontal left , vertical center;font:height 250;',
                )
        style3 = easyxf(
                    'align: horizontal right , vertical center;font:height 250;',
                )

        for rec_line in record_line:
            row +=1 
            column = 1
            for list_item in rec_list:
                if list_item == 'so_id':
                    so = rec_line.get('so_id') and rec_line['so_id'][1]
                    ws.get_sheet(0).write(0, 1, rec_line.get('so_id') and rec_line['so_id'][1], style1)
                elif list_item == 'amount':
                    ws.get_sheet(0).write(row, column, str(rec_line[list_item]), style3)
                elif list_item == 'due_date':
                    ws.get_sheet(0).write(row, column, rec_line[list_item], style1)
                elif list_item == 'percent':
                    ws.get_sheet(0).write(row, column, str(rec_line[list_item]) + '%', style1)
                else:
                    ws.get_sheet(0).write(row, column, rec_line[list_item], style2)
                column += 1
        row = row + 10 
        n = so and ("%s.xls" % so) or 'undefined.xls'
        ws.save(join(file_path, n))
        file = StringIO.StringIO()
        out = ws.save(file)
        self.write(cr, uid, ids, {'pac_file': base64.encodestring(file.getvalue())})
        return True
Beispiel #27
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(wh_vat_installer, self).default_get(cr,
                                                      uid,
                                                      fields,
                                                      context=context)
     gaceta = open(
         addons.get_module_resource('l10n_ve_withholding_iva', 'files',
                                    'RegimendeRetencionesdelIVA.odt'), 'rb')
     data['gaceta'] = base64.encodestring(gaceta.read())
     return data
Beispiel #28
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(thunderbird_installer,
                  self).default_get(cr, uid, fields, context)
     data[
         'pdf_file'] = 'http://doc.openerp.com/v6.0/book/2/3_CRM_Contacts/communicate.html#managing-your-crm-from-mozilla-thunderbird'
     file = open(
         addons.get_module_resource('thunderbird', 'plugin',
                                    'openerp_plugin.xpi'), 'rb')
     data['plugin_file'] = base64.encodestring(file.read())
     return data
Beispiel #29
0
    def create(self, cr, uid, ids, datas, context=None):
        pool = pooler.get_pool(cr.dbname)

        color = ''
        if datas['form']['data']['color']:
            color = 'COLOUR CODE : ' + datas['form']['data']['color']

        result = {
            'no':
            datas['form']['data']['no'],
            'urgent':
            datas['form']['data']['urgent'],
            'weight':
            datas['form']['data']['weight'],
            'measurement':
            datas['form']['data']['measurement'],
            'name':
            datas['form']['data']['name'],
            'attention':
            datas['form']['data']['attention'],
            'date':
            time.strftime(
                '     %B %Y',
                time.strptime(datas['form']['data']['date'],
                              '%Y-%m-%d %H:%M:%S')),
            'reference':
            datas['form']['data']['reference'],
            'purchase':
            'Purchase Order No.' + datas['form']['data']['purchase'] +
            ', Tgl. ' + time.strftime(
                '%d/%m/%Y',
                time.strptime(datas['form']['data']['pur_date'], '%Y-%m-%d')),
            'color':
            color,
            'qty':
            datas['form']['data']['qty'],
            'product':
            datas['form']['data']['product'],
            'totalitem':
            'Total :    Item',
            'totalbox':
            'Total :    Box',
        }

        tmp_file = tempfile.mkstemp(".pdf")[1]
        try:
            fill_pdf(
                addons.get_module_resource('ad_delivery_note', 'report',
                                           'paketA4.pdf'), tmp_file, result)
            with open(tmp_file, "r") as ofile:
                self.obj = external_pdf(ofile.read())
        finally:
            os.remove(tmp_file)
        self.obj.render()
        return (self.obj.pdf, 'pdf')
Beispiel #30
0
 def default_get(self, cr, uid, fields_list=None, context=None):
     defaults = super(split_invoice_config,
                      self).default_get(cr,
                                        uid,
                                        fields_list=fields_list,
                                        context=context)
     logo = open(
         addons.get_module_resource('l10n_ve_split_invoice', 'images',
                                    'puente-maracaibo.jpg'), 'rb')
     defaults['config_logo'] = base64.encodestring(logo.read())
     return defaults
Beispiel #31
0
 def read_image(self, path):
     path_info = path.split(',')
     icon_path = addons.get_module_resource(path_info[0], path_info[1])
     icon_image = False
     if icon_path:
         try:
             icon_file = tools.file_open(icon_path, 'rb')
             icon_image = base64.encodestring(icon_file.read())
         finally:
             icon_file.close()
     return icon_image
 def read_image(self, path):
     path_info = path.split(',')
     icon_path = addons.get_module_resource(path_info[0],path_info[1])
     icon_image = False
     if icon_path:
         try:
             icon_file = tools.file_open(icon_path,'rb')
             icon_image = base64.encodestring(icon_file.read())
         finally:
             icon_file.close()
     return icon_image
    def create(self, cr, uid, ids, datas, context=None):

        pool = pooler.get_pool(cr.dbname)
        taxobj = pool.get('account.tax.code')

        if context is None:
            context = {}

        #code_ids = taxobj.search(cr, uid, [('parent_id','child_of',[datas['form']['tax_code_id']])])
        code_ids = taxobj.search(cr, uid, [("code","like","PP30_")])

        result = {}
        for t in taxobj.browse(cr, uid, code_ids, {'period_id': datas['form']['period_id']}):
            if str(t.code):
                result['case_'+str(t.code)] = '%.2f' % (t.sum_period or 0.0, )
        user = pool.get('res.users').browse(cr, uid, uid, context)

        partner = user.company_id.partner_id
        result['p1_npwp_1'] = user.company_id.npwp[:2]
        result['p1_npwp_2'] = user.company_id.npwp[3:6]
        result['p1_npwp_3'] = user.company_id.npwp[7:10]
        result['p1_npwp_4'] = user.company_id.npwp[11:12]
        result['p1_npwp_5'] = user.company_id.npwp[13:16]
        result['p1_npwp_6'] = user.company_id.npwp[17:20]
        result['p1_nama_pkp'] = user.company_id.name.upper()
        result['info_name'] = user.company_id.name
        result['info_vatnum'] = partner.vat
        result['p1_jenis_usaha'] = "PERKEBUNAN"

        if partner.address:
            phone = partner.address[0].phone
            if phone:
                
                result['p1_telp_1'] = phone
                result['p1_telp_2'] = phone
                
            result['info_address'] = partner.address[0].street
            result['info_address2'] = (partner.address[0].zip or '') + ' ' + (partner.address[0].city or '')
        try:
            tmp_file = tempfile.mkstemp(".pdf")[1]
            try:
                tools.pdf_utils.fill_pdf(addons.get_module_resource('ad_hr_indonesia','report','pdf','spt_pph2126-1721.pdf'), tmp_file, result)
                with open(tmp_file, "r") as ofile:
                    self.obj = external_pdf(ofile.read())
            finally:
                try:
                    os.remove(tmp_file)
                except:
                    pass # nothing to do
            self.obj.render()
            return (self.obj.pdf, 'pdf')
        except Exception:
            raise osv.except_osv(_('pdf not created !'), _('Please check if package pdftk is installed!'))
Beispiel #34
0
def init_postgis(cursor):
    ## Create language may fail and it can be normal
    cursor.execute(
        "SELECT tablename from pg_tables where tablename='spatial_ref_sys';")
    check = cursor.fetchone()
    if check:
        return {}
    db, pool = pooler.get_db_and_pool(cursor.dbname)
    mycursor = db.cursor()
    p = addons.get_module_resource('base_geoengine', 'postgis_sql',
                                   'postgis.sql')
    postgis_sql = open(p).read()
    p = addons.get_module_resource('base_geoengine', 'postgis_sql',
                                   'spatial_ref_sys.sql')
    spatial_ref_sys_sql = open(p).read()
    try:
        mycursor.execute('CREATE LANGUAGE plpgsql')
        mycursor.commit()
    except Exception, exc:
        mycursor.rollback()
        logger.warning('Can not create LANGUAGE plpgsql')
Beispiel #35
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(outlook_installer, self).default_get(cr,
                                                       uid,
                                                       fields,
                                                       context=context)
     data[
         'doc_file'] = 'http://doc.openerp.com/v6.0/book/2/3_CRM_Contacts/communicate.html#managing-your-crm-from-microsoft-outlook'
     file = open(
         addons.get_module_resource('outlook', 'plugin',
                                    'openerp-outlook-addin.exe'), 'r')
     data['plugin_file'] = base64.encodestring(file.read())
     return data
def up(cursor, installed_version):
    if not installed_version:
        return
    data_path = get_module_resource(
        'som_account_invoice_pending', 'som_account_invoice_pending_data.xml'
    )
    with open(data_path, 'r') as f:
        data_xml = f.read()
    dm = DataMigration(data_xml, cursor, 'som_account_invoice_pending', {
        'poweremail.templates': ['name']
    })
    dm.migrate()
 def default_get(self, cr, uid, fields, context=None):
     data = super(outlook_installer, self).default_get(cr,
                                                       uid,
                                                       fields,
                                                       context=context)
     data[
         'doc_file'] = 'http://doc.openerp.com/book/2/2_6_Comms/2_6_Comms_outlook.html'
     file = open(
         addons.get_module_resource('outlook', 'plugin',
                                    'openerp-outlook-addin.exe'), 'r')
     data['plugin_file'] = base64.encodestring(file.read())
     return data
Beispiel #38
0
    def update_translations(self, cr, uid, ids, filter_lang=None, context=None):
        logger = logging.getLogger('i18n')
        if not filter_lang:
            pool = pooler.get_pool(cr.dbname)
            lang_obj = pool.get('res.lang')
            lang_ids = lang_obj.search(cr, uid, [('translatable', '=', True)])
            filter_lang = [lang.code for lang in lang_obj.browse(cr, uid, lang_ids)]
        elif not isinstance(filter_lang, (list, tuple)):
            filter_lang = [filter_lang]

        for mod in self.browse(cr, uid, ids):
            if mod.state != 'installed':
                continue
            modpath = addons.get_module_path(mod.name)
            if not modpath:
                # unable to find the module. we skip
                continue
            for lang in filter_lang:
                iso_lang = tools.get_iso_codes(lang)
                # Implementation notice: We need to load both the base language,
                # like "en" and then the dialects (like "en_GB"). 
                # With overwrite=False, en will be complemented with 'en_GB' terms.
                # with overwrite, we need to reverse the loading order
                to_load = []
                
                f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
                if f:
                    to_load.append((iso_lang, f))
                if '_' in iso_lang:
                    iso_lang = iso_lang.split('_')[0]
                    f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po')
                    if f:
                        to_load.append((iso_lang, f))
                if context and context.get('overwrite', False):
                    to_load.reverse()
                for (iso_lang, f) in to_load:
                    logger.info('module %s: loading translation file for language %s', mod.name, iso_lang)
                    tools.trans_load(cr, f, lang, verbose=False, context=context)
                if to_load == [] and lang != 'en_US':
                    logger.warning('module %s: no translation for language %s', mod.name, lang)
Beispiel #39
0
    def create(self, cr, uid, ids, datas, context=None):
        pool = pooler.get_pool(cr.dbname)

        kwitansi = '-'
        if datas['form']['data']['kwitansi']:
            kwitansi = datas['form']['data']['kwitansi']

        result = {
            'name':
            kwitansi,
            'customer':
            datas['form']['data']['partner_id'][1],
            'alamatcustomer':
            datas['form']['data']['alamatcustomer'],
            'no':
            datas['form']['data']['no'],
            'qty':
            datas['form']['data']['qty'],
            'product':
            datas['form']['data']['product'].encode('latin9'),
            'price':
            datas['form']['data']['price'],
            'subtotal':
            datas['form']['data']['subtotal'],
            'rsubtotal':
            datas['form']['data']['rsubtotal'],
            'rpajak':
            datas['form']['data']['rpajak'],
            'rtotal':
            datas['form']['data']['rtotal'],
            'terbilang':
            datas['form']['data']['terbilang'],
            'tanggal':
            time.strftime(
                '%d.%m.%Y',
                time.strptime(datas['form']['data']['date_invoice'],
                              '%Y-%m-%d')),
            'orang':
            datas['form']['data']['approver'][1],
        }

        tmp_file = tempfile.mkstemp(".pdf")[1]
        try:
            fill_pdf(
                addons.get_module_resource('ad_account_finance', 'report',
                                           'invoice.pdf'), tmp_file, result)
            with open(tmp_file, "r") as ofile:
                self.obj = external_pdf(ofile.read())
        finally:
            os.remove(tmp_file)
        self.obj.render()
        return (self.obj.pdf, 'pdf')
 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 = addons.get_module_resource('survey', 'report') + file_name + '.pdf'
         service = netsvc.LocalService(report_name);
         (result, format) = service.create(cr, uid, res_ids, {}, {})
         fp = open(ret_file_name, 'wb+');
         fp.write(result);
         fp.close();
     except Exception,e:
         print 'Exception in create report:',e
         return (False, str(e))
Beispiel #41
0
 def default_get(self, cr, uid, fields_list=None, context=None):
     """ Default value config_logo field
     """
     defaults = super(wh_islr_config,
                      self).default_get(cr,
                                        uid,
                                        fields_list=fields_list,
                                        context=context)
     logo = open(
         addons.get_module_resource('l10n_ve_withholding_islr', 'images',
                                    'playa-medina.jpg'), 'rb')
     defaults['config_logo'] = base64.encodestring(logo.read())
     return defaults
def parse_cng_xls_file(xls_file,db,pricelist_name, wizard_obj):
    user = wizard_obj.postgres_config_id.db_user
    host = wizard_obj.postgres_config_id.host_name
    password = wizard_obj.postgres_config_id.db_user_pass
    rb = xlrd.open_workbook(xls_file,formatting_info=False)
    final_lst = []
    worksheet = rb.sheet_by_index(0)
    col_values = worksheet.row_values(0)
    data_lst = []
    file_gas = addons.get_module_resource('import_xls/csv_data', 'master_sheet_cng_gas.csv')
    sheet_1_data_gas = first_sheet.sheet_1_cng_gas_price(file_gas,col_values,worksheet,pricelist_name)
    pricelist.import_pricelist_cng_gas(db,user,host,password,sheet_1_data_gas)
    final_lst += sheet_1_data_gas
    return final_lst
    def file_open(name, mode="r", subdir='addons', pathinfo=False):
        """Modified version for calls after direct join of module names.

        For example, this can be seen in ``addons.load_module_graph()``
           fp = tools.file_open(opj(m, filename))

        Found it simpler (and necessary, given there were references to
        addons_path and root_path) to correct from here.

        The original one does try and replace subpaths by zip files if
        some are found. We simply call it back to avoid duplicating this
        (in the same way it's already doing after subdir related resolutions).
        """

        if name.replace(os.path.sep, '/').startswith('addons/'):
            subdir = 'addons'
            name = name[7:]

        # First try to locate in addons_path
        if subdir:  # remember that the default value is 'addons'
            subdir2 = subdir
            if subdir2.replace(os.path.sep, '/').startswith('addons/'):
                subdir2 = subdir2[7:]

            subdir2 = (subdir2 != 'addons' or None) and subdir2
            if os.path.isabs(name):
                fn = name
            elif subdir2 is None:
                # first segment is necessary the module name
                fn = addons.get_module_resource(*name.split(os.path.sep, 1))

            try:
                fn = os.path.normpath(fn)
                # subdir=None will skip this override's equivalent in
                # original code (leading to zip handling etc)
                fo = file_open(fn, mode=mode, subdir=None, pathinfo=pathinfo)
                if pathinfo:
                    return fo, fn
                return fo
            except IOError:
                pass

        rtp = os.path.normcase(os.path.abspath(tools.config['root_path']))
        if subdir:
            name = os.path.join(rtp, subdir, name)
        else:
            name = os.path.join(rtp, name)

        name = os.path.normpath(name)
        return orig_file_open(name, subdir=None, pathinfo=pathinfo)
Beispiel #44
0
    def file_open(name, mode="r", subdir='addons', pathinfo=False):
        """Modified version for calls after direct join of module names.

        For example, this can be seen in ``addons.load_module_graph()``
           fp = tools.file_open(opj(m, filename))

        Found it simpler (and necessary, given there were references to
        addons_path and root_path) to correct from here.

        The original one does try and replace subpaths by zip files if
        some are found. We simply call it back to avoid duplicating this
        (in the same way it's already doing after subdir related resolutions).
        """

        if name.replace(os.path.sep, '/').startswith('addons/'):
            subdir = 'addons'
            name = name[7:]

        # First try to locate in addons_path
        if subdir:  # remember that the default value is 'addons'
            subdir2 = subdir
            if subdir2.replace(os.path.sep, '/').startswith('addons/'):
                subdir2 = subdir2[7:]

            subdir2 = (subdir2 != 'addons' or None) and subdir2
            if os.path.isabs(name):
                fn = name
            elif subdir2 is None:
                # first segment is necessary the module name
                fn = addons.get_module_resource(*name.split(os.path.sep, 1))

            try:
                fn = os.path.normpath(fn)
                # subdir=None will skip this override's equivalent in
                # original code (leading to zip handling etc)
                fo = file_open(fn, mode=mode, subdir=None, pathinfo=pathinfo)
                if pathinfo:
                    return fo, fn
                return fo
            except IOError:
                pass

        rtp = os.path.normcase(os.path.abspath(tools.config['root_path']))
        if subdir:
            name = os.path.join(rtp, subdir, name)
        else:
            name = os.path.join(rtp, name)

        name = os.path.normpath(name)
        return orig_file_open(name, subdir=None, pathinfo=pathinfo)
Beispiel #45
0
 def execute(self, cr, uid, ids, context=None):
     """Override of code in order to be able to link journal with account in XML"""
     res = super(WizardMultiChartsAccounts,
                 self).execute(cr, uid, ids, context)
     path = addons.get_module_resource(
         os.path.join('l10n_ch', 'sterchi_chart',
                      'account_journal_rel.xml'))
     tools.convert_xml_import(cr,
                              'l10n_ch',
                              path,
                              idref=None,
                              mode='init',
                              noupdate=True,
                              report=None)
     return res
    def create_single_pdf(self, cr, uid, ids, data, report_xml, context=None):
        if context is None:
            context = {}
        if report_xml.report_type != 'webkit':
            return super(WebKitParser,self).create_single_pdf(cr, uid, ids, data, report_xml, context=context)

        self.report_xml = report_xml
        self.parser_instance = self.parser(cr, uid, self.name2, context=context)
        self.pool = pooler.get_pool(cr.dbname)

        if not context.get('splitbrowse'):
            objs = self.getObjects(cr, uid, ids, context)
        else:
            objs = []
            self.parser_instance.localcontext['ids'] = ids
            self.parser_instance.localcontext['context'] = context
        self.parser_instance.set_context(objs, data, ids, report_xml.report_type)

        template = False
        if report_xml.report_file:
            path = addons.get_module_resource(report_xml.report_file)
            if path and os.path.exists(path):
                template = file(path).read()

        if self.tmpl:
            f = file_open(self.tmpl)
            template = f.read()
            f.close()

        if not template:
            raise osv.except_osv(_('Error!'), _('Webkit Report template not found !'))

        self.localcontext.update({'lang': context.get('lang')})
        self.parser_instance.localcontext.update({'setLang':self.setLang})
        self.parser_instance.localcontext.update({'formatLang':self.formatLang})


        null, tmpname = tempfile.mkstemp()
        fileout = codecs.open(tmpname, 'wb', 'utf8')
        body_mako_tpl = Template(template, input_encoding='utf-8', default_filters=['unicode'])
        try:
            mako_ctx = Context(fileout, _=self.translate_call, **self.parser_instance.localcontext)
            body_mako_tpl.render_context(mako_ctx)
            fileout.close()
        except Exception, e:
            msg = exceptions.text_error_template().render()
            netsvc.Logger().notifyChannel('Webkit render', netsvc.LOG_ERROR, msg)
            raise osv.except_osv(_('Webkit render'), msg)
Beispiel #47
0
    def create(self, cr, uid, ids, datas, context=None):
        pool = pooler.get_pool(cr.dbname)

        result = {
            'name':
            datas['form']['data']['name'],
            'date':
            time.strftime(
                '%d %B %Y',
                time.strptime(datas['form']['data']['kontrakdate'],
                              '%Y-%m-%d')),
            'tanggal':
            time.strftime(
                '%d %B %Y',
                time.strptime(datas['form']['data']['date'], '%Y-%m-%d')),
            'kirim':
            time.strftime(
                '%d %B %Y',
                time.strptime(datas['form']['data']['delivery_date'],
                              '%Y-%m-%d')),
            'order':
            datas['form']['data']['kontrak'],
            'qty':
            datas['form']['data']['qty'],
            'partner':
            datas['form']['data']['partner_id'][1],
            'product':
            datas['form']['data']['product'].encode('latin9'),
            'creator':
            datas['form']['data']['creator'],
            'checker':
            datas['form']['data']['checker'],
            'approver':
            datas['form']['data']['approver']
        }

        tmp_file = tempfile.mkstemp(".pdf")[1]
        try:
            fill_pdf(
                addons.get_module_resource('ad_perintah_kerja', 'report',
                                           'perintahA4.pdf'), tmp_file, result)
            with open(tmp_file, "r") as ofile:
                self.obj = external_pdf(ofile.read())
        finally:
            os.remove(tmp_file)
        self.obj.render()
        return (self.obj.pdf, 'pdf')
Beispiel #48
0
    def create(self, cr, uid, ids, datas, context=None):

        pool = pooler.get_pool(cr.dbname)
        taxobj = pool.get('account.tax.code')

        if context is None:
            context = {}
        code_ids = taxobj.search(
            cr, uid,
            [('parent_id', 'child_of', [datas['form']['tax_code_id']])])
        result = {}
        for t in taxobj.browse(cr, uid, code_ids,
                               {'period_id': datas['form']['period_id']}):
            if str(t.code):
                result['case_' +
                       str(t.code)] = '%.2f' % (t.sum_period or 0.0, )
        user = pool.get('res.users').browse(cr, uid, uid, context)

        # Not Clean, to be changed
        partner = user.company_id.partner_id
        result['info_name'] = user.company_id.name
        result['info_vatnum'] = partner.vat
        if partner.address:
            result['info_address'] = partner.address[0].street
            result['info_address2'] = (partner.address[0].zip or '') + ' ' + (
                partner.address[0].city or '')
        try:
            tmp_file = tempfile.mkstemp(".pdf")[1]
            try:
                tools.pdf_utils.fill_pdf(
                    addons.get_module_resource('l10n_lu', 'wizard',
                                               '2008_DECL_F_M10.pdf'),
                    tmp_file, result)
                with open(tmp_file, "r") as ofile:
                    self.obj = external_pdf(ofile.read())
            finally:
                try:
                    os.remove(tmp_file)
                except:
                    pass  # nothing to do
            self.obj.render()
            return (self.obj.pdf, 'pdf')
        except Exception:
            raise osv.except_osv(
                _('pdf not created !'),
                _('Please check if package pdftk is installed!'))
def parse_bg_gas_xls_file(xls_file,db,pricelist_name, wizard_obj):
    user = wizard_obj.postgres_config_id.db_user
    host = wizard_obj.postgres_config_id.host_name
    password = wizard_obj.postgres_config_id.db_user_pass
    utility_type = wizard_obj.categ_id and wizard_obj.categ_id.name or False 
    rb = xlrd.open_workbook(xls_file,formatting_info=False)
    final_lst = []
    worksheet = rb.sheet_by_name('Sheet1')
    col_values = worksheet.row_values(1,start_colx=0, end_colx=6)
#     print "________col_values______________",col_values
    data_lst = []
    file_gas = addons.get_module_resource('import_xls/csv_data', 'master_sheet_cng_gas.csv')
    sheet_1_data_gas,product_lst = first_sheet.sheet_1_bg_gas_price(file_gas,col_values,worksheet,pricelist_name)
    product_import = pricelist.import_pricelist_bg_gas_product(db,user,host,password,product_lst,utility_type)
    pricelist.import_pricelist_bg_gas(db,user,host,password,sheet_1_data_gas,utility_type)
    final_lst += sheet_1_data_gas
    return final_lst
Beispiel #50
0
 def default_get(self, cr, uid, fields_list=None, context=None):
     """ get default company if any, and the various other fields
     from the company's fields
     """
     defaults = super(wh_iva_config, self)\
           .default_get(cr, uid, fields_list=fields_list, context=context)
     user = self.pool.get('res.users').browse(cr, uid, [uid], context)
     pa_obj = self.pool.get('res.partner.address')
     #Set Vauxoo logo on config Window.
     logo = open(
         addons.get_module_resource('l10n_ve_withholding_iva', 'images',
                                    'angelfalls.jpg'), 'rb')
     defaults['config_logo'] = base64.encodestring(logo.read())
     if not self._show_company_data(cr, uid, context=context):
         #            defaults['add']=''
         #            defaults['vat']=''
         return defaults
     return defaults
Beispiel #51
0
def get_lib(self, cursor, uid,):
    """Return absolute path of wkhtmlto pdf depending on OS and architecture"""
    res = {}
    curr_sys = platform.system()
    extention = u'i386'
    # As recomended in Python in order to support Mac os X
    if sys.maxsize > 2**32:
        extention = 'amd64'
    sysmapping = {'Linux': (u'linux', u'wkhtmltopdf-'+ extention),
                  'Darwin': (u'osx', u'wkhtmltopdf'),
                  'Windows': (u'windows', u'wkhtmltopdf.exe')}
    args = (u'report_webkit_lib', 'lib') + sysmapping[curr_sys]
    path = addons.get_module_resource(*args)
    print path
    if not os.access(path, os.X_OK):
        raise osv.except_osv(_('SystemError'),
                             _('%s is not executable' % (path)))
    return path
def parse_total_xls_file(xls_file,db,pricelist_name, wizard_obj):
    user = wizard_obj.postgres_config_id.db_user
    host = wizard_obj.postgres_config_id.host_name
    password = wizard_obj.postgres_config_id.db_user_pass
    utility_type = wizard_obj.categ_id and wizard_obj.categ_id.name or False 
    reader = csv.DictReader(open(xls_file, 'r'), delimiter=",")
    final_lst = []
    data_lst = []
    file_gas = addons.get_module_resource('import_xls/csv_data', 'master_sheet_cng_gas.csv')
    if utility_type == 'Gas':
        product_lst,sheet_1_data_gas = first_sheet.sheet_1_total_gas_price(file_gas,reader,pricelist_name,utility_type)
        product_import = pricelist.import_pricelist_total_product(db,user,host,password,product_lst,utility_type)
        pricelist.import_pricelist_total_gas(db,user,host,password,sheet_1_data_gas,utility_type)
    elif utility_type == 'Electricity':
        product_lst,sheet_1_data_gas = first_sheet.sheet_1_total_gas_price(file_gas,reader,pricelist_name,utility_type)
        product_import = pricelist.import_pricelist_total_product(db,user,host,password,product_lst,utility_type)
        pricelist.import_total_pricelist_ele(db,user,host,password,sheet_1_data_gas,utility_type)
    final_lst += sheet_1_data_gas
    return final_lst
 def get_relation_graph(self, cr, uid, module_name, context=None):
     if context is None: context = {}
     object_ids = self._get_module_objects(cr, uid, module_name, context=context)
     if not object_ids:
         return {'module_file': False}
     context.update({'level': 1})
     dots = self.get_graphical_representation(cr, uid, object_ids, context=context)
     # todo: use os.realpath
     file_path = addons.get_module_resource('base_module_doc_rst')
     path_png = file_path + "/module.png"
     for key, val in dots.items():
        path_dotfile = file_path + "/%s.dot" % (key,)
        fp = file(path_dotfile, "w")
        fp.write(val)
        fp.close()
     os.popen('dot -Tpng' +' '+ path_dotfile + ' '+ '-o' +' ' + path_png)
     fp = file(path_png, "r")
     x = fp.read()
     fp.close()
     os.popen('rm ' + path_dotfile + ' ' + path_png)
     return {'module_file': base64.encodestring(x)}
 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 = addons.get_module_resource(
             'survey', 'report') + file_name + '.pdf'
         service = netsvc.LocalService(report_name)
         (result, format) = service.create(cr, uid, res_ids, {}, {})
         fp = open(ret_file_name, 'wb+')
         fp.write(result)
         fp.close()
     except Exception, e:
         print 'Exception in create report:', e
         return (False, str(e))
Beispiel #55
0
    def post_process_xml_data(self, cr, uid, xml, context=None):
        if not context:
            context={}
        # find the position of the 3rd tag
        # (skip the <?xml ...?> and the "root" tag)
        iter = re.finditer('<[^>]*>', xml)
        i = iter.next()
        i = iter.next()
        pos_xml = i.end()

        doc = print_xml.document(cr, uid, {}, {})
        tmpl_path = addons.get_module_resource('base', 'report', 'corporate_defaults.xml')
        doc.parse(tmpl_path, [uid], 'res.users', context)
        corporate_header = doc.xml_get()
        doc.close()

        # find the position of the tag after the <?xml ...?> tag
        iter = re.finditer('<[^>]*>', corporate_header)
        i = iter.next()
        pos_header = i.end()

        return xml[:pos_xml] + corporate_header[pos_header:] + xml[pos_xml:]
Beispiel #56
0
 def create(self, cr, uid, ids, datas, context=None):
     pool = pooler.get_pool(cr.dbname)
     
     result = {
               'name' : datas['form']['data']['name'],
               'date' : time.strftime('%d %B %Y', time.strptime(datas['form']['data']['tanggal'],'%Y-%m-%d')),
               'order': datas['form']['data']['poc'],
               'qty': datas['form']['data']['qty'],
               'partner': datas['form']['data']['partner_id'][1]+'\n'+datas['form']['data']['street']+'\n'+datas['form']['data']['jalan']+'\n'+datas['form']['data']['phone'],
               'product_name': datas['form']['data']['product_name'].encode('utf-8'),
               'product_code': datas['form']['data']['product_code']
     }
     
     tmp_file = tempfile.mkstemp(".pdf")[1]
     try:
         fill_pdf(addons.get_module_resource('ad_order_preparation','report','preparationA4.pdf'), tmp_file, result)
         with open(tmp_file, "r") as ofile:
             self.obj = external_pdf(ofile.read())
     finally:
         os.remove(tmp_file)    
     self.obj.render()
     return (self.obj.pdf, 'pdf')
Beispiel #57
0
    def create(self, cr, uid, ids, datas, context=None):
        pool = pooler.get_pool(cr.dbname)

        result = {
            'name':
            datas['form']['data']['name'],
            'order':
            datas['form']['data']['poc'],
            'prepare':
            datas['form']['data']['prepare_id'][1],
            'qty':
            datas['form']['data']['qty'],
            'partner':
            datas['form']['data']['partner_id'][1] + '\n' +
            datas['form']['data']['street'] + '\n' +
            datas['form']['data']['jalan'] + '\n' +
            datas['form']['data']['phone'],
            'product_name':
            datas['form']['data']['product_name'].encode('latin9'),
            'product_code':
            datas['form']['data']['product_code']
        }

        print '------------------', datas['form']['data']['partner_id'][
            1] + '\n' + datas['form']['data']['street'] + '\n' + datas['form'][
                'data']['jalan'] + '\n' + datas['form']['data']['phone']

        tmp_file = tempfile.mkstemp(".pdf")[1]
        try:
            fill_pdf(
                addons.get_module_resource('ad_delivery_note', 'report',
                                           'deliveryA4.pdf'), tmp_file, result)
            with open(tmp_file, "r") as ofile:
                self.obj = external_pdf(ofile.read())
        finally:
            os.remove(tmp_file)
        self.obj.render()
        return (self.obj.pdf, 'pdf')
Beispiel #58
0
    def post_process_xml_data(self, cr, uid, xml, context=None):

        if not context:
            context={}
        # find the position of the 3rd tag
        # (skip the <?xml ...?> and the "root" tag)
        iter = re.finditer('<[^>]*>', xml)
        i = iter.next()
        i = iter.next()
        pos_xml = i.end()

        doc = print_xml.document(cr, uid, {}, {})
        tmpl_path = addons.get_module_resource('base', 'report', 'corporate_defaults.xml')
        doc.parse(tmpl_path, [uid], 'res.users', context)
        corporate_header = doc.xml_get()
        doc.close()

        # find the position of the tag after the <?xml ...?> tag
        iter = re.finditer('<[^>]*>', corporate_header)
        i = iter.next()
        pos_header = i.end()

        return xml[:pos_xml] + corporate_header[pos_header:] + xml[pos_xml:]