Пример #1
0
    def save_page_info(self, website_id, data):
        website = self.env['website'].browse(website_id)
        page = self.browse(int(data['id']))

        #If URL has been edited, slug it
        original_url = page.url
        url = data['url']
        if not url.startswith('/'):
            url = '/' + url
        if page.url != url:
            url = '/' + slugify(url, max_length=1024, path=True)
            url = self.env['website'].get_unique_path(url)

        #If name has changed, check for key uniqueness
        if page.name != data['name']:
            page_key = self.env['website'].get_unique_key(slugify(data['name']))
        else:
            page_key = page.key

        menu = self.env['website.menu'].search([('page_id', '=', int(data['id']))])
        if not data['is_menu']:
            #If the page is no longer in menu, we should remove its website_menu
            if menu:
                menu.unlink()
        else:
            #The page is now a menu, check if has already one
            if menu:
                menu.write({'url': url})
            else:
                self.env['website.menu'].create({
                    'name': data['name'],
                    'url': url,
                    'page_id': data['id'],
                    'parent_id': website.menu_id.id,
                    'website_id': website.id,
                })

        page.write({
            'key': page_key,
            'name': data['name'],
            'url': url,
            'website_published': data['website_published'],
            'website_indexed': data['website_indexed'],
            'date_publish': data['date_publish'] or None,
            'is_homepage': data['is_homepage'],
        })

        # Create redirect if needed
        if data['create_redirect']:
            self.env['website.redirect'].create({
                'type': data['redirect_type'],
                'url_from': original_url,
                'url_to': url,
                'website_id': website.id,
            })

        return True
Пример #2
0
    def save_page_info(self, website_id, data):
        website = self.env['website'].browse(website_id)

        if data['is_homepage'] and website.homepage_id.id != int(data['id']):
            # If page is set as the new homepage, set it on website (only page can be set as homepage)
            website.write({'homepage_id': data['id']})
        else:
            if not data['is_homepage'] and website.homepage_id.id == int(data['id']):
                # If the page is not a homepage, check if it was the homepage
                website.write({'homepage_id': None})

        #If URL has been edited, slug it
        page = self.browse(int(data['id']))
        original_url = page.url
        url = data['url']
        if page.url != url:
            url = slugify(url, max_length=200, path=True)

        menu = self.env['website.menu'].search([('page_id', '=', int(data['id']))])
        if not data['is_menu']:
            #If the page is no longer in menu, we should remove its website_menu
            if menu:
                menu.unlink()
        else:
            #The page is now a menu, check if has already one
            if menu:
                menu.write({'url': url})
            else:
                self.env['website.menu'].create({
                    'name': data['name'],
                    'url': url,
                    'page_id': data['id'],
                    'parent_id': website.menu_id.id,
                    'website_id': website.id,
                })

        page.write({
            'key': 'website.' + slugify(data['name'], 50),
            'name': data['name'],
            'url': url,
            'website_published': data['website_published'],
            'website_indexed': data['website_indexed'],
            'date_publish': data['date_publish'] or None
        })

        # Create redirect if needed
        if data['create_redirect']:
            self.env['website.redirect'].create({
                'type': data['redirect_type'],
                'url_from': original_url,
                'url_to': url,
                'website_id': website.id,
            })

        return True
Пример #3
0
    def new_page(self, name=False, add_menu=False, template='website.default_page', ispage=True, namespace=None):
        """ Create a new website page, and assign it a xmlid based on the given one
            :param name : the name of the page
            :param template : potential xml_id of the page to create
            :param namespace : module part of the xml_id if none, the template module name is used
        """
        if namespace:
            template_module = namespace
        else:
            template_module, _ = template.split('.')
        page_url = '/' + slugify(name, max_length=1024, path=True)
        page_url = self.get_unique_path(page_url)
        page_key = slugify(name)
        result = dict({'url': page_url, 'view_id': False})

        if not name:
            name = 'Home'
            page_key = 'home'

        template_record = self.env.ref(template)
        website_id = self._context.get('website_id')
        key = self.get_unique_key(page_key, template_module)
        view = template_record.copy({'website_id': website_id, 'key': key})

        view.with_context(lang=None).write({
            'arch': template_record.arch.replace(template, key),
            'name': name,
        })

        if view.arch_fs:
            view.arch_fs = False

        website = self.get_current_website()
        if ispage:
            page = self.env['website.page'].create({
                'url': page_url,
                'website_id': website.id,  # remove it if only one webiste or not?
                'view_id': view.id,
            })
            result['view_id'] = view.id
        if add_menu:
            self.env['website.menu'].create({
                'name': name,
                'url': page_url,
                'parent_id': website.menu_id.id,
                'page_id': page.id,
                'website_id': website.id,
            })
        return result
