Example #1
0
 def exists(self):
     ids = self._existing()
     existing = self.filtered(lambda rec: rec.id in ids)
     if len(existing) < len(self):
         # mark missing records in cache with a failed value
         exc = MissingError(_("Record does not exist or has been deleted."))
         for record in (self - existing):
             record._cache.set_failed(self._fields, exc)
     return existing
Example #2
0
 def _move_file(self, old_file_path, new_file_path):
     try:
         shutil.move(old_file_path, new_file_path)
     except IOError as exc:
         if exc.errno == errno.ENOENT:
             _logger.error("Failed to move the file: " + str(exc))
             raise MissingError(
                 _("Something went wrong! Seems that the file is missing."))
         else:
             _logger.error("Failed to move the file: " + str(exc))
             raise AccessError(_("The System failed to rename the file."))
Example #3
0
 def exists(self):
     ids = self._existing()
     existing = self.filtered(lambda rec: rec.id in ids)
     if len(existing) < len(self):
         # mark missing records in cache with a failed value
         exc = MissingError(
             _("Record does not exist or has been deleted.") +
             '\n\n({} {}, {} {})'.format(_('Records:'), (
                 self - existing).ids[:6], _('User:'), self._uid))
         for record in (self - existing):
             record._cache.set_failed(self._fields, exc)
     return existing
Example #4
0
 def update_checksum(self):
     for record in self:
         file_path = record._build_path()
         with opened_w_error(file_path, "rb") as (file_handler, exc):
             if exc:
                 _logger.error("Failed to read the file: " + str(exc))
                 raise MissingError(
                     _("Something went wrong! Seems that the file is missing."
                       ))
             else:
                 file = file_handler.read()
                 record.checksum = record._compute_checksum(file)
Example #5
0
 def _document_check_access(self, model_name, document_id, access_token=None):
     document = request.env[model_name].browse([document_id])
     document_sudo = document.with_user(SUPERUSER_ID).exists()
     if not document_sudo:
         raise MissingError(_("This document does not exist."))
     try:
         document.check_access_rights('read')
         document.check_access_rule('read')
     except AccessError:
         if not access_token or not document_sudo.access_token or not consteq(document_sudo.access_token, access_token):
             raise
     return document_sudo
Example #6
0
 def _read_file(self, file_path):
     with opened_w_error(file_path, "rb") as (file_handler, exc):
         if exc:
             _logger.error("Failed to read the file (%s): %s" %
                           (file_path, str(exc)))
             raise MissingError(
                 _("Something went wrong! Seems that the file is missing or is broken."
                   ))
         else:
             file = file_handler.read()
             encode_file = base64.b64encode(file)
             if self._check_file(file, self.checksum):
                 return encode_file
             else:
                 _logger.error(
                     "Failed to read the file: The file has been altered outside of the system."
                 )
                 raise ValidationError(_("The file is corrupted."))
Example #7
0
 def test_missing_error_http(self, **kwargs):
     raise MissingError("This is a missing http test")
Example #8
0
 def test_missing_error_json(self, **kwargs):
     raise MissingError("This is a missing rpc test")
