Ejemplo n.º 1
0
 def _prepare_event_register_values(self, event, **post):
     """Return the require values to render the template."""
     urls = lazy(event._get_event_resource_urls)
     return {
         'event': event,
         'main_object': event,
         'range': range,
         'google_url': lazy(lambda: urls.get('google_url')),
         'iCal_url': lazy(lambda: urls.get('iCal_url')),
     }
Ejemplo n.º 2
0
    def test_80_lazy_set_operations(self):
        """ Check set operations on recordsets. """
        pa = lazy(lambda: self.env['res.partner'].search([('name', 'ilike', 'a'), ('id', 'in', self.partners.ids)]))
        pb = lazy(lambda: self.env['res.partner'].search([('name', 'ilike', 'b'), ('id', 'in', self.partners.ids)]))

        self.assertTrue(pa)
        self.assertTrue(pb)
        self.assertTrue(set(pa) & set(pb))

        concat = pa + pb
        self.assertEqual(list(concat), list(pa) + list(pb))
        self.assertEqual(len(concat), len(pa) + len(pb))

        difference = pa - pb
        self.assertEqual(len(difference), len(set(difference)))
        self.assertEqual(set(difference), set(pa) - set(pb))
        self.assertLessEqual(difference, pa)

        intersection = pa & pb
        self.assertEqual(len(intersection), len(set(intersection)))
        self.assertEqual(set(intersection), set(pa) & set(pb))
        self.assertLessEqual(intersection, pa)
        self.assertLessEqual(intersection, pb)

        union = pa | pb
        self.assertEqual(len(union), len(set(union)))
        self.assertEqual(set(union), set(pa) | set(pb))
        self.assertGreaterEqual(union, pa)
        self.assertGreaterEqual(union, pb)

        # one cannot mix different models with set operations
        ps = pa
        ms = lazy(lambda: self.env['ir.ui.menu'].search([]))
        self.assertNotEqual(ps._name, ms._name)
        self.assertNotEqual(ps, ms)

        with self.assertRaisesRegex(TypeError, r"unsupported operand types in: res\.partner.* \+ 'string'"):
            ps + 'string'
        with self.assertRaisesRegex(TypeError, r"inconsistent models in: res\.partner.* \+ ir\.ui\.menu.*"):
            ps + ms
        with self.assertRaisesRegex(TypeError, r"inconsistent models in: res\.partner.* - ir\.ui\.menu.*"):
            ps - ms
        with self.assertRaisesRegex(TypeError, r"inconsistent models in: res\.partner.* & ir\.ui\.menu.*"):
            ps & ms
        with self.assertRaisesRegex(TypeError, r"inconsistent models in: res\.partner.* \| ir\.ui\.menu.*"):
            ps | ms
        with self.assertRaises(TypeError):
            ps < ms
        with self.assertRaises(TypeError):
            ps <= ms
        with self.assertRaises(TypeError):
            ps > ms
        with self.assertRaises(TypeError):
            ps >= ms
Ejemplo n.º 3
0
    def blog(self, blog=None, tag=None, page=1, search=None, **opt):
        Blog = request.env['blog.blog']
        blogs = tools.lazy(lambda: Blog.search(request.website.website_domain(), order="create_date asc, id asc"))

        if not blog and len(blogs) == 1:
            return request.redirect('/blog/%s' % slug(blogs[0]), code=302)

        date_begin, date_end, state = opt.get('date_begin'), opt.get('date_end'), opt.get('state')

        if tag and request.httprequest.method == 'GET':
            # redirect get tag-1,tag-2 -> get tag-1
            tags = tag.split(',')
            if len(tags) > 1:
                url = QueryURL('' if blog else '/blog', ['blog', 'tag'], blog=blog, tag=tags[0], date_begin=date_begin, date_end=date_end, search=search)()
                return request.redirect(url, code=302)

        values = self._prepare_blog_values(blogs=blogs, blog=blog, date_begin=date_begin, date_end=date_end, tags=tag, state=state, page=page, search=search)

        # in case of a redirection need by `_prepare_blog_values` we follow it
        if isinstance(values, werkzeug.wrappers.Response):
            return values

        if blog:
            values['main_object'] = blog
            values['edit_in_backend'] = True
            values['blog_url'] = QueryURL('', ['blog', 'tag'], blog=blog, tag=tag, date_begin=date_begin, date_end=date_end, search=search)
        else:
            values['blog_url'] = QueryURL('/blog', ['tag'], date_begin=date_begin, date_end=date_end, search=search)

        return request.render("website_blog.blog_post_short", values)