Пример #4
0
    def new_page(self, name, template='website.default_page', ispage=True, namespace=None):
        """ Create a new website page, and assign it a xmlid based on the given one
            :param name : the name of the page
            :param template : potential xml_id of the page to create
            :param namespace : module part of the xml_id if none, the template module name is used
        """
        if namespace:
            template_module = namespace
        else:
            template_module, dummy = template.split('.')
        website_id = self._context.get('website_id')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        # find a free xmlid
        inc = 0
        domain_static = [('website_id', '=', False), ('website_id', '=', website_id)]
        while self.env['ir.ui.view'].with_context(active_test=False).sudo().search([('key', '=', page_xmlid), '|'] + domain_static):
            inc += 1
            page_xmlid = "%s.%s" % (template_module, page_name + ("-%s" % inc if inc else ""))
        page_name += (inc and "-%s" % inc or "")

        # new page
        template_record = self.env.ref(template)
        key = '%s.%s' % (template_module, page_name)
        page = template_record.copy({'website_id': website_id, 'key': key})
        page.with_context(lang=None).write({
            'arch': page.arch.replace(template, page_xmlid),
            'name': page_name,
            'page': ispage,
        })
        return page_xmlid
Пример #5
0
    def get_seo_data(self, res_id, res_model):
        if not request.env.user.has_group('website.group_website_publisher'):
            raise werkzeug.exceptions.Forbidden()

        fields = ['website_meta_title', 'website_meta_description', 'website_meta_keywords', 'website_meta_og_img']
        if res_model == 'website.page':
            fields.extend(['website_indexed', 'website_id'])

        record = request.env[res_model].browse(res_id)
        res = record._read_format(fields)[0]
        res['has_social_default_image'] = request.website.has_social_default_image

        if res_model not in ('website.page', 'ir.ui.view') and 'seo_name' in record:  # allow custom slugify
            res['seo_name_default'] = slugify(record.display_name)  # default slug, if seo_name become empty
            res['seo_name'] = record.seo_name and slugify(record.seo_name) or ''
        return res
Пример #6
0
    def new_page(self, name, template='website.default_page', ispage=True, namespace=None):
        """ Create a new website page, and assign it a xmlid based on the given one
            :param name : the name of the page
            :param template : potential xml_id of the page to create
            :param namespace : module part of the xml_id if none, the template module name is used
        """
        if namespace:
            template_module = namespace
        else:
            template_module, dummy = template.split('.')
        website_id = self._context.get('website_id')

        # completely arbitrary max_length
        page_name = slugify(name, max_length=50)
        page_xmlid = "%s.%s" % (template_module, page_name)

        # find a free xmlid
        inc = 0
        domain_static = [('website_id', '=', False), ('website_id', '=', website_id)]
        while self.env['ir.ui.view'].with_context(active_test=False).sudo().search([('key', '=', page_xmlid), '|'] + domain_static):
            inc += 1
            page_xmlid = "%s.%s" % (template_module, page_name + ("-%s" % inc if inc else ""))
        page_name += (inc and "-%s" % inc or "")

        # new page
        template_record = self.env.ref(template)
        key = '%s.%s' % (template_module, page_name)
        page = template_record.copy({'website_id': website_id, 'key': key})
        page.with_context(lang=None).write({
            'arch': page.arch.replace(template, page_xmlid),
            'name': page_name,
            'page': ispage,
        })
        return page_xmlid
Пример #7
0
    def clone_page(self, page_id, page_name=None, clone_menu=True):
        """ Clone a page, given its identifier
            :param page_id : website.page identifier
        """
        page = self.browse(int(page_id))
        copy_param = dict(
            name=page_name or page.name,
            website_id=self.env['website'].get_current_website().id)
        if page_name:
            page_url = '/' + slugify(page_name, max_length=1024, path=True)
            copy_param['url'] = self.env['website'].get_unique_path(page_url)

        new_page = page.copy(copy_param)
        # Should not clone menu if the page was cloned from one website to another
        # Eg: Cloning a generic page (no website) will create a page with a website, we can't clone menu (not same container)
        if clone_menu and new_page.website_id == page.website_id:
            menu = self.env['website.menu'].search([('page_id', '=', page_id)],
                                                   limit=1)
            if menu:
                # If the page being cloned has a menu, clone it too
                menu.copy({
                    'url': new_page.url,
                    'name': new_page.name,
                    'page_id': new_page.id
                })

        return new_page.url + '?enable_editor=1'
Пример #8
0
 def search_pages(self, needle=None, limit=None):
     name = slugify(needle, max_length=50, path=True)
     res = []
     for page in self.enumerate_pages(query_string=name, force=True):
         res.append(page)
         if len(res) == limit:
             break
     return res