Example #9
0
    def complex_report(self, docids, data, report, ctx):
        """ Returns an aeroo report generated by aeroolib
        """
        self.model = ctx.get('active_model', False)
        # tmpl_type = 'odt'
        self.record_ids = docids
        self.ctx = ctx
        self.company = self.env.user.company_id
        self.report = report

        #=======================================================================
        self.localcontext = {
            'user':     self.env.user,
            'user_lang': ctx.get('lang', False),
            'data':     data,

            'time':     time,
            'asarray':  self._asarray,
            'average':  self._average,
            'currency_to_text': self._currency_to_text,
            'asimage': self._asimage,
            'get_selection_item': self._get_selection_items('item'),
            'get_selection_items': self._get_selection_items(),
            'get_log': self._get_log,
            'asarray': self._asarray,

            '__filter': self.__filter,  # Don't use in the report template!
            'getLang':  self._get_lang,
            'setLang':  self._set_lang,
            'formatLang': self._format_lang,
            '_': self._translate_text,
            'gettext': self._translate_text,
            'test':     self.test,
            'fields':     fields,
            'company':     self.env.user.company_id,
        }
        self.localcontext.update(ctx)
        self._set_lang(self.company.partner_id.lang)
        self._set_objects(self.model, docids)

        file_data = None
        if report.tml_source == 'database':
            if not report.report_data or report.report_data == 'False':
                # TODO log report ID etc.
                raise MissingError(
                    _("Aeroo Reports could'nt find report template"))
            file_data = b64decode(report.report_data)
        elif report.tml_source == 'file':
            if not report.report_file or report.report_file == 'False':
                # TODO log report ID etc.
                raise MissingError(
                    _("No Aeroo Reports template filename provided"))
            file_data = report._read_template()
        else:
            rec_id = ctx.get('active_id', data.get('id')) or data.get('id')
            file_data = self.get_other_template(self.model, rec_id)

        if not file_data:
            # TODO log report ID etc.
            raise MissingError(_("Aeroo Reports could'nt find report template"))

        template_io = BytesIO(file_data)
        if report.styles_mode == 'default':
            serializer = OOSerializer(template_io)
        else:
            style_io = BytesIO(self.get_stylesheet(report))
            serializer = OOSerializer(template_io, oo_styles=style_io)

        basic = Template(source=template_io,
                         serializer=serializer,
                         lookup=StrictLookup
                         )

        # Add metadata
        ser = basic.Serializer
        model_obj = self.env.get('ir.model')
        model_name = model_obj.search([('model', '=', self.model)])[0].name
        ser.add_title(model_name)

        user_name = self.env.user.name
        ser.add_creation_user(user_name)

        module_info = load_information_from_description_file('report_aeroo')
        version = module_info['version']
        ser.add_generator_info('Aeroo Lib/%s Aeroo Reports/%s'
                               % (aeroolib_version, version))
        ser.add_custom_property('Aeroo Reports %s' % version, 'Generator')
        ser.add_custom_property('Flectra %s' % flectra_release.version, 'Software')
        ser.add_custom_property(module_info['website'], 'URL')
        ser.add_creation_date(time.strftime('%Y-%m-%dT%H:%M:%S'))

        file_data = basic.generate(**self.localcontext).render().getvalue()
        #=======================================================================
        code = mime_dict[report.in_format]
        #_logger.info("End process %s (%s), elapsed time: %s" % (self.name, self.model, time.time() - aeroo_print.start_time), logging.INFO) # debug mode

        return file_data, code
Example #10
0
    def _update_records(self, model_name, website):
        """
            This method:

            - Find and update existing records.

                For each model, overwrite the fields that are defined in the template (except few
                cases such as active) but keep inherited models to not lose customizations.

            - Create new records from templates for those that didn't exist.

            - Remove the models that existed before but are not in the template anymore.

                See _theme_cleanup for more information.


            There is a special 'while' loop around the 'for' to be able queue back models at the end
            of the iteration when they have unmet dependencies. Hopefully the dependency will be
            found after all models have been processed, but if it's not the case an error message will be shown.


            :param model_name: string with the technical name of the model to handle
                (the name must be one of the keys present in ``_theme_model_names``)
            :param website: ``website`` model for which the records have to be updated

            :raise MissingError: if there is a missing dependency.
        """
        self.ensure_one()

        remaining = self._get_module_data(model_name)
        last_len = -1
        while (len(remaining) != last_len):
            last_len = len(remaining)
            for rec in remaining:
                rec_data = rec._convert_to_base_model(website)
                if not rec_data:
                    _logger.info('Record queued: %s' % rec.display_name)
                    continue

                find = rec.with_context(active_test=False).mapped('copy_ids').filtered(lambda m: m.website_id == website)

                # special case for attachment
                # if module B override attachment from dependence A, we update it
                if not find and model_name == 'ir.attachment':
                    # In master, a unique constraint over (theme_template_id, website_id)
                    # will be introduced, thus ensuring unicity of 'find'
                    find = rec.copy_ids.search([('key', '=', rec.key), ('website_id', '=', website.id), ("original_id", "=", False)])

                if find:
                    imd = self.env['ir.model.data'].search([('model', '=', find._name), ('res_id', '=', find.id)])
                    if imd and imd.noupdate:
                        _logger.info('Noupdate set for %s (%s)' % (find, imd))
                    else:
                        # at update, ignore active field
                        if 'active' in rec_data:
                            rec_data.pop('active')
                        if model_name == 'ir.ui.view' and (find.arch_updated or find.arch == rec_data['arch']):
                            rec_data.pop('arch')
                        find.update(rec_data)
                        self._post_copy(rec, find)
                else:
                    new_rec = self.env[model_name].create(rec_data)
                    self._post_copy(rec, new_rec)

                remaining -= rec

        if len(remaining):
            error = 'Error - Remaining: %s' % remaining.mapped('display_name')
            _logger.error(error)
            raise MissingError(error)

        self._theme_cleanup(model_name, website)