<commit_before># -*- coding: utf-8 -*-
import datetime
import werkzeug

from collections import OrderedDict

from odoo import fields
from odoo.addons.web import http
from odoo.addons.web.http import request
from odoo.addons.website.models.website import slug, unslug
from odoo.addons.website_partner.controllers.main import WebsitePartnerPage
from odoo.tools.translate import _

from odoo.addons.website_portal.controllers.main import website_account


class WebsiteAccount(website_account):

    @http.route()
    def account(self):
        response = super(WebsiteAccount, self).account()
        lead_count = request.env['crm.lead'].search_count([
            ('partner_assigned_id', '=', request.env.user.partner_id.id),
            ('type', '=', 'lead')
        ])
        opp_count = request.env['crm.lead'].search_count([
            ('partner_assigned_id', '=', request.env.user.partner_id.id),
            ('type', '=', 'opportunity')
        ])
        response.qcontext.update({'lead_count': lead_count, 'opp_count': opp_count})
        return response

    @http.route(['/my/leads', '/my/leads/page/<int:page>'], type='http', auth="user", website=True)
    def portal_my_leads(self, page=1, date_begin=None, date_end=None, lead=None, sortby=None, **kw):
        values = self._prepare_portal_layout_values()
        CrmLead = request.env['crm.lead']
        domain = [('partner_assigned_id', '=', request.env.user.partner_id.id), ('type', '=', 'lead')]

        sortings = {
            'date': {'label': _('Newest'), 'order': 'create_date desc'},
            'name': {'label': _('Name'), 'order': 'name'},
            'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'},
        }

        order = sortings.get(sortby, sortings['date'])['order']

        # archive groups - Default Group By 'create_date'
        archive_groups = self._get_archive_groups('crm.lead', domain)
        if date_begin and date_end:
            domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
        # pager
        lead_count = CrmLead.search_count(domain)
        pager = request.website.pager(
            url="/my/leads",
            url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'lead': lead},
            total=lead_count,
            page=page,
            step=self._items_per_page
        )
        # content according to pager and archive selected
        leads = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])

        values.update({
            'date': date_begin,
            'leads': leads,
            'page_name': 'lead',
            'lead': lead,
            'sortings': sortings,
            'sortby': sortby,
            'archive_groups': archive_groups,
            'default_url': '/my/leads',
            'pager': pager
        })
        return request.website.render("website_crm_partner_assign.portal_my_leads", values)

    @http.route(['/my/opportunities', '/my/opportunities/page/<int:page>'], type='http', auth="user", website=True)
    def portal_my_opportunities(self, page=1, date_begin=None, date_end=None, opportunity=None, sortby=None, **kw):
        values = self._prepare_portal_layout_values()
        CrmLead = request.env['crm.lead']
        domain = [('partner_assigned_id', '=', request.env.user.partner_id.id), ('type', '=', 'opportunity')]

        today = fields.Date.today()
        this_week_end_date = fields.Date.to_string(fields.Date.from_string(today) + datetime.timedelta(days=7))

        filters = {
            'all': {'label': _('All'), 'domain': []},
            'today': {'label': _('Today Activities'), 'domain': [('date_action', '=', today)]},
            'week': {'label': _('This Week Activities'),
                     'domain': [('date_action', '>=', today), ('date_action', '<=', this_week_end_date)]},
            'overdue': {'label': _('Overdue Activities'), 'domain': [('date_action', '<', today)]},
            'won': {'label': _('Won'), 'domain': [('stage_id.probability', '=', 100), ('stage_id.fold', '=', True)]},
            'lost': {'label': _('Lost'), 'domain': [('active', '=', False)]},
        }

        sortings = {
            'date': {'label': _('Newest'), 'order': 'create_date desc'},
            'name': {'label': _('Name'), 'order': 'name'},
            'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'},
            'revenue': {'label': _('Expected Revenue'), 'order': 'planned_revenue desc'},
            'probability': {'label': _('Probability'), 'order': 'probability desc'},
            'stage': {'label': _('Stage'), 'order': 'stage_id'},
        }

        domain += filters.get(opportunity, filters['all'])['domain']
        order = sortings.get(sortby, sortings['date'])['order']

        # archive groups - Default Group By 'create_date'
        archive_groups = self._get_archive_groups('crm.lead', domain)
        if date_begin and date_end:
            domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
        # pager
        opp_count = CrmLead.search_count(domain)
        pager = request.website.pager(
            url="/my/opportunities",
            url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'opportunity': opportunity},
            total=opp_count,
            page=page,
            step=self._items_per_page
        )
        # content according to pager and archive selected
        opportunities = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])

        values.update({
            'date': date_begin,
            'opportunities': opportunities,
            'page_name': 'opportunity',
            'filters': OrderedDict(sorted(filters.items())),
            'opportunity': opportunity,
            'sortings': sortings,
            'sortby': sortby,
            'archive_groups': archive_groups,
            'default_url': '/my/opportunities',
            'pager': pager
        })
        return request.website.render("website_crm_partner_assign.portal_my_opportunities", values)

    @http.route(['/my/lead/<model("crm.lead"):lead>'], type='http', auth="user", website=True)
    def portal_my_lead(self, lead=None, **kw):
        return request.website.render("website_crm_partner_assign.portal_my_lead", {'lead': lead})

    @http.route(['/my/opportunity/<model("crm.lead"):lead>'], type='http', auth="user", website=True)
    def portal_my_opportunity(self, lead=None, **kw):
        return request.website.render(
            "website_crm_partner_assign.portal_my_opportunity", {
                'opportunity': lead,
                'stages': request.env['crm.stage'].search([('probability', '!=', '100')], order='sequence desc'),
                'activities': request.env['crm.activity'].sudo().search([], order='sequence desc'),
                'states': request.env['res.country.state'].sudo().search([]),
                'countries': request.env['res.country'].sudo().search([]),
            })