Пример #9
0
 def search_pages(self, needle=None, limit=None):
     name = slugify(needle, max_length=50, path=True)
     res = []
     for page in self.enumerate_pages(query_string=name, force=True):
         res.append(page)
         if len(res) == limit:
             break
     return res
Пример #10
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report = request.env['ir.actions.report']._get_report_from_name(
            reportname)
        context = dict(request.env.context)

        # Get filename for report
        filepart = "report"

        if docids:
            docids = [int(i) for i in docids.split(',')]
        if data.get('options'):
            data.update(json.loads(data.pop('options')))
        if data.get('context'):
            # Ignore 'lang' here, because the context in data is the one from the webclient *but* if
            # the user explicitly wants to change the lang, this mechanism overwrites it.
            data['context'] = json.loads(data['context'])
            if data['context'].get('lang'):
                del data['context']['lang']
            context.update(data['context'])
        if converter == 'html':
            html = report.with_context(context).render_qweb_html(docids,
                                                                 data=data)[0]
            return request.make_response(html)
        elif converter == 'pdf':
            pdf = report.with_context(context).render_qweb_pdf(docids,
                                                               data=data)[0]

            # Get filename for report
            if docids:
                if len(docids) > 1:
                    filepart = "%s (x%s)" % (
                        request.env['ir.model'].sudo().search([
                            ('model', '=', report.model)
                        ]).name, str(len(docids)))
                elif len(docids) == 1:
                    obj = request.env[report.model].browse(docids)
                    if report.print_report_name:
                        filepart = safe_eval(report.print_report_name, {
                            'object': obj,
                            'time': time
                        })
            else:
                filepart = "report"

            pdfhttpheaders = [('Content-Type', 'application/pdf'),
                              ('Content-Length', len(pdf)),
                              ('Content-Disposition',
                               'filename="%s.pdf"' % slugify(filepart))]
            return request.make_response(pdf, headers=pdfhttpheaders)
        elif converter == 'text':
            text = report.with_context(context).render_qweb_text(docids,
                                                                 data=data)[0]
            texthttpheaders = [('Content-Type', 'text/plain'),
                               ('Content-Length', len(text))]
            return request.make_response(text, headers=texthttpheaders)
        else:
            raise werkzeug.exceptions.HTTPException(
                description='Converter %s not implemented.' % converter)
Пример #11
0
 def search_pages(self, needle=None, limit=None):
     name = re.sub(r"^/p(a(g(e(/(w(e(b(s(i(t(e(\.)?)?)?)?)?)?)?)?)?)?)?)?", "", needle or "")
     name = slugify(name, max_length=50)
     res = []
     for page in self.enumerate_pages(query_string=name):
         res.append(page)
         if len(res) == limit:
             break
     return res
Пример #12
0
 def _compute_xls_name(self):
     for record in self:
         if record.year and record.month:
             filename = '%s/%02d %s' % (record.year, int(
                 record.month), record.name)
             filename = slugify(filename) + '.xlsx'
         else:
             filename = 'allocation.xlsx'
         record.allocation_lines_xlsx_filename = filename
Пример #13
0
    def delete(self, survey, token, **post):
        domain = [('token', '=', token), ('survey_id', '=', survey.id)]
        user_input = request.env['survey.user_input'].search(domain)
        for input in user_input:
            if input.sudo().order_id.state == 'draft':
                input.sudo().unlink()

        return request.redirect("/event/%s/registration_survey_list" %
                                slugify(survey.event_id))
Пример #14
0
 def search_pages(self, needle=None, limit=None):
     name = re.sub(r"^/p(a(g(e(/(w(e(b(s(i(t(e(\.)?)?)?)?)?)?)?)?)?)?)?)?", "", needle or "")
     name = slugify(name, max_length=50)
     res = []
     for page in self.enumerate_pages(query_string=name):
         res.append(page)
         if len(res) == limit:
             break
     return res
Пример #15
0
    def new_page(self, name=False, add_menu=False, template='website.default_page', ispage=True, namespace=None):
        """ Create a new website page, and assign it a xmlid based on the given one
            :param name : the name of the page
            :param template : potential xml_id of the page to create
            :param namespace : module part of the xml_id if none, the template module name is used
        """
        if namespace:
            template_module = namespace
        else:
            template_module, _ = template.split('.')
        page_url = '/' + slugify(name, max_length=1024, path=True)
        page_url = self.get_unique_path(page_url)
        page_key = slugify(name)
        result = dict({'url': page_url, 'view_id': False})

        if not name:
            name = 'Home'
            page_key = 'home'

        template_record = self.env.ref(template)
        website_id = self._context.get('website_id')
        key = self.get_unique_key(page_key, template_module)
        view = template_record.copy({'website_id': website_id, 'key': key})

        view.with_context(lang=None).write({
            'arch': template_record.arch.replace(template, key),
            'name': name,
        })
        if ispage:
            page = self.env['website.page'].create({
                'url': page_url,
                'website_ids': [(6, None, [self.get_current_website().id])],
                'view_id': view.id
            })
            result['view_id'] = view.id
        if add_menu:
            self.env['website.menu'].create({
                'name': name,
                'url': page_url,
                'parent_id': self.get_current_website().menu_id.id,
                'page_id': page.id,
                'website_id': self.get_current_website().id,
            })
        return result
