Beispiel #1
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
Beispiel #2
0
 def _get_desc(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, '')
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name,
                                    'static/description/index.html')
         if path:
             with tools.file_open(path, 'rb') as desc_file:
                 doc = desc_file.read()
                 html = lxml.html.document_fromstring(doc)
                 for element, attribute, link, pos in html.iterlinks():
                     if element.get('src') and not '//' in element.get(
                             'src') and not 'static/' in element.get('src'):
                         element.set(
                             'src', "/%s/static/description/%s" %
                             (module.name, element.get('src')))
                 res[module.id] = html_sanitize(lxml.html.tostring(html))
         else:
             overrides = {
                 'embed_stylesheet': False,
                 'doctitle_xform': False,
                 'output_encoding': 'unicode',
                 'xml_declaration': False,
             }
             output = publish_string(source=module.description or '',
                                     settings_overrides=overrides,
                                     writer=MyWriter())
             res[module.id] = html_sanitize(output)
     return res
Beispiel #3
0
 def _get_desc(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, "")
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name, "static/description/index.html")
         if path:
             with tools.file_open(path, "rb") as desc_file:
                 doc = desc_file.read()
                 html = lxml.html.document_fromstring(doc)
                 for element, attribute, link, pos in html.iterlinks():
                     if (
                         element.get("src")
                         and not "//" in element.get("src")
                         and not "static/" in element.get("src")
                     ):
                         element.set("src", "/%s/static/description/%s" % (module.name, element.get("src")))
                 res[module.id] = html_sanitize(lxml.html.tostring(html))
         else:
             overrides = {
                 "embed_stylesheet": False,
                 "doctitle_xform": False,
                 "output_encoding": "unicode",
                 "xml_declaration": False,
             }
             output = publish_string(
                 source=module.description or "", settings_overrides=overrides, writer=MyWriter()
             )
             res[module.id] = html_sanitize(output)
     return res
Beispiel #4
0
    def setUp(self):
        super(TestScenarioReconcile, self).setUp()
        tools.convert_file(
            self.cr, 'account',
            get_module_resource('account', 'test', 'account_minimal_test.xml'),
            {}, 'init', False, 'test')
        self.rec_history_obj = self.env['mass.reconcile.history']
        self.mass_rec_obj = self.env['account.mass.reconcile']
        self.invoice_obj = self.env['account.invoice']
        self.bk_stmt_obj = self.env['account.bank.statement']
        self.bk_stmt_line_obj = self.env['account.bank.statement.line']
        self.acc_move_line_obj = self.env['account.move.line']
        self.mass_rec_method_obj = (self.env['account.mass.reconcile.method'])
        self.account_fx_income_id = self.ref("account.income_fx_income")
        self.account_fx_expense_id = self.ref("account.income_fx_expense")
        self.acs_model = self.env['account.config.settings']

        acs_ids = self.acs_model.search([('company_id', '=',
                                          self.ref("base.main_company"))])

        values = {
            'group_multi_currency': True,
            'currency_id': self.ref('base.EUR')
        }

        if acs_ids:
            acs_ids.write(values)
        else:
            default_vals = self.acs_model.default_get([])
            default_vals.update(values)
            acs_ids = self.acs_model.create(default_vals)
Beispiel #5
0
 def setUp(self):
     super(TestReconcile, self).setUp()
     tools.convert_file(
         self.cr, 'account',
         get_module_resource('account', 'test', 'account_minimal_test.xml'),
         {}, 'init', False, 'test')
     self.rec_history_obj = self.env['mass.reconcile.history']
     self.mass_rec_obj = self.env['account.mass.reconcile']
     self.mass_rec_method_obj = (self.env['account.mass.reconcile.method'])
     self.mass_rec = self.mass_rec_obj.create({
         'name':
         'AER2',
         'account':
         self.ref('account.a_salary_expense'),
     })
     self.mass_rec_method = self.mass_rec_method_obj.create({
         'name':
         'mass.reconcile.simple.name',
         'sequence':
         '10',
         'task_id':
         self.mass_rec.id,
     })
     self.mass_rec_no_history = self.mass_rec_obj.create({
         'name':
         'AER3',
         'account':
         self.ref('account.a_salary_expense'),
     })
     self.rec_history = self.rec_history_obj.create({
         'mass_reconcile_id':
         self.mass_rec.id,
         'date':
         fields.Datetime.now(),
     })
