<commit_before># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2015 Comunitea Servicios Tecnológicos All Rights Reserved
#    $<NAME> <<EMAIL>>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models, fields, api, exceptions, osv, _
from openerp.addons.account_followup.report import account_followup_print
from openerp.osv import fields as fields2
from collections import defaultdict
import time
from datetime import date
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
import datetime
import dateutil.relativedelta

class ResPartnerInvoiceType(models.Model):
    _name = 'res.partner.invoice.type'

    name = fields.Char('Name', required=True)


class ResPartner(models.Model):
    _inherit = "res.partner"

    def _invoice_total_real(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        if context is None:
            context = {}
        account_invoice_report = self.pool.get('account.invoice.report')
        user = self.pool['res.users'].browse(cr, uid, uid, context=context)
        user_currency_id = user.company_id.currency_id.id
        for partner_id in ids:
            all_partner_ids = self.pool['res.partner'].search(
                cr, uid, [('id', 'child_of', partner_id)], context=context)

            # searching account.invoice.report via the orm is comparatively expensive
            # (generates queries "id in []" forcing to build the full table).
            # In simple cases where all invoices are in the same currency than the user's company
            # access directly these elements
            domain = [('partner_id', 'in', all_partner_ids),
                      ('state', 'not in', ['draft', 'cancel']),
                      ('number', 'not like', '%_ef%')]
            if context.get('date_from', False):
                domain.append(('date', '>=', context['date_from']))
            # generate where clause to include multicompany rules
            where_query = account_invoice_report._where_calc(cr, uid, domain,
                                                             context=context)
            account_invoice_report._apply_ir_rules(cr, uid, where_query, 'read', context=context)
            from_clause, where_clause, where_clause_params = where_query.get_sql()

            query = """ WITH currency_rate (currency_id, rate, date_start, date_end) AS (
                                SELECT r.currency_id, r.rate, r.name AS date_start,
                                    (SELECT name FROM res_currency_rate r2
                                     WHERE r2.name > r.name AND
                                           r2.currency_id = r.currency_id
                                     ORDER BY r2.name ASC
                                     LIMIT 1) AS date_end
                                FROM res_currency_rate r
                                )
                      SELECT SUM(price_total * cr.rate) as total
                        FROM account_invoice_report account_invoice_report, currency_rate cr
                       WHERE %s
                         AND cr.currency_id = %%s
                         AND (COALESCE(account_invoice_report.date, NOW()) >= cr.date_start)
                         AND (COALESCE(account_invoice_report.date, NOW()) < cr.date_end OR cr.date_end IS NULL)
                    """ % where_clause

            # price_total is in the currency with rate = 1
            # total_invoice should be displayed in the current user's currency
            cr.execute(query, where_clause_params + [user_currency_id])
            result[partner_id] = cr.fetchone()[0]

        return result

    _columns = {
        'total_invoiced_real': fields2.function(_invoice_total_real, string="Total Invoiced", type='float',
                                         groups='account.group_account_invoice')
    }


    @api.one
    def _get_products_sold(self):
        lines = self.env["sale.order.line"].read_group([('order_partner_id',
                                                         '=', self.id)],
                                                       ['product_id'],
                                                       groupby="product_id")
        self.sale_product_count = len(lines)

    @api.one
    def _sale_order_count(self):
        self.sale_order_count = len(self.env["sale.order"].
                                    search([('partner_id', 'child_of',
                                             [self.id]),
                                            ('state', 'not in',
                                             ['draft', 'cancel', 'sent'])]))

    @api.one
    def _get_growth_rate(self):
        if self.customer:
            search_date_180 = (date.today() - relativedelta(days=180)).\
                strftime("%Y-%m-%d")
            invoiced_180 = self.with_context(date_from=search_date_180).\
                browse(self.id).total_invoiced_real
            diary_invoice = invoiced_180 / 180.0
            goal = diary_invoice * 15.0
            if goal:
                search_date_15 = (date.today() - relativedelta(days=15)).\
                    strftime("%Y-%m-%d")
                invoiced_15 = self.with_context(date_from=search_date_15).\
                    browse(self.id).total_invoiced_real
                self.growth_rate = invoiced_15 / goal

    @api.one
    def _get_average_margin(self):
        if self.customer:
            margin_avg = 0.0

            d1 = datetime.datetime.strptime(datetime.datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
            final_date = d1.strftime("%Y-%m-%d")
            d2 = d1 - dateutil.relativedelta.relativedelta(months=3)
            start_date = d2.strftime("%Y-%m-%d")

            invoices = self.env['account.invoice'].search(
                [('partner_id', '=', self.id),
                 ('state', 'in', ['paid', 'history']),
                 ('date_invoice', '>=', start_date),
                 ('date_invoice', '<=', final_date)])<commit_msg>[FIX] custom_partner: Corrección de una doble importación<commit_after># -*- coding: utf-8 -*-
##############################################################################
#
#    Copyright (C) 2015 Comunitea Servicios Tecnológicos All Rights Reserved
#    $<NAME> <<EMAIL>>$
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from openerp import models, fields, api, exceptions, osv, _
from openerp.addons.account_followup.report import account_followup_print
from openerp.osv import fields as fields2
from collections import defaultdict
import time
from datetime import date
from dateutil.relativedelta import relativedelta
from datetime import datetime, timedelta
import dateutil.relativedelta

class ResPartnerInvoiceType(models.Model):
    _name = 'res.partner.invoice.type'

    name = fields.Char('Name', required=True)


class ResPartner(models.Model):
    _inherit = "res.partner"

    def _invoice_total_real(self, cr, uid, ids, field_name, arg, context=None):
        result = {}
        if context is None:
            context = {}
        account_invoice_report = self.pool.get('account.invoice.report')
        user = self.pool['res.users'].browse(cr, uid, uid, context=context)
        user_currency_id = user.company_id.currency_id.id
        for partner_id in ids:
            all_partner_ids = self.pool['res.partner'].search(
                cr, uid, [('id', 'child_of', partner_id)], context=context)

            # searching account.invoice.report via the orm is comparatively expensive
            # (generates queries "id in []" forcing to build the full table).
            # In simple cases where all invoices are in the same currency than the user's company
            # access directly these elements
            domain = [('partner_id', 'in', all_partner_ids),
                      ('state', 'not in', ['draft', 'cancel']),
                      ('number', 'not like', '%_ef%')]
            if context.get('date_from', False):
                domain.append(('date', '>=', context['date_from']))
            # generate where clause to include multicompany rules
            where_query = account_invoice_report._where_calc(cr, uid, domain,
                                                             context=context)
            account_invoice_report._apply_ir_rules(cr, uid, where_query, 'read', context=context)
            from_clause, where_clause, where_clause_params = where_query.get_sql()

            query = """ WITH currency_rate (currency_id, rate, date_start, date_end) AS (
                                SELECT r.currency_id, r.rate, r.name AS date_start,
                                    (SELECT name FROM res_currency_rate r2
                                     WHERE r2.name > r.name AND
                                           r2.currency_id = r.currency_id
                                     ORDER BY r2.name ASC
                                     LIMIT 1) AS date_end
                                FROM res_currency_rate r
                                )
                      SELECT SUM(price_total * cr.rate) as total
                        FROM account_invoice_report account_invoice_report, currency_rate cr
                       WHERE %s
                         AND cr.currency_id = %%s
                         AND (COALESCE(account_invoice_report.date, NOW()) >= cr.date_start)
                         AND (COALESCE(account_invoice_report.date, NOW()) < cr.date_end OR cr.date_end IS NULL)
                    """ % where_clause

            # price_total is in the currency with rate = 1
            # total_invoice should be displayed in the current user's currency
            cr.execute(query, where_clause_params + [user_currency_id])
            result[partner_id] = cr.fetchone()[0]

        return result

    _columns = {
        'total_invoiced_real': fields2.function(_invoice_total_real, string="Total Invoiced", type='float',
                                         groups='account.group_account_invoice')
    }


    @api.one
    def _get_products_sold(self):
        lines = self.env["sale.order.line"].read_group([('order_partner_id',
                                                         '=', self.id)],
                                                       ['product_id'],
                                                       groupby="product_id")
        self.sale_product_count = len(lines)

    @api.one
    def _sale_order_count(self):
        self.sale_order_count = len(self.env["sale.order"].
                                    search([('partner_id', 'child_of',
                                             [self.id]),
                                            ('state', 'not in',
                                             ['draft', 'cancel', 'sent'])]))

    @api.one
    def _get_growth_rate(self):
        if self.customer:
            search_date_180 = (date.today() - relativedelta(days=180)).\
                strftime("%Y-%m-%d")
            invoiced_180 = self.with_context(date_from=search_date_180).\
                browse(self.id).total_invoiced_real
            diary_invoice = invoiced_180 / 180.0
            goal = diary_invoice * 15.0
            if goal:
                search_date_15 = (date.today() - relativedelta(days=15)).\
                    strftime("%Y-%m-%d")
                invoiced_15 = self.with_context(date_from=search_date_15).\
                    browse(self.id).total_invoiced_real
                self.growth_rate = invoiced_15 / goal

    @api.one
    def _get_average_margin(self):
        if self.customer:
            margin_avg = 0.0

            d1 = datetime.strptime(datetime.now().strftime("%Y-%m-%d"), "%Y-%m-%d")
            final_date = d1.strftime("%Y-%m-%d")
            d2 = d1 - dateutil.relativedelta.relativedelta(months=3)
            start_date = d2.strftime("%Y-%m-%d")

            invoices = self.env['account.invoice'].search(
                [('partner_id', '=', self.id),
                 ('state', 'in', ['paid', 'history']),
                 ('date_invoice', '>=', start_date),
                 ('date_invoice', '<=', final_date)])
{'fraction_non_alphanumeric': 0.12128531693749085, 'fraction_numerical': 0.008051529790660225, 'mean_word_length': 1.8613612565445026, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 46, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7576230', 'n_tokens_mistral': 3774, 'n_tokens_neox': 3542, 'n_words': 917}