Пример #16
0
    def new_page(self, name=False, add_menu=False, template='website.default_page', ispage=True, namespace=None):
        """ Create a new website page, and assign it a xmlid based on the given one
            :param name : the name of the page
            :param template : potential xml_id of the page to create
            :param namespace : module part of the xml_id if none, the template module name is used
        """
        if namespace:
            template_module = namespace
        else:
            template_module, _ = template.split('.')
        # completely arbitrary max_length
        page_url = '/' + slugify(name, max_length=200, path=True)
        page_key = self.get_unique_path(slugify(name, 50))
        result = dict({'url': page_url, 'view_id': False})

        if not name:
            name = 'Home'
            page_key = 'home'

        template_record = self.env.ref(template)
        website_id = self._context.get('website_id')
        key = '%s.%s' % (template_module, page_key)
        view = template_record.copy({'website_id': website_id, 'key': key})

        view.with_context(lang=None).write({
            'arch': template_record.arch.replace(template, key),
            'name': name,
        })
        if ispage:
            page = self.env['website.page'].create({
                'url': page_url,
                'website_ids': [(6, None, [self.get_current_website().id])],
                'view_id': view.id
            })
            result['view_id'] = view.id
        if add_menu:
            self.env['website.menu'].create({
                'name': name,
                'url': page_url,
                'parent_id': self.get_current_website().menu_id.id,
                'page_id': page.id,
                'website_id': self.get_current_website().id,
            })
        return result
Пример #17
0
    def save_page_info(self, website_id, data):
        website = self.env['website'].browse(website_id)

        if data['is_homepage'] and website.homepage_id.id != int(data['id']):
            # If page is set as the new homepage, set it on website (only page can be set as homepage)
            website.write({'homepage_id': data['id']})
        else:
            if not data['is_homepage'] and website.homepage_id.id == int(
                    data['id']):
                # If the page is not a homepage, check if it was the homepage
                website.write({'homepage_id': None})

        #If URL has been edited, slug it
        page = self.browse(int(data['id']))
        original_url = page.url
        url = data['url']
        if page.url != url:
            url = slugify(url, max_length=200, path=True)

        menu = self.env['website.menu'].search([('page_id', '=',
                                                 int(data['id']))])
        if not data['is_menu']:
            #If the page is no longer in menu, we should remove its website_menu
            if menu:
                menu.unlink()
        else:
            #The page is now a menu, check if has already one
            if menu:
                menu.write({'url': url})
            else:
                self.env['website.menu'].create({
                    'name': data['name'],
                    'url': url,
                    'page_id': data['id'],
                    'parent_id': website.menu_id.id,
                    'website_id': website.id,
                })

        page.write({
            'name': data['name'],
            'url': url,
            'website_published': data['website_published'],
            'website_indexed': data['website_indexed'],
            'date_publish': data['date_publish'] or None
        })

        # Create redirect if needed
        if data['create_redirect']:
            self.env['website.redirect'].create({
                'type': data['redirect_type'],
                'url_from': original_url,
                'url_to': url,
                'website_id': website.id,
            })

        return True
Пример #18
0
    def report_routes(self, reportname, docids=None, converter=None, **data):
        report = request.env["ir.actions.report"]._get_report_from_name(reportname)
        context = dict(request.env.context)

        if docids:
            docids = [int(i) for i in docids.split(",")]
        if data.get("options"):
            data.update(json.loads(data.pop("options")))
        if data.get("context"):
            data["context"] = json.loads(data["context"])
            if data["context"].get("lang"):
                del data["context"]["lang"]
            context.update(data["context"])
        if converter == "html":
            html = report.with_context(context)._render_qweb_html(docids, data=data)[0]
            return request.make_response(html)
        elif converter == "pdf":

            # Get filename for report
            filepart = "report"

            if docids:
                if len(docids) > 1:
                    filepart = "{} (x{})".format(
                        request.env["ir.model"]
                        .sudo()
                        .search([("model", "=", report.model)])
                        .name,
                        str(len(docids)),
                    )
                elif len(docids) == 1:
                    obj = request.env[report.model].browse(docids)
                    if report.print_report_name:
                        filepart = safe_eval(
                            report.print_report_name, {"object": obj, "time": time}
                        )

            pdf = report.with_context(context)._render_qweb_pdf(docids, data=data)[0]
            pdfhttpheaders = [
                ("Content-Type", "application/pdf"),
                ("Content-Length", len(pdf)),
                ("Content-Disposition", 'filename="%s.pdf"' % slugify(filepart)),
            ]
            return request.make_response(pdf, headers=pdfhttpheaders)
        elif converter == "text":
            text = report.with_context(context)._render_qweb_text(docids, data=data)[0]
            texthttpheaders = [
                ("Content-Type", "text/plain"),
                ("Content-Length", len(text)),
            ]
            return request.make_response(text, headers=texthttpheaders)
        else:
            raise werkzeug.exceptions.HTTPException(
                description="Converter %s not implemented." % converter
            )