Beispiel #6
0
 def load_exif(self):  # Should be one using StringIO to conform with file/datas and vals (in create)
     if self.type == 'url':
         module = self.url.split('/')[1]
         path = '/'.join(self.url.split('/')[2:])
         #~ raise Warning(get_module_path(module),get_module_resource(module,path),module,path)
         exif_dict = piexif.load(get_module_resource(module,path))
     else:
         exif_dict = piexif.load(self.datas.decode('base64'))
     for ifd in ['0th','Exif','thumbnail','1th','GPS','Interop']:
         if exif_dict.get(ifd):
             for tag in exif_dict[ifd]:
                 label = self.env['ir.attachment.exif.label'].search([('name','=',piexif.TAGS[ifd][tag]["name"])])
                 if not label:
                     label = self.env['ir.attachment.exif.label'].create({'ifd': ifd,'name': piexif.TAGS[ifd][tag]['name'], 'exif_type': piexif.TAGS[ifd][tag]['type']} )
                 if not label.type == 'drop':
                     exif = self.env['ir.attachment.exif'].search([('attachment_id','=',self.id),('exif_label','=',label.id)])
                     if not exif:
                         try:
                             self.env['ir.attachment.exif'].create({
                                 'attachment_id': self.id,
                                 'exif_label': label.id,
                                 'exif_value': '%s' % (exif_dict[ifd][tag]),
                             })
                         except:
                             pass
 def test_statement_import(self):
     journal_usd = self.env['account.journal'].create({
         'name':
         'USD Bank Journal - (test)',
         'code':
         'TUBK',
         'type':
         'bank',
         'currency_id':
         self.env.ref('base.USD').id,
     })
     statement = self.env['account.bank.statement'].create({
         'journal_id':
         journal_usd.id,
     })
     importer_model = self.env['v11.import.wizard'].with_context(
         active_id=statement.id)
     v11_path = get_module_resource('l10n_ch_payment_slip', 'tests',
                                    'test_v11_files', 'test1.v11')
     with open(v11_path) as v11_file:
         importer = importer_model.create(
             {'v11file': base64.encodestring(v11_file.read())})
     importer.import_v11()
     statement.refresh()
     self.assertTrue(len(statement.line_ids), 1)
     line = statement.line_ids[0]
     self.assertEqual(line.name, '005095000000000000000000013')
     self.assertEqual(line.ref, '/')
     self.assertEqual(line.amount, 5415.0)
    def setUp(self):
        super(TestScenarioReconcile, self).setUp()
        tools.convert_file(self.cr, 'account',
                           get_module_resource('account', 'test',
                                               'account_minimal_test.xml'),
                           {}, 'init', False, 'test')
        self.rec_history_obj = self.env['mass.reconcile.history']
        self.mass_rec_obj = self.env['account.mass.reconcile']
        self.invoice_obj = self.env['account.invoice']
        self.bk_stmt_obj = self.env['account.bank.statement']
        self.bk_stmt_line_obj = self.env['account.bank.statement.line']
        self.acc_move_line_obj = self.env['account.move.line']
        self.mass_rec_method_obj = (
            self.env['account.mass.reconcile.method']
        )
        self.account_fx_income_id = self.ref("account.income_fx_income")
        self.account_fx_expense_id = self.ref("account.income_fx_expense")
        self.acs_model = self.env['account.config.settings']

        acs_ids = self.acs_model.search(
            [('company_id', '=', self.ref("base.main_company"))]
            )

        values = {'group_multi_currency': True,
                  'currency_id': self.ref('base.EUR')}

        if acs_ids:
            acs_ids.write(values)
        else:
            default_vals = self.acs_model.default_get([])
            default_vals.update(values)
            acs_ids = self.acs_model.create(default_vals)
Beispiel #9
0
    def test_import(self):
        journal_obj = self.env['account.journal']
        misc = journal_obj.search([('name', 'ilike', 'miscellaneous')],
                                  limit=1)

        test_file_path = get_module_resource('l10n_ch_import_cresus', 'tests',
                                             'cresus.txt')
        buf = StringIO()
        with open(test_file_path) as f:
            base64.encode(f, buf)
        contents = buf.getvalue()
        buf.close()
        wizard = self.env['account.cresus.import'].create({
            'journal_id': misc.id,
            'file': contents
        })
        wizard._import_file()

        res = wizard.imported_move_ids
        self.assertEqual(len(res), 5)
        res.assert_balanced()
        for l in res[0].line_ids:
            self.assertEqual(l.analytic_account_id, self.reserve)
        self.assertEqual(res[1].date, '2002-01-07')
        self.assertEqual(res[2].date, '2002-01-07')
        self.assertEqual(res[3].line_ids[0].account_id.code, '6642')
        self.assertEqual(res[3].line_ids[0].debit, 15.0)
        self.assertEqual(res[3].line_ids[0].credit, 0.0)
        self.assertEqual(res[3].line_ids[1].account_id.code, '1010')
        self.assertEqual(res[3].line_ids[1].debit, 0.0)
        self.assertEqual(res[3].line_ids[1].credit, 15.0)
        self.assertEqual(res[4].line_ids[1].tax_line_id, self.vat)