class WebsiteCrmPartnerAssign(WebsitePartnerPage):
    _references_per_page = 40

    @http.route([
        '/partners',
        '/partners/page/<int:page>',

        '/partners/grade/<model("res.partner.grade"):grade>',
        '/partners/grade/<model("res.partner.grade"):grade>/page/<int:page>',

        '/partners/country/<model("res.country"):country>',
        '/partners/country/<model("res.country"):country>/page/<int:page>',

        '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>',
        '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>/page/<int:page>',
    ], type='http', auth="public", website=True)
    def partners(self, country=None, grade=None, page=0, **post):
        country_all = post.pop('country_all', False)
        partner_obj = request.env['res.partner']
        country_obj = request.env['res.country']
        search = post.get('search', '')

        base_partner_domain = [('is_company', '=', True), ('grade_id', '!=', False), ('website_published', '=', True)]
        if not request.env['res.users'].has_group('base.group_website_publisher'):
            base_partner_domain += [('grade_id.website_published', '=', True)]
        if search:
            base_partner_domain += ['|', ('name', 'ilike', search), ('website_description', 'ilike', search)]

        # group by grade
        grade_domain = list(base_partner_domain)
        if not country and not country_all:
            country_code = request.session['geoip'].get('country_code')
            if country_code:
                country_ids = country_obj.search([('code', '=', country_code)])
                if country_ids:
                    country = country_obj.browse(country_ids[0])
        if country:
            grade_domain += [('country_id', '=', country.id)]
        grades = partner_obj.sudo().read_group(
            grade_domain, ["id", "grade_id"],
            groupby="grade_id", orderby="grade_id DESC")
        grades_partners = partner_obj.sudo().search_count(grade_domain)
        # flag active grade
        for grade_dict in grades:
            grade_dict['active'] = grade and grade_dict['grade_id'][0] == grade.id
        grades.insert(0, {
            'grade_id_count': grades_partners,<commit_msg>[FIX] website_crm_partner_assign: do not browse a recordset<commit_after># -*- coding: utf-8 -*-
import datetime
import werkzeug

from collections import OrderedDict

from odoo import fields
from odoo.addons.web import http
from odoo.addons.web.http import request
from odoo.addons.website.models.website import slug, unslug
from odoo.addons.website_partner.controllers.main import WebsitePartnerPage
from odoo.tools.translate import _

from odoo.addons.website_portal.controllers.main import website_account


class WebsiteAccount(website_account):

    @http.route()
    def account(self):
        response = super(WebsiteAccount, self).account()
        lead_count = request.env['crm.lead'].search_count([
            ('partner_assigned_id', '=', request.env.user.partner_id.id),
            ('type', '=', 'lead')
        ])
        opp_count = request.env['crm.lead'].search_count([
            ('partner_assigned_id', '=', request.env.user.partner_id.id),
            ('type', '=', 'opportunity')
        ])
        response.qcontext.update({'lead_count': lead_count, 'opp_count': opp_count})
        return response

    @http.route(['/my/leads', '/my/leads/page/<int:page>'], type='http', auth="user", website=True)
    def portal_my_leads(self, page=1, date_begin=None, date_end=None, lead=None, sortby=None, **kw):
        values = self._prepare_portal_layout_values()
        CrmLead = request.env['crm.lead']
        domain = [('partner_assigned_id', '=', request.env.user.partner_id.id), ('type', '=', 'lead')]

        sortings = {
            'date': {'label': _('Newest'), 'order': 'create_date desc'},
            'name': {'label': _('Name'), 'order': 'name'},
            'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'},
        }

        order = sortings.get(sortby, sortings['date'])['order']

        # archive groups - Default Group By 'create_date'
        archive_groups = self._get_archive_groups('crm.lead', domain)
        if date_begin and date_end:
            domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
        # pager
        lead_count = CrmLead.search_count(domain)
        pager = request.website.pager(
            url="/my/leads",
            url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'lead': lead},
            total=lead_count,
            page=page,
            step=self._items_per_page
        )
        # content according to pager and archive selected
        leads = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])

        values.update({
            'date': date_begin,
            'leads': leads,
            'page_name': 'lead',
            'lead': lead,
            'sortings': sortings,
            'sortby': sortby,
            'archive_groups': archive_groups,
            'default_url': '/my/leads',
            'pager': pager
        })
        return request.website.render("website_crm_partner_assign.portal_my_leads", values)

    @http.route(['/my/opportunities', '/my/opportunities/page/<int:page>'], type='http', auth="user", website=True)
    def portal_my_opportunities(self, page=1, date_begin=None, date_end=None, opportunity=None, sortby=None, **kw):
        values = self._prepare_portal_layout_values()
        CrmLead = request.env['crm.lead']
        domain = [('partner_assigned_id', '=', request.env.user.partner_id.id), ('type', '=', 'opportunity')]

        today = fields.Date.today()
        this_week_end_date = fields.Date.to_string(fields.Date.from_string(today) + datetime.timedelta(days=7))

        filters = {
            'all': {'label': _('All'), 'domain': []},
            'today': {'label': _('Today Activities'), 'domain': [('date_action', '=', today)]},
            'week': {'label': _('This Week Activities'),
                     'domain': [('date_action', '>=', today), ('date_action', '<=', this_week_end_date)]},
            'overdue': {'label': _('Overdue Activities'), 'domain': [('date_action', '<', today)]},
            'won': {'label': _('Won'), 'domain': [('stage_id.probability', '=', 100), ('stage_id.fold', '=', True)]},
            'lost': {'label': _('Lost'), 'domain': [('active', '=', False)]},
        }

        sortings = {
            'date': {'label': _('Newest'), 'order': 'create_date desc'},
            'name': {'label': _('Name'), 'order': 'name'},
            'contact_name': {'label': _('Contact Name'), 'order': 'contact_name'},
            'revenue': {'label': _('Expected Revenue'), 'order': 'planned_revenue desc'},
            'probability': {'label': _('Probability'), 'order': 'probability desc'},
            'stage': {'label': _('Stage'), 'order': 'stage_id'},
        }

        domain += filters.get(opportunity, filters['all'])['domain']
        order = sortings.get(sortby, sortings['date'])['order']

        # archive groups - Default Group By 'create_date'
        archive_groups = self._get_archive_groups('crm.lead', domain)
        if date_begin and date_end:
            domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)]
        # pager
        opp_count = CrmLead.search_count(domain)
        pager = request.website.pager(
            url="/my/opportunities",
            url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby, 'opportunity': opportunity},
            total=opp_count,
            page=page,
            step=self._items_per_page
        )
        # content according to pager and archive selected
        opportunities = CrmLead.search(domain, order=order, limit=self._items_per_page, offset=pager['offset'])

        values.update({
            'date': date_begin,
            'opportunities': opportunities,
            'page_name': 'opportunity',
            'filters': OrderedDict(sorted(filters.items())),
            'opportunity': opportunity,
            'sortings': sortings,
            'sortby': sortby,
            'archive_groups': archive_groups,
            'default_url': '/my/opportunities',
            'pager': pager
        })
        return request.website.render("website_crm_partner_assign.portal_my_opportunities", values)

    @http.route(['/my/lead/<model("crm.lead"):lead>'], type='http', auth="user", website=True)
    def portal_my_lead(self, lead=None, **kw):
        return request.website.render("website_crm_partner_assign.portal_my_lead", {'lead': lead})

    @http.route(['/my/opportunity/<model("crm.lead"):lead>'], type='http', auth="user", website=True)
    def portal_my_opportunity(self, lead=None, **kw):
        return request.website.render(
            "website_crm_partner_assign.portal_my_opportunity", {
                'opportunity': lead,
                'stages': request.env['crm.stage'].search([('probability', '!=', '100')], order='sequence desc'),
                'activities': request.env['crm.activity'].sudo().search([], order='sequence desc'),
                'states': request.env['res.country.state'].sudo().search([]),
                'countries': request.env['res.country'].sudo().search([]),
            })