Пример #19
0
 def createUrlKey(self, modelObj, fieldsList):
     url_key = []
     for field in fieldsList:
         if hasattr(modelObj, field):
             name = getattr(modelObj, field)
             name = slugify(name or '').strip().strip('-')
             url_key.append(name)
     urlKey = '-'.join(url_key)
     if not urlKey:
         urlKey = slug(modelObj)
     return urlKey
def migrate(cr, installed_version):
    env = api.Environment(cr, SUPERUSER_ID, {})

    # Migrate timesheet activity
    Activity = env['request.timesheet.activity'].with_context(
        active_test=False)
    for record in Activity.search([('code', '=', False)]):
        code = slugify(record.display_name, max_length=0)
        if Activity.search_count([('code', '=', code)]) > 0:
            code = "%s-%s" % (code, record.id)
        record.code = code
Пример #21
0
 def _get_seats_name_mapping(self):
     self.ensure_one()
     res = {}
     for line in self.seats_names.split('\n'):
         line = line.strip()
         if line:
             seat, name = list(map(str.strip, line.split(':', 1)))
             res[seat] = {
                 'classes': slugify(name),
                 'category': name,
             }
     return res
Пример #22
0
    def _record2id(self, record):
        existing = self.env["ir.model.data"].search([
            ("model", "=", record._name), ("res_id", "=", record.id)
        ])
        if existing:
            existing = existing[0]
            if existing.module == self.module:
                return existing.name
            else:
                return existing.complete_name

        xmlid = "{}_{}".format(slugify(record.display_name),
                               slugify(record._description))

        self.env["ir.model.data"].create({
            "model": record._name,
            "res_id": record.id,
            "module": self.module,
            "name": xmlid,
        })
        return xmlid
Пример #23
0
 def edit(self, survey, token, **post):
     domain = [('token', '=', token), ('survey_id', '=', survey.id)]
     user_input = request.env['survey.user_input'].search(domain)
     if user_input:
         user_input.ensure_one()
         if user_input.sudo().order_id.state == 'draft':
             user_input.state = 'new'
             return request.redirect('/survey/fill/%s/%s' %
                                     (survey.id, token))
         else:
             return request.redirect("/event/%s/registration_survey_list" %
                                     slugify(survey.event_id))
Пример #24
0
    def registration_survey_list(self, event, error_msg='', **post):
        attendees = self._get_attendees(event, **post)
        if not attendees:
            return request.redirect("/event/%s/register" % slugify(event))

        total_price = sum(
            [a['event_registration_total_price'] for a in attendees])
        data = {
            'attendees': attendees,
            'total_price': total_price,
            'event': event,
            'error_msg': error_msg
        }
        return request.render("event_survey.registration_survey_list", data)