Beispiel #10
0
    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 delCopyOfFiles(self, srcfile):
     path = addons.get_module_resource('seedoo_protocollo_zip', 'tests',
                                       'data', srcfile)
     currDir = os.path.dirname(path)
     for fname in glob.glob(currDir + '/*.' + srcfile.split('.')[1]):
         if os.path.basename(fname) != srcfile:
             os.remove(fname)
    def font_absolute_path(self):
        """Will get the ocrb font absolute path

        :return: path to the font
        """
        path = get_module_resource('l10n_ch_payment_slip', 'static', 'src',
                                   'font', 'ocrbb.ttf')
        return path
Beispiel #13
0
 def onchange_default_shipping(self):
     if 'default_parent_id' in self.env.context:
         if self.default_shipping_address:
                 image = modules.get_module_resource('customer_area', 'static/src/img/', 'icon-fav.png')
                 with open(image, "rb") as image_file:
                     encoded_string = base64.b64encode(image_file.read())
                     self.image = encoded_string
         else:
             self.image = False
Beispiel #14
0
    def default_get(self, cr, uid, fields, context=None):
        if context is None:
            context = {}

        data = super(GetPricelistVersionCsv, self).default_get(cr, uid, fields, context=context)
        plugin_file = open(get_module_resource('dmpi_base','data_import/csv', 'pricelist_upload_template.csv'),'rb')
        data['template_file'] = base64.encodestring(plugin_file.read())
        data['pricelist_id'] = context.get('pricelist_id', False)
        return data
Beispiel #15
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]

        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)
Beispiel #16
0
 def getCopyOfFile(self, filename, srcfile):
     path = addons.get_module_resource('seedoo_protocollo',
                                       'tests', 'data', srcfile)
     currDir = os.path.dirname(path)
     new_file = '%s/%s.pdf' % (currDir, filename)
     shutil.copyfile(path, new_file)
     with open(new_file) as test_data:
         with tempfile.TemporaryFile() as out:
             base64.encode(test_data, out)
             out.seek(0)
             return path, out.read()
Beispiel #17
0
 def onchange_default_shipping(self):
     if 'default_parent_id' in self.env.context:
         if self.default_shipping_address:
             image = modules.get_module_resource('customer_area',
                                                 'static/src/img/',
                                                 'icon-fav.png')
             with open(image, "rb") as image_file:
                 encoded_string = base64.b64encode(image_file.read())
                 self.image = encoded_string
         else:
             self.image = False
Beispiel #18
0
 def _get_icon_image(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, '')
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name, 'static', 'description', 'icon.png')
         if path:
             image_file = tools.file_open(path, 'rb')
             try:
                 res[module.id] = image_file.read().encode('base64')
             finally:
                 image_file.close()
     return res
Beispiel #19
0
 def _get_icon_image(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, '')
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name, 'static', 'description', 'icon.png')
         if path:
             image_file = tools.file_open(path, 'rb')
             try:
                 res[module.id] = image_file.read().encode('base64')
             finally:
                 image_file.close()
     return res
    def image_absolute_path(self, file_name):
        """Will get image absolute path

        :param file_name: name of image

        :return: image path
        :rtype: str
        """
        path = get_module_resource('l10n_ch_payment_slip', 'static', 'src',
                                   'img', file_name)
        return path
Beispiel #21
0
 def _get_icon_image(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, "")
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name, "static", "description", "icon.png")
         if path:
             image_file = tools.file_open(path, "rb")
             try:
                 res[module.id] = image_file.read().encode("base64")
             finally:
                 image_file.close()
     return res