class WebsiteCrmPartnerAssign(WebsitePartnerPage):
    _references_per_page = 40

    @http.route([
        '/partners',
        '/partners/page/<int:page>',

        '/partners/grade/<model("res.partner.grade"):grade>',
        '/partners/grade/<model("res.partner.grade"):grade>/page/<int:page>',

        '/partners/country/<model("res.country"):country>',
        '/partners/country/<model("res.country"):country>/page/<int:page>',

        '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>',
        '/partners/grade/<model("res.partner.grade"):grade>/country/<model("res.country"):country>/page/<int:page>',
    ], type='http', auth="public", website=True)
    def partners(self, country=None, grade=None, page=0, **post):
        country_all = post.pop('country_all', False)
        partner_obj = request.env['res.partner']
        country_obj = request.env['res.country']
        search = post.get('search', '')

        base_partner_domain = [('is_company', '=', True), ('grade_id', '!=', False), ('website_published', '=', True)]
        if not request.env['res.users'].has_group('base.group_website_publisher'):
            base_partner_domain += [('grade_id.website_published', '=', True)]
        if search:
            base_partner_domain += ['|', ('name', 'ilike', search), ('website_description', 'ilike', search)]

        # group by grade
        grade_domain = list(base_partner_domain)
        if not country and not country_all:
            country_code = request.session['geoip'].get('country_code')
            if country_code:
                country = country_obj.search([('code', '=', country_code)], limit=1)
        if country:
            grade_domain += [('country_id', '=', country.id)]
        grades = partner_obj.sudo().read_group(
            grade_domain, ["id", "grade_id"],
            groupby="grade_id", orderby="grade_id DESC")
        grades_partners = partner_obj.sudo().search_count(grade_domain)
        # flag active grade
        for grade_dict in grades:
            grade_dict['active'] = grade and grade_dict['grade_id'][0] == grade.id
        grades.insert(0, {
            'grade_id_count': grades_partners,
{'fraction_non_alphanumeric': 0.17325618772099002, 'fraction_numerical': 0.0017143469409621772, 'mean_word_length': 2.9465116279069767, 'pattern_counts': {'":': 0, '<': 43, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '8822', 'n_tokens_mistral': 5853, 'n_tokens_neox': 5710, 'n_words': 1008}