Пример #25
0
    def new_page(self,
                 name=False,
                 add_menu=False,
                 template='website.default_page',
                 ispage=True,
                 namespace=None):
        res = super(Website, self).new_page(name,
                                            add_menu,
                                            template,
                                            ispage=True,
                                            namespace=namespace)
        if ispage:
            arch = "<?xml version='1.0'?><t t-name='website." + slugify(
                str(name)) + "'><t t-call='website.layout'> \
                    <div id='wrap' class='oe_structure oe_empty'>"

            arch = arch + '<t t-if="not website.is_breadcum">'

            arch =arch+'<t t-if="website.breadcum_background_image">'\
                '<nav class="is-breadcrumb shop-breadcrumb" role="navigation" aria-label="breadcrumbs" t-attf-style="background:none;background-color:#{website.breadcrumb_color};padding:#{website.breadcrumb_height};">'\
                      '<div class="container">'\
                        '<h1><span t-attf-style="color:#{website.breadcrumb_text_color}">'+saxutils.escape(str(name))+'</span></h1>'\
                        '<ul class="breadcrumb">'\
                            '<li><a href="/page/homepage" t-attf-style="color:#{website.breadcrumb_text_color}">Home</a></li>'\
                            '<li class="active"><span t-attf-style="color:#{website.breadcrumb_text_color}">'+saxutils.escape(str(name))+'</span></li>'\
                        '</ul>'\
                      '</div>'\
                '</nav>'\
                '</t>'
            arch=arch+'<t t-if="not website.breadcum_background_image">'\
                '<t t-set="bread_cum" t-value="website.image_url(website,'+repr('bread_cum_image')+')"/>'\
                '<nav class="is-breadcrumb shop-breadcrumb" role="navigation" aria-label="breadcrumbs" t-attf-style="background-image:url(#{bread_cum}#);padding:#{website.breadcrumb_height};">'\
                    '<div class="container">'\
                        '<h1><span t-attf-style="color:#{website.breadcrumb_text_color}">'+saxutils.escape(str(name))+'</span></h1>'\
                        '<ul class="breadcrumb">'\
                            '<li><a href="/page/homepage" t-attf-style="color:#{website.breadcrumb_text_color}">Home</a></li>'\
                            '<li class="active"><span t-attf-style="color:#{website.breadcrumb_text_color}">'+saxutils.escape(str(name))+'</span></li>'\
                        '</ul>'\
                      '</div>'\
                '</nav>'\
            '</t>'
            arch = arch + '</t>'
            arch = arch + '<div class="oe_structure"/>'
            arch = arch + '</div></t></t>'
            view_id = res['view_id']
            view = self.env['ir.ui.view'].browse(int(view_id))
            view.write({'arch': arch})
        return res
Пример #26
0
 def message_new(self, msg_dict, custom_values=None):
     custom_values = custom_values if custom_values is not None else {}
     parent_directory_id = custom_values.get("parent_id", None)
     parent_directory = self.sudo().browse(parent_directory_id)
     if not parent_directory_id or not parent_directory.exists():
         raise ValueError("No directory could be found!")
     if parent_directory.alias_process == "files":
         parent_directory._process_message(msg_dict)
         return parent_directory
     names = parent_directory.child_directory_ids.mapped("name")
     subject = slugify(msg_dict.get("subject", _("Alias-Mail-Extraction")))
     defaults = dict(
         {"name": unique_name(subject, names, escape_suffix=True)},
         **custom_values)
     directory = super().message_new(msg_dict, custom_values=defaults)
     directory._process_message(msg_dict)
     return directory
Пример #27
0
 def confirm_sheet(self):
     """
     confirm Advice - confirmed Advice after computing Advice Lines..
     """
     seq_obj = self.env['ir.sequence']
     for advice in self:
         if not advice.line_count:
             raise ValidationError(
                 'You can not confirm Payment advice without advice lines.')
         advice_year = advice.date_generated.strftime(
             '%m') + '-' + advice.date_generated.strftime('%Y')
         number = seq_obj.next_by_code('disbursement.advice')
         sequence_num = 'PAY' + '/' + slugify(
             advice.bank_id.name,
             max_length=8).upper() + '/' + advice_year + '/' + number
         advice.write({'number': sequence_num, 'state': 'confirm'})
     return True
Пример #28
0
 def _make_exchange_filename(self, exchange_record):
     """Generate filename."""
     pattern = self.exchange_filename_pattern
     ext = self.exchange_file_ext
     pattern = pattern + ".{ext}"
     dt = slugify(fields.Datetime.to_string(fields.Datetime.now()))
     record_name = self._get_record_name(exchange_record)
     record = exchange_record
     if exchange_record.model and exchange_record.res_id:
         record = exchange_record.record
     return pattern.format(
         exchange_record=exchange_record,
         record=record,
         record_name=record_name,
         type=self,
         dt=dt,
         ext=ext,
     )
Пример #29
0
    def is_available(self, database_name, operator_id, **kw):
        database_name = database_name.lower().strip()
        if not database_name:
            return {"answer": "Empty database name"}

        if database_name != slugify(database_name):
            return {"answer": "Invalid database name"}

        is_free_slot = not request.env["saas.db"].sudo().search(
            [("name", "=", database_name)])
        if is_free_slot:
            return {
                "domain":
                request.env["saas.operator"].sudo().browse(
                    int(operator_id)).db_url_template.format(
                        db_name=database_name)
            }
        else:
            return {"answer": "Database already exists"}