Beispiel #22
0
    def update_translations(self, cr, uid, ids, filter_lang=None, context=None):
        if context is None:
            context = {}
        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)
    def test_file_parsing(self):
        invoice = self.env['account.invoice'].create(
            {
                'partner_id': self.env.ref('base.res_partner_12').id,
                'reference_type': 'none',
                'name': 'A customer invoice',
                'account_id': self.env.ref('account.a_recv').id,
                'type': 'out_invoice',
            }
        )

        self.env['account.invoice.line'].create(
            {
                'product_id': False,
                'quantity': 1,
                'price_unit': 5415.0,
                'invoice_id': invoice.id,
                'name': 'product',
            }
        )
        invoice.signal_workflow('invoice_open')
        for line in invoice.move_id.line_id:
            if line.account_id.type == 'receivable':
                # setting it manually because we can't predict the value
                line.transaction_ref = '005095000000000000000000013'

        v11_path = get_module_resource('l10n_ch_payment_slip',
                                       'tests',
                                       'test_v11_files',
                                       'test1.v11')
        with open(v11_path) as v11_file:
            importer = self.env['v11.import.wizard.voucher'].create({
                'v11file': base64.encodestring(v11_file.read()),
                'currency_id': self.env.ref('base.EUR').id,
                'journal_id': self.env.ref('account.bank_journal').id,
                'validate_vouchers': True,
                })
            std_importer = self.env['v11.import.wizard'].create({})
            v11_file.seek(0)
            lines = v11_file.readlines()
            records = std_importer._parse_lines(lines)
            self.assertTrue(len(records), 1)
            record = records[0]
            self.assertEqual(
                record,
                {'date': '2022-10-17',
                 'amount': 5415.0,
                 'cost': 0.0,
                 'reference': '005095000000000000000000013'}
            )
            importer.import_v11()
            self.assertEqual(invoice.state, 'paid')
Beispiel #24
0
 def setUp(self):
     super(BaseCompletion, self).setUp()
     tools.convert_file(
         self.cr, 'account',
         get_module_resource('account', 'test', 'account_minimal_test.xml'),
         {}, 'init', False, 'test')
     self.account_move_obj = self.env["account.move"]
     self.account_move_line_obj = \
         self.env["account.move.line"]
     self.company_a = self.browse_ref('base.main_company')
     self.journal = self.browse_ref("account.bank_journal")
     self.partner = self.browse_ref("base.res_partner_12")
     self.account_id = self.ref("account.a_recv")
Beispiel #25
0
    def test_0_prot_pdf_in(self):
        """
        Testing receive pdf File and protocol it
        with signature as typology_rac
        """

        cr, uid = self.cr, self.uid
        partner_id = self.getIdDemoObj('base', 'main_partner')
        racc_id = self.getIdDemoObj('', 'protocollo_typology_rac')
        com_varie_id = self.getIdDemoObj('seedoo_gedoc',
                                         'protocollo_classification_6')
        send_rec_id = self.modelProtSendRec.create(cr, uid, {
            'name': 'test_partner',
            'type': 'individual',
            'partner_id': partner_id
        })
        prot_id = self.modelProtocollo.create(
            cr, uid, {
                'type': 'in',
                'subject': 'test',
                'typology': racc_id,
                'sender_receivers': [(4, send_rec_id)],
                'classification': com_varie_id,
                'datas_fname': 'test0',
                'datas': self.getCopyOfFile('test0', 'test_doc_src.pdf')[1],
                'mimetype': 'application/pdf'
            })
        self.assertTrue(bool(prot_id))
        prot_obj = self.modelProtocollo.browse(cr, uid, prot_id)
        self.assertEqual(prot_obj.state, 'draft')
        self.assertEqual(prot_obj.fingerprint, False)
        self.wf_service.trg_validate(uid, 'protocollo.protocollo', prot_id,
                                     'register', cr)
        prot_obj.refresh()
        self.assertEqual(prot_obj.state, 'registered')

        nextProtNumber = self.get_next_number(cr, uid, prot_obj)
        nextProtNumber = int(nextProtNumber) - 1
        # prot_name = 'Protocollo_0000001_%d' % prot_obj.year
        prot_name = 'Protocollo_%07d_%d' % (nextProtNumber, prot_obj.year)
        self.assertEqual(prot_obj.doc_id.name, prot_name)
        sha1 = self.sha1OfFile(prot_obj.doc_id.id)
        self.assertEqual(prot_obj.fingerprint, sha1)
        self.assertTrue(prot_obj.xml_signature)
        path = addons.get_module_resource('seedoo_protocollo', 'data',
                                          "segnatura.dtd")
        dtdPath = os.path.dirname(path) + "/segnatura.dtd"
        dtdfile = open(dtdPath, 'r')
        dtd = etree.DTD(dtdfile)
        signature_xml = etree.XML(prot_obj.xml_signature)
        self.assertTrue(dtd.validate(signature_xml))
Beispiel #26
0
 def get_demo_images(self):
     self.ensure_one()
     demo_images = self.demo_images and self.demo_images.split(',') or []
     res = []
     mod_path = get_module_resource(self.name)
     for image_name in demo_images:
         full_name = os.path.join(mod_path, image_name)
         try:
             with tools.file_open(full_name, 'rb') as image_file:
                 res.append(
                     (image_name, image_file.read().encode('base64')))
         except:
             pass
     return res
Beispiel #27
0
    def set_default_autoload(self):
        if self.directory_name:
            self.env['ir.config_parameter'].set_param(
                'knowledge.directory_name', self.directory_name)
            try:
                os.makedirs(self.directory_name)
            except OSError as exc:
                if exc.errno == errno.EEXIST and os.path.isdir(
                        self.directory_name):
                    pass
                else:
                    raise

            incron = subprocess.Popen(['incrontab', '-l'],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            (std, err) = incron.communicate()
            if err and 'is not allowed' in err:
                raise Warning(err)
            elif err and 'no table for' in err:
                pass
            elif not err:
                incron = subprocess.Popen(['incrontab', '-r'],
                                          stdout=subprocess.PIPE,
                                          stderr=subprocess.PIPE)
                (std, err) = incron.communicate()
                #~ raise Warning(get_module_path('attachment_autoload'),get_module_resource('attachment_autoload','bin/load_document.py'))
            echo = subprocess.Popen([
                'echo',
                '%s IN_CREATE %s -D $@/$# -d %s' %
                (self.directory_name,
                 get_module_resource(
                     'attachment_autoload',
                     'bin/load_document.py'), self.env.cr.dbname)
            ],
                                    stdout=subprocess.PIPE)
            incron = subprocess.Popen(['incrontab', '-'],
                                      stdin=echo.stdout,
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            echo.stdout.close()
            (std, err) = incron.communicate()
        else:
            self.env['ir.config_parameter'].set_param(
                'knowledge.directory_name', 'Kalle')
            incron = subprocess.Popen(['incrontab', '-r'],
                                      stdout=subprocess.PIPE,
                                      stderr=subprocess.PIPE)
            (std, err) = incron.communicate()
 def setUp(self):
     super(PermanentLock, self).setUp()
     tools.convert_file(
         self.cr, 'account',
         get_module_resource('account', 'test', 'account_minimal_test.xml'),
         {}, 'init', False, 'test')
     self.account_move_obj = self.env["account.move"]
     self.account_move_line_obj = \
         self.env["account.move.line"]
     self.company_id = self.ref('base.main_company')
     self.partner = self.browse_ref("base.res_partner_12")
     self.account_id = self.ref("account.a_recv")
     self.account_id2 = self.ref("account.a_expense")
     self.journal_id = self.ref("account.bank_journal")
     self.wizard_obj = self.env["permanent.lock.date.wizard"]
 def setUp(self):
     super(TestOnChange, self).setUp()
     tools.convert_file(self.cr, 'account',
                        get_module_resource('account', 'test',
                                            'account_minimal_test.xml'),
                        {}, 'init', False, 'test')
     acc_setting = self.env['account.config.settings']
     self.acc_setting_obj = acc_setting.create({})
     self.company_obj = self.env['res.company']
     # analytic defaults account creation
     self.main_company = self.env.ref('base.main_company')
     self.sec_company = self.company_obj.create(
         {
             'name': 'Second company',
             'reconciliation_commit_every': 80
         }
     )
Beispiel #30
0
 def _get_desc(self, cr, uid, ids, field_name=None, arg=None, context=None):
     res = dict.fromkeys(ids, '')
     for module in self.browse(cr, uid, ids, context=context):
         path = get_module_resource(module.name, 'static/description/index.html')
         if path:
             with tools.file_open(path, 'rb') as desc_file:
                 doc = desc_file.read()
                 html = lxml.html.document_fromstring(doc)
                 for element, attribute, link, pos in html.iterlinks():
                     if element.get('src') and not '//' in element.get('src') and not 'static/' in element.get('src'):
                         element.set('src', "/%s/static/description/%s" % (module.name, element.get('src')))
                 res[module.id] = lxml.html.tostring(html)
         else:
             overrides = dict(embed_stylesheet=False, doctitle_xform=False, output_encoding='unicode')
             output = publish_string(source=module.description, settings_overrides=overrides, writer=MyWriter())
             res[module.id] = output
     return res
 def getCopyOfFile(self, filename, srcfile):
     """
     this method get a copy of file , present in data folder
     of this tests.
     filename: the name of new file
     srcfile: the file which we want have a copy
     """
     path = addons.get_module_resource('seedoo_protocollo_zip', 'tests',
                                       'data', srcfile)
     currDir = os.path.dirname(path)
     new_file = '%s/%s.pdf' % (currDir, filename)
     shutil.copyfile(path, new_file)
     with open(new_file) as test_data:
         with tempfile.TemporaryFile() as out:
             base64.encode(test_data, out)
             out.seek(0)
             return path, out.read()
 def test_file_parsing(self):
     v11_path = get_module_resource('l10n_ch_payment_slip', 'tests',
                                    'test_v11_files', 'test1.v11')
     with open(v11_path) as v11_file:
         importer = self.env['v11.import.wizard'].create(
             {'v11file': base64.encodestring(v11_file.read())})
         v11_file.seek(0)
         lines = v11_file.readlines()
         records = importer._parse_lines(lines)
         self.assertTrue(len(records), 1)
         record = records[0]
         self.assertEqual(
             record, {
                 'date': '2022-10-17',
                 'amount': 5415.0,
                 'cost': 0.0,
                 'reference': '005095000000000000000000013'
             })
 def setUp(self):
     super(PermanentLock, self).setUp()
     tools.convert_file(
         self.cr,
         "account",
         get_module_resource("account", "test", "account_minimal_test.xml"),
         {},
         "init",
         False,
         "test",
     )
     self.account_move_obj = self.env["account.move"]
     self.account_move_line_obj = self.env["account.move.line"]
     self.company_id = self.ref("base.main_company")
     self.partner = self.browse_ref("base.res_partner_12")
     self.account_id = self.ref("account.a_recv")
     self.account_id2 = self.ref("account.a_expense")
     self.journal_id = self.ref("account.bank_journal")
     self.wizard_obj = self.env["permanent.lock.date.wizard"]
 def setUp(self):
     super(TestReconcileHistory, self).setUp()
     tools.convert_file(
         self.cr, 'account',
         get_module_resource('account', 'test', 'account_minimal_test.xml'),
         {}, 'init', False, 'test')
     self.rec_history_obj = self.env['mass.reconcile.history']
     self.mass_rec_obj = self.env['account.mass.reconcile']
     self.mass_rec = self.mass_rec_obj.create({
         'name':
         'AER1',
         'account':
         self.ref('account.a_expense'),
     })
     self.rec_history = self.rec_history_obj.create({
         'mass_reconcile_id':
         self.mass_rec.id,
         'date':
         fields.Datetime.now(),
     })
Beispiel #35
0
    def post_process_xml_data(self, cr, uid, xml, context=None):
        # 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 = 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 #36
0
    def setUp(self):
        super(BankAccountCompletion, self).setUp()
        tools.convert_file(
            self.cr, 'account',
            get_module_resource('account', 'test', 'account_minimal_test.xml'),
            {}, 'init', False, 'test')
        self.account_move_obj = self.env["account.move"]
        self.account_move_line_obj = \
            self.env["account.move.line"].with_context(
                check_move_validity=False
            )
        self.company_a = self.browse_ref('base.main_company')
        self.completion_rule_id = \
            self.ref('account_move_bankaccount_import.'
                     'bank_statement_completion_rule_10')
        self.journal = self.browse_ref("account.bank_journal")
        self.partner = self.browse_ref('base.main_partner')
        self.account_id = self.ref("account.a_recv")

        # Create the profile
        self.journal.write({
            'used_for_completion': True,
            'rule_ids': [(6, 0, [self.completion_rule_id])]
        })
        # Create a bank statement
        self.move = self.account_move_obj.create({
            "date": fields.Date.today(),
            "journal_id": self.journal.id
        })

        # Add a bank account number to the partner
        self.res_partner_bank_obj = self.env['res.partner.bank']
        vals = {
            "state": "bank",
            "company_id": self.company_a.id,
            "partner_id": self.partner.id,
            "acc_number": ACC_NUMBER,
            "footer": True,
            "bank_name": "Reserve",
        }
        self.partner_bank = self.res_partner_bank_obj.create(vals)
    def setUp(self):
        super(TestReconcileHistory, self).setUp()
        tools.convert_file(self.cr, 'account',
                           get_module_resource('account', 'test',
                                               'account_minimal_test.xml'),
                           {}, 'init', False, 'test')
        self.rec_history_obj = self.env['mass.reconcile.history']
        self.mass_rec_obj = self.env['account.mass.reconcile']
        self.mass_rec = self.mass_rec_obj.create(
            {
                'name': 'AER1',
                'account': self.ref('account.a_expense'),

            }
            )
        self.rec_history = self.rec_history_obj.create(
            {
                'mass_reconcile_id': self.mass_rec.id,
                'date': fields.Datetime.now(),
            }
            )
Beispiel #38
0
    def post_process_xml_data(self, cr, uid, xml, context=None):
        # 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 = 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 #39
0
 def setUp(self):
     super(TestCodaImport, self).setUp()
     self.company_a = self.browse_ref('base.main_company')
     tools.convert_file(
         self.cr, 'account',
         get_module_resource('account', 'test', 'account_minimal_test.xml'),
         {}, 'init', False, 'test')
     self.account_move_obj = self.env["account.move"]
     self.account_move_line_obj = self.env["account.move.line"]
     self.account_id = self.ref("account.a_recv")
     self.journal = self.browse_ref("account.bank_journal")
     self.import_wizard_obj = self.env['credit.statement.import']
     self.partner = self.browse_ref("base.res_partner_12")
     self.journal.write({
         'used_for_import': True,
         "import_type": "generic_csvxls_so",
         'partner_id': self.partner.id,
         'commission_account_id': self.account_id,
         'receivable_account_id': self.account_id,
         'create_counterpart': True,
     })
Beispiel #40
0
 def test_file_parsing(self):
     v11_path = get_module_resource('l10n_ch_payment_slip',
                                    'tests',
                                    'test_v11_files',
                                    'test1.v11')
     with open(v11_path) as v11_file:
         importer = self.env['v11.import.wizard'].create(
             {'v11file': base64.encodestring(v11_file.read())}
         )
         v11_file.seek(0)
         lines = v11_file.readlines()
         records = importer._parse_lines(lines)
         self.assertTrue(len(records), 1)
         record = records[0]
         self.assertEqual(
             record,
             {'date': '2022-10-17',
              'amount': 5415.0,
              'cost': 0.0,
              'reference': '005095000000000000000000013'}
         )
    def button_generate(self):
        self.date_generated = fields.Datetime.now(self)
        xml = self.env.ref('l10n_nl_xaf_auditfile_export.auditfile_template')\
            .render(values={
                'self': self,
            })
        # the following is dealing with the fact that qweb templates don't like
        # namespaces, but we need the correct namespaces for validation
        # we inject them at parse time in order not to traverse the document
        # multiple times
        default_namespace = 'http://www.auditfiles.nl/XAF/3.2'
        iterparse = etree.iterparse(StringIO(xml),
                                    remove_blank_text=True,
                                    remove_comments=True)
        for action, element in iterparse:
            element.tag = '{%s}%s' % (default_namespace, element.tag)
        del xml
        xmldoc = etree.Element(iterparse.root.tag,
                               nsmap={
                                   None:
                                   default_namespace,
                                   'xsi':
                                   'http://www.w3.org/2001/XMLSchema-instance',
                               })
        for element in iterparse.root:
            xmldoc.append(element)
        del iterparse

        xsd = etree.XMLSchema(
            etree.parse(
                file(
                    modules.get_module_resource(
                        'l10n_nl_xaf_auditfile_export', 'data',
                        'XmlAuditfileFinancieel3.2.xsd'))))
        if not xsd.validate(xmldoc):
            self.message_post('\n'.join(map(str, xsd.error_log)))
            return

        self.auditfile = base64.b64encode(
            etree.tostring(xmldoc, xml_declaration=True, encoding='utf8'))
    def button_generate(self):
        self.date_generated = fields.Datetime.now(self)
        xml = self.env.ref('l10n_nl_xaf_auditfile_export.auditfile_template')\
            .render(values={
                'self': self,
            })
        # the following is dealing with the fact that qweb templates don't like
        # namespaces, but we need the correct namespaces for validation
        # we inject them at parse time in order not to traverse the document
        # multiple times
        default_namespace = 'http://www.auditfiles.nl/XAF/3.2'
        iterparse = etree.iterparse(
            StringIO(xml),
            remove_blank_text=True, remove_comments=True)
        for action, element in iterparse:
            element.tag = '{%s}%s' % (default_namespace, element.tag)
        del xml
        xmldoc = etree.Element(
            iterparse.root.tag,
            nsmap={
                None: default_namespace,
                'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
            })
        for element in iterparse.root:
            xmldoc.append(element)
        del iterparse

        xsd = etree.XMLSchema(
            etree.parse(
                file(
                    modules.get_module_resource(
                        'l10n_nl_xaf_auditfile_export', 'data',
                        'XmlAuditfileFinancieel3.2.xsd'))))
        if not xsd.validate(xmldoc):
            self.message_post('\n'.join(map(str, xsd.error_log)))
            return

        self.auditfile = base64.b64encode(etree.tostring(
            xmldoc, xml_declaration=True, encoding='utf8'))
    def setUp(self):
        super(TestReconcile, self).setUp()
        tools.convert_file(self.cr, 'account',
                           get_module_resource('account', 'test',
                                               'account_minimal_test.xml'),
                           {}, 'init', False, 'test')
        self.rec_history_obj = self.env['mass.reconcile.history']
        self.mass_rec_obj = self.env['account.mass.reconcile']
        self.mass_rec_method_obj = (
            self.env['account.mass.reconcile.method']
        )
        self.mass_rec = self.mass_rec_obj.create(
            {
                'name': 'AER2',
                'account': self.ref('account.a_salary_expense'),
            }
            )
        self.mass_rec_method = self.mass_rec_method_obj.create(
            {
                'name': 'mass.reconcile.simple.name',
                'sequence': '10',
                'task_id': self.mass_rec.id,
            }
            )
        self.mass_rec_no_history = self.mass_rec_obj.create(
            {
                'name': 'AER3',
                'account': self.ref('account.a_salary_expense'),

            }
            )
        self.rec_history = self.rec_history_obj.create(
            {
                'mass_reconcile_id': self.mass_rec.id,
                'date': fields.Datetime.now(),
            }
            )
Beispiel #44
0
 def test_statement_import(self):
     statement = self.env['account.bank.statement'].create(
         {
             'journal_id': self.env.ref('account.bank_journal_usd').id,
         }
     )
     importer_model = self.env['v11.import.wizard'].with_context(
         active_id=statement.id
     )
     v11_path = get_module_resource('l10n_ch_payment_slip',
                                    'tests',
                                    'test_v11_files',
                                    'test1.v11')
     with open(v11_path) as v11_file:
         importer = importer_model.create(
             {'v11file': base64.encodestring(v11_file.read())}
         )
     importer.import_v11()
     statement.refresh()
     self.assertTrue(len(statement.line_ids), 1)
     line = statement.line_ids[0]
     self.assertEqual(line.name, '005095000000000000000000013')
     self.assertEqual(line.ref, '/')
     self.assertEqual(line.amount, 5415.0)
Beispiel #45
0
    def run_test(self, cr, uid, module_path):
        registry = RegistryManager.get(cr.dbname)
        module_name = module_path.split('/')[-1]
        test_file = modules.get_module_resource(
            module_name) + '/unit_test/test.py'
        if not os.path.isfile(test_file):
            self.result += _("Module does not have 'unit_test/test.py' file")
            return None
        module_obj = registry['ir.module.module']
        module_ids = module_obj.search(cr, uid, [('name', '=', module_name)])
        module = module_obj.browse(cr, uid, module_ids)
        if not len(module):
            self.result += _("Error! Module is not properly loaded/installed")
            return None
        module = module[0]
        test = module.name + '.' + 'unit_test.test'
        test_module = __import__(test)
        test_file = getattr(test_module, 'unit_test')
        test_obj = getattr(test_file, 'test')

        test_result = test_obj.runTest(cr, uid)
        self.result = self.get_result(test_result)
        self.result_details += self.get_result_details(test_result)
        return None
Beispiel #46
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(GetSaleCsv, self).default_get(cr, uid, fields, context=context)
     plugin_file = open(get_module_resource('dmpi_base','data_import/csv', 'sales_upload_template.csv'),'rb')
     data['template_file'] = base64.encodestring(plugin_file.read())
     return data
Beispiel #47
0
 def default_get(self, cr, uid, fields, context=None):
     data = super(GetPartnerCsv, self).default_get(cr, uid, fields, context=context)
     plugin_file = open(get_module_resource("dmpi_base", "data_import/csv", "partner_upload_template.csv"), "rb")
     data["template_file"] = base64.encodestring(plugin_file.read())
     return data
Beispiel #48
0
 def _get_default_faq(self):
     fname = modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html')
     with open(fname, 'r') as f:
         return f.read()
     return False
Beispiel #49
0
 def _get_default_image(self):
     image_path = modules.get_module_resource('mail', 'static/src/img', 'groupdefault.png')
     return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
Beispiel #50
0
 def _get_default_faq(self):
     fname = modules.get_module_resource("website_forum", "data", "forum_default_faq.html")
     with open(fname, "r") as f:
         return f.read()
     return False
Beispiel #51
0
 def _get_default_faq(self):
     fname = modules.get_module_resource('website_forum', 'data', 'forum_default_faq.html')
     with open(fname, 'r') as f:
         return f.read()
     return False
Beispiel #52
0
 def _get_default_image(self):
     image_path = modules.get_module_resource('mail', 'static/src/img',
                                              'groupdefault.png')
     return tools.image_resize_image_big(
         open(image_path, 'rb').read().encode('base64'))
Beispiel #53
0
    def run_test(self, cr, uid, module_path):
        config_file_path = modules.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
Beispiel #54
0
 def _get_default_image(self):
     image_path = modules.get_module_resource("mail", "static/src/img", "groupdefault.png")
     return tools.image_resize_image_big(open(image_path, "rb").read().encode("base64"))