Ejemplo n.º 4
0
 def _qweb_prepare_qcontext(self, view_id, domain):
     """
     Base qcontext for rendering qweb views bound to this model
     """
     return {
         'model': self,
         'domain': domain,
         # not necessarily necessary as env is already part of the
         # non-minimal qcontext
         'context': self.env.context,
         'records': lazy(self.search, domain),
     }
Ejemplo n.º 5
0
 def qweb_render_view(self, view_id, domain):
     assert view_id
     return self.env['ir.qweb']._render(
         view_id,
         {
             'model': self,
             'domain': domain,
             # not necessarily necessary as env is already part of the
             # non-minimal qcontext
             'context': self.env.context,
             'records': lazy(self.search, domain),
         })
Ejemplo n.º 6
0
 def _qweb_prepare_qcontext(self, view_id, domain):
     """
     Base qcontext for rendering qweb views bound to this model
     """
     return {
         'model': self,
         'domain': domain,
         # not necessarily necessary as env is already part of the
         # non-minimal qcontext
         'context': self.env.context,
         'records': lazy(self.search, domain),
     }
Ejemplo n.º 7
0
    def test_80_lazy_contains(self):
        """ Test membership on recordset. """
        p1 = lazy(lambda: self.partners[0])
        ps = lazy(lambda: self.partners)
        self.assertTrue(p1 in ps)

        with self.assertRaisesRegex(TypeError, r"unsupported operand types in: 42 in res\.partner.*"):
            lazy(lambda: 42) in ps
        with self.assertRaisesRegex(TypeError, r"inconsistent models in: ir\.ui\.menu.* in res\.partner.*"):
            lazy(lambda: self.env['ir.ui.menu']) in ps
Ejemplo n.º 8
0
    def _prepare_frontend_environment(self, values):
        """ Returns ir.qweb with context and update values with portal specific
            value (required to render portal layout template)
        """
        irQweb = super()._prepare_frontend_environment(values)
        values.update(
            is_html_empty=is_html_empty,
            languages=lazy(lambda: [lang for
                    lang in irQweb.env['res.lang'].get_available()
                    if lang[0] in irQweb.env['ir.http']._get_frontend_langs()])
        )
        for key in irQweb.env.context:
            if key not in values:
                values[key] = irQweb.env.context[key]

        return irQweb
Ejemplo n.º 9
0
    def _prepare_blog_values(self, blogs, blog=False, date_begin=False, date_end=False, tags=False, state=False, page=False, search=None):
        """ Prepare all values to display the blogs index page or one specific blog"""
        BlogPost = request.env['blog.post']
        BlogTag = request.env['blog.tag']

        # prepare domain
        domain = request.website.website_domain()

        if blog:
            domain += [('blog_id', '=', blog.id)]

        if date_begin and date_end:
            domain += [("post_date", ">=", date_begin), ("post_date", "<=", date_end)]
        active_tag_ids = tags and [unslug(tag)[1] for tag in tags.split(',')] or []
        active_tags = BlogTag
        if active_tag_ids:
            active_tags = BlogTag.browse(active_tag_ids).exists()
            fixed_tag_slug = ",".join(slug(t) for t in active_tags)
            if fixed_tag_slug != tags:
                new_url = request.httprequest.full_path.replace("/tag/%s" % tags, "/tag/%s" % fixed_tag_slug, 1)
                if new_url != request.httprequest.full_path:  # check that really replaced and avoid loop
                    return request.redirect(new_url, 301)
            domain += [('tag_ids', 'in', active_tags.ids)]

        if request.env.user.has_group('website.group_website_designer'):
            count_domain = domain + [("website_published", "=", True), ("post_date", "<=", fields.Datetime.now())]
            published_count = BlogPost.search_count(count_domain)
            unpublished_count = BlogPost.search_count(domain) - published_count

            if state == "published":
                domain += [("website_published", "=", True), ("post_date", "<=", fields.Datetime.now())]
            elif state == "unpublished":
                domain += ['|', ("website_published", "=", False), ("post_date", ">", fields.Datetime.now())]
        else:
            domain += [("post_date", "<=", fields.Datetime.now())]

        use_cover = request.website.is_view_active('website_blog.opt_blog_cover_post')
        fullwidth_cover = request.website.is_view_active('website_blog.opt_blog_cover_post_fullwidth_design')

        # if blog, we show blog title, if use_cover and not fullwidth_cover we need pager + latest always
        offset = (page - 1) * self._blog_post_per_page
        if not blog:
            if use_cover and not fullwidth_cover:
                offset += 1

        options = {
            'displayDescription': True,
            'displayDetail': False,
            'displayExtraDetail': False,
            'displayExtraLink': False,
            'displayImage': False,
            'allowFuzzy': not request.params.get('noFuzzy'),
            'blog': str(blog.id) if blog else None,
            'tag': ','.join([str(id) for id in active_tags.ids]),
            'date_begin': date_begin,
            'date_end': date_end,
            'state': state,
        }
        total, details, fuzzy_search_term = request.website._search_with_fuzzy("blog_posts_only", search,
            limit=page * self._blog_post_per_page, order="is_published desc, post_date desc, id asc", options=options)
        posts = details[0].get('results', BlogPost)
        first_post = BlogPost
        if posts and not blog and posts[0].website_published:
            first_post = posts[0]
        posts = posts[offset:offset + self._blog_post_per_page]

        url_args = dict()
        if search:
            url_args["search"] = search

        if date_begin and date_end:
            url_args["date_begin"] = date_begin
            url_args["date_end"] = date_end

        pager = tools.lazy(lambda: request.website.pager(
            url=request.httprequest.path.partition('/page/')[0],
            total=total,
            page=page,
            step=self._blog_post_per_page,
            url_args=url_args,
        ))

        if not blogs:
            all_tags = request.env['blog.tag']
        else:
            all_tags = tools.lazy(lambda: blogs.all_tags(join=True) if not blog else blogs.all_tags().get(blog.id, request.env['blog.tag']))
        tag_category = tools.lazy(lambda: sorted(all_tags.mapped('category_id'), key=lambda category: category.name.upper()))
        other_tags = tools.lazy(lambda: sorted(all_tags.filtered(lambda x: not x.category_id), key=lambda tag: tag.name.upper()))

        # for performance prefetch the first post with the others
        post_ids = (first_post | posts).ids
        # and avoid accessing related blogs one by one
        posts.blog_id

        return {
            'date_begin': date_begin,
            'date_end': date_end,
            'first_post': first_post.with_prefetch(post_ids),
            'other_tags': other_tags,
            'tag_category': tag_category,
            'nav_list': self.nav_list,
            'tags_list': self.tags_list,
            'pager': pager,
            'posts': posts.with_prefetch(post_ids),
            'tag': tags,
            'active_tag_ids': active_tags.ids,
            'domain': domain,
            'state_info': state and {"state": state, "published": published_count, "unpublished": unpublished_count},
            'blogs': blogs,
            'blog': blog,
            'search': fuzzy_search_term or search,
            'search_count': total,
            'original_search': fuzzy_search_term and search,
        }
Ejemplo n.º 10
0
def lazy_name_get(self):
    """Evaluate self.name_get() lazily."""
    names = tools.lazy(lambda: dict(self.name_get()))
    return [(rid, tools.lazy(operator.getitem, names, rid))
            for rid in self.ids]
Ejemplo n.º 11
0
Archivo: main.py Proyecto: GSLabIt/odoo
    def questions(self,
                  forum,
                  tag=None,
                  page=1,
                  filters='all',
                  my=None,
                  sorting=None,
                  search='',
                  **post):
        Post = request.env['forum.post']

        if sorting:
            # check that sorting is valid
            # retro-compatibily for V8 and google links
            try:
                sorting = werkzeug.urls.url_unquote_plus(sorting)
                Post._generate_order_by(sorting, None)
            except (UserError, ValueError):
                sorting = False

        if not sorting:
            sorting = forum.default_order

        options = {
            'displayDescription': False,
            'displayDetail': False,
            'displayExtraDetail': False,
            'displayExtraLink': False,
            'displayImage': False,
            'allowFuzzy': not post.get('noFuzzy'),
            'forum': str(forum.id) if forum else None,
            'tag': str(tag.id) if tag else None,
            'filters': filters,
            'my': my,
        }
        question_count, details, fuzzy_search_term = request.website._search_with_fuzzy(
            "forum_posts_only",
            search,
            limit=page * self._post_per_page,
            order=sorting,
            options=options)
        question_ids = details[0].get('results', Post)
        question_ids = question_ids[(page - 1) * self._post_per_page:page *
                                    self._post_per_page]

        if tag:
            url = "/forum/%s/tag/%s/questions" % (slug(forum), slug(tag))
        else:
            url = "/forum/%s" % slug(forum)

        url_args = {'sorting': sorting}
        if search:
            url_args['search'] = search
        if filters:
            url_args['filters'] = filters
        if my:
            url_args['my'] = my
        pager = tools.lazy(
            lambda: request.website.pager(url=url,
                                          total=question_count,
                                          page=page,
                                          step=self._post_per_page,
                                          scope=self._post_per_page,
                                          url_args=url_args))

        values = self._prepare_user_values(
            forum=forum, searches=post, header={'ask_hide': not forum.active})
        values.update({
            'main_object': tag or forum,
            'edit_in_backend': not tag,
            'question_ids': question_ids,
            'question_count': question_count,
            'search_count': question_count,
            'pager': pager,
            'tag': tag,
            'filters': filters,
            'my': my,
            'sorting': sorting,
            'search': fuzzy_search_term or search,
            'original_search': fuzzy_search_term and search,
        })
        return request.render("website_forum.forum_index", values)
Ejemplo n.º 12
0
    def _prepare_frontend_environment(self, values):
        """ Update the values and context with website specific value
            (required to render website layout template)
        """
        irQweb = super()._prepare_frontend_environment(values)

        Website = irQweb.env['website']
        editable = request.website.is_publisher()
        translatable = editable and irQweb.env.context.get(
            'lang') != irQweb.env['ir.http']._get_default_lang().code
        editable = editable and not translatable

        current_website = Website.get_current_website()

        has_group_publisher = irQweb.env.user.has_group(
            'website.group_website_publisher')
        if has_group_publisher and irQweb.env.user.has_group(
                'website.group_multi_website'):
            values['multi_website_websites_current'] = lazy(
                lambda: current_website.name)
            values['multi_website_websites'] = lazy(
                lambda: [{
                    'website_id': website.id,
                    'name': website.name,
                    'domain': website.domain
                } for website in Website.search([('id', '!=', current_website.
                                                  id)])])

            cur_company = irQweb.env.company
            values['multi_website_companies_current'] = lazy(
                lambda: {
                    'company_id': cur_company.id,
                    'name': cur_company.name
                })
            values['multi_website_companies'] = lazy(
                lambda: [{
                    'company_id': comp.id,
                    'name': comp.name
                } for comp in irQweb.env.user.company_ids
                         if comp != cur_company])

        # update values

        values.update(
            dict(
                website=current_website,
                is_view_active=lazy(lambda: current_website.is_view_active),
                res_company=lazy(request.env['res.company'].browse(
                    current_website._get_cached('company_id')).sudo),
                translatable=translatable,
                editable=editable,
            ))

        if editable:
            # form editable object, add the backend configuration link
            if 'main_object' in values and has_group_publisher:
                func = getattr(values['main_object'], 'get_backend_menu_id',
                               False)
                values['backend_menu_id'] = lazy(
                    lambda: func and func() or irQweb.env['ir.model.data'].
                    _xmlid_to_res_id('website.menu_website_configuration'))

        # update options

        irQweb = irQweb.with_context(website_id=current_website.id)

        if 'inherit_branding' not in irQweb.env.context and not self.env.context.get(
                'rendering_bundle'):
            if editable:
                # in edit mode add brancding on ir.ui.view tag nodes
                irQweb = irQweb.with_context(inherit_branding=True)
            elif has_group_publisher and not translatable:
                # will add the branding on fields (into values)
                irQweb = irQweb.with_context(inherit_branding_auto=True)

        return irQweb