Пример #30
0
    def registration_survey_list_confirm(self, event, **post):

        order = request.website.sale_get_order()
        OrderLine = request.env['sale.order.line']
        Registration = request.env['event.registration']

        # validation with server action
        action = event.registration_validation_action_id
        user = event.company_id.user_tech_id
        if action and action.state == 'code' and action.website_published:
            error_msg = action.with_context(
                active_id=order.id,
                active_model='sale.order').sudo(user).run()
            if error_msg:
                return request.redirect(
                    "/event/%s/registration_survey_list/%s" %
                    (slugify(event), error_msg))

        # delete previously registered attendees on this sales order, and event-related products in the shopping cart
        Registration.sudo().search([('sale_order_id', '=', order.id)]).unlink()
        tickets = event.event_ticket_ids
        labels = request.env['survey.question.answer'].search(
            []).filtered(lambda l: l.question_id.page_id.survey_id.event_id ==
                         event and l.product_id)
        product_ids = [t.product_id.id
                       for t in tickets] + [l.product_id.id for l in labels]
        OrderLine.sudo().search([('order_id', '=', order.id),
                                 ('product_id', 'in', product_ids)]).unlink()

        # event partner > public partner (to skip address)
        if order.partner_id == event.registration_partner_id:
            order.partner_id = request.website.user_id.sudo().partner_id.id

        # get attendees
        attendees = self._get_attendees(event, **post)
        for count, attendee in enumerate(attendees, start=1):
            i = str(count) + '-'
            post.update({i + k: v for k, v in attendee.items()})

        # Take the user to the next step (confirmation or payment)
        controller = WebsiteEventSaleController2()
        return controller.registration_confirm(event, **post)
Пример #31
0
    def rename_page(self, view_id, new_name):
        """ Change the name of the given page
            :param view_id : id of the view to rename
            :param new_name : name to use
        """
        view = self.key_to_view_id(view_id)
        if view:
            # slugify the new name and prefix by module if
            # not already done by end user
            new_name = slugify(new_name, max_length=50)
            prefix = view.key.split('.')[0]
            if not new_name.startswith(prefix):
                new_name = "%s.%s" % (prefix, new_name)

            view.write({
                'key': new_name,
                'arch_db': view.arch_db.replace(view.key, new_name, 1)
            })
            return new_name
        return False
Пример #32
0
    def rename_page(self, view_id, new_name):
        """ Change the name of the given page
            :param view_id : id of the view to rename
            :param new_name : name to use
        """
        view = self.key_to_view_id(view_id)
        if view:
            # slugify the new name and prefix by module if
            # not already done by end user
            new_name = slugify(new_name, max_length=50)
            prefix = view.key.split('.')[0]
            if not new_name.startswith(prefix):
                new_name = "%s.%s" % (prefix, new_name)

            view.write({
                'key': new_name,
                'arch_db': view.arch_db.replace(view.key, new_name, 1)
            })
            return new_name
        return False
Пример #33
0
    def _export_allocation_lines(self):
        calculation_type = self.get_calculation_type()
        headers, lines_values = self._get_allocation_lines_data()

        report_name = '%s-%02d %s' % (self.year, int(self.month), self.name)
        report_name = slugify(report_name)

        output = io.BytesIO()
        workbook = xlsxwriter.Workbook(output, {'in_memory': True})
        sheet = workbook.add_worksheet(calculation_type)

        style_header = workbook.add_format({
            'font_name': 'Arial',
            'bold': True,
            'bg_color': '#eeeeee'
        })
        style_data = workbook.add_format({'font_name': 'Arial'})

        offset_x = 0
        offset_y = 0
        for header in headers:
            sheet.write(offset_y, offset_x, header, style_header)
            offset_x += 1

        for row in lines_values:
            offset_y += 1
            offset_x = 0
            for value in row:
                sheet.write(offset_y, offset_x, value, style_data)
                offset_x += 1

        workbook.close()
        output.seek(0)
        generated_file = output.read()
        output.close()

        self.write(
            {'allocation_lines_xlsx': base64.encodebytes(generated_file)})
Пример #34
0
    def save_page_info(self, website_id, data):
        website = self.env['website'].browse(website_id)
        page = self.browse(int(data['id']))

        # If URL has been edited, slug it
        original_url = page.url
        url = data['url']
        if not url.startswith('/'):
            url = '/' + url
        if page.url != url:
            url = '/' + slugify(url, max_length=1024, path=True)
            url = self.env['website'].get_unique_path(url)

        # If name has changed, check for key uniqueness
        if page.name != data['name']:
            page_key = self.env['website'].get_unique_key(slugify(
                data['name']))
        else:
            page_key = page.key

        menu = self.env['website.menu'].search([('page_id', '=',
                                                 int(data['id']))])
        if not data['is_menu']:
            # If the page is no longer in menu, we should remove its website_menu
            if menu:
                menu.unlink()
        else:
            # The page is now a menu, check if has already one
            if menu:
                menu.write({'url': url})
            else:
                self.env['website.menu'].create({
                    'name': data['name'],
                    'url': url,
                    'page_id': data['id'],
                    'parent_id': website.menu_id.id,
                    'website_id': website.id,
                })

        # Edits via the page manager shouldn't trigger the COW
        # mechanism and generate new pages. The user manages page
        # visibility manually with is_published here.
        w_vals = {
            'key': page_key,
            'name': data['name'],
            'url': url,
            'is_published': data['website_published'],
            'website_indexed': data['website_indexed'],
            'date_publish': data['date_publish'] or None,
            'is_homepage': data['is_homepage'],
            'secure_page': data['secure_page'],
        }
        page.with_context(no_cow=True).write(w_vals)

        # Create redirect if needed
        if data['create_redirect']:
            self.env['website.redirect'].create({
                'type': data['redirect_type'],
                'url_from': original_url,
                'url_to': url,
                'website_id': website.id,
            })

        return url
Пример #35
0
 def test_all(self):
     self.assertEqual(
         "do-you-know-martine-a-la-plage",
         slugify(u"Do YOU know 'Martine à la plage' ?")
     )
Пример #36
0
 def test_caps(self):
     self.assertEqual(
         "camelcase",
         slugify(u"CamelCase")
     )
Пример #37
0
    def save_page_info(self, website_id, data):
        website = self.env['website'].browse(website_id)
        page = self.browse(int(data['id']))

        # If URL has been edited, slug it
        original_url = page.url
        url = data['url']
        if not url.startswith('/'):
            url = '/' + url
        if page.url != url:
            url = '/' + slugify(url, max_length=1024, path=True)
            url = self.env['website'].get_unique_path(url)

        # If name has changed, check for key uniqueness
        if page.name != data['name']:
            page_key = self.env['website'].get_unique_key(slugify(data['name']))
        else:
            page_key = page.key

        menu = self.env['website.menu'].search([('page_id', '=', int(data['id']))])
        if not data['is_menu']:
            # If the page is no longer in menu, we should remove its website_menu
            if menu:
                menu.unlink()
        else:
            # The page is now a menu, check if has already one
            if menu:
                menu.write({'url': url})
            else:
                self.env['website.menu'].create({
                    'name': data['name'],
                    'url': url,
                    'page_id': data['id'],
                    'parent_id': website.menu_id.id,
                    'website_id': website.id,
                })

        # Edits via the page manager shouldn't trigger the COW
        # mechanism and generate new pages. The user manages page
        # visibility manually with is_published here.
        w_vals = {
            'key': page_key,
            'name': data['name'],
            'url': url,
            'is_published': data['website_published'],
            'website_id': False if data['share_page_info'] else website.id,
            'website_indexed': data['website_indexed'],
            'date_publish': data['date_publish'] or None,
            'is_homepage': data['is_homepage'],
        }
        # toggle is hidden to prevent user to unshare a page
        if 'share_page_info' in data:
            w_vals['website_id'] = False if data['share_page_info'] else website.id
        page.with_context(no_cow=True).write(w_vals)

        # Create redirect if needed
        if data['create_redirect']:
            self.env['website.redirect'].create({
                'type': data['redirect_type'],
                'url_from': original_url,
                'url_to': url,
                'website_id': website.id,
            })

        return url
Пример #38
0
 def _normalize_tech_name(name):
     return slugify(name).replace("-", "_")
Пример #39
0
 def _product_link_code(self, link):
     """Normalize link code, default to `generic` when missing."""
     return slugify(link.type_id.code or "generic").replace("-", "_")
Пример #40
0
 def _onchange_name(self):
     self.description = slugify(self.name) + '-' + str(datetime.now())
Пример #41
0
 def _compute_name(self):
     for r in self:
         name = slugify(r.project_id.name).replace("-", "_")
         name = "sync_project_{}_data.xml".format(name)
         r.name = name
         r.name2 = "{}.txt".format(name)
Пример #42
0
 def test_numbers(self):
     self.assertEqual(
         "article-1",
         slugify(u"Article 1")
     )
Пример #43
0
 def test_underscore(self):
     self.assertEqual(
         "one-two",
         slugify(u"one_two")
     )
Пример #44
0
 def test_unicode(self):
     self.assertEqual(
         "heterogeneite",
         slugify(u"hétérogénéité")
     )
Пример #45
0
 def test_spaces(self):
     self.assertEqual(
         "spaces",
         slugify(u"   spaces   ")
     )
Пример #46
0
 def test_special_chars(self):
     self.assertEqual(
         "o-d-o-o",
         slugify(u"o!#d{|\o/@~o&%^?")
     )
Пример #47
0
 def test_str_to_unicode(self):
     self.assertEqual(
         "espana",
         slugify("España")
     )