<commit_before># -*- coding: utf-8 -*-
# © 2016 Comunitea - <NAME> <<EMAIL>>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models, api, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError
from odoo.addons.stock.models.product import OPERATORS


class ProductTemplate(models.Model):
    _inherit = "product.template"

    def _search_global_real_stock(self, operator, value):
        domain = [('global_real_stock', operator, value)]
        product_variant_ids = self.env['product.product'].search(domain)
        return [('product_variant_ids', 'in', product_variant_ids.ids)]

    def _search_global_avail_stock(self, operator, value):
        domain = [('global_available_stock', operator, value)]
        product_variant_ids = self.env['product.product'].search(domain)
        return [('product_variant_ids', 'in', product_variant_ids.ids)]

    global_real_stock = fields.Float('Global Real Stock',
                                     compute='_compute_global_stock',
                                     digits=dp.get_precision
                                     ('Product Unit of Measure'),
                                     help="Real stock in all companies.",
                                     search='_search_global_real_stock')
    global_available_stock = fields.Float('Global Available Stock',
                                          compute='_compute_global_stock',
                                          digits=dp.get_precision
                                          ('Product Unit of Measure'),
                                          help="Real stock minus outgoing "
                                          " in all companies.",
                                          search='_search_global_avail_stock')

    @api.multi
    def _compute_global_stock(self):
        for template in self:
            global_real_stock = 0.0
            global_available_stock = 0.0
            for p in template.product_variant_ids:
                global_real_stock += p.global_real_stock
                global_available_stock += p.global_available_stock
            template.global_real_stock = global_real_stock
            template.global_available_stock = global_available_stock


class ProductProduct(models.Model):
    _inherit = "product.product"

    def _search_global_product_quantity(self, operator, value, field):
        if field not in ('global_available_stock', 'global_real_stock', 'web_global_stock'):
            raise UserError(_('Invalid domain left operand %s') % field)
        if operator not in ('<', '>', '=', '!=', '<=', '>='):
            raise UserError(_('Invalid domain operator %s') % operator)
        if not isinstance(value, (float, int)):
            raise UserError(_('Invalid domain right operand %s') % value)

        ids = []
        for product in self.search([]):
            if OPERATORS[operator](product[field], value):
                ids.append(product.id)
        return [('id', 'in', ids)]

    def _search_global_real_stock(self, operator, value):
        if value == 0.0 and operator in ('=', '>=', '<='):
            return self._search_global_product_quantity(operator, value,
                                                        'global_real_stock')

    def _search_global_avail_stock(self, operator, value):
        return self.\
            _search_global_product_quantity(operator, value,
                                            'global_available_stock')

    def _search_web_global_stock(self, operator, value):
        return self._search_global_product_quantity(operator, value,
                                                        'web_global_stock')

    global_real_stock = fields.Float('Global Real Stock',
                                     compute='_compute_global_stock',
                                     digits=dp.get_precision
                                     ('Product Unit of Measure'),
                                     help="Real stock in all companies.",
                                     search='_search_global_real_stock')
    global_available_stock = fields.Float('Global Available Stock',
                                          compute='_compute_global_stock',
                                          digits=dp.get_precision
                                          ('Product Unit of Measure'),
                                          help="Real stock minus outgoing "
                                          " in all companies.",
                                          search='_search_global_avail_stock')
    web_global_stock = fields.Float('Web stock', readonly=True,
                                    digits=dp.get_precision
                                    ('Product Unit of Measure'),
                                    compute="_compute_global_stock")

    @api.multi
    def _calculate_globals(self):
        not_deposit_ids = \
            self.env['stock.location'].sudo().search(
                [('deposit', '!=', True), ('usage', '=', 'internal')]).ids
        company_ids = \
            self.env['res.company'].sudo().search(
                [('no_stock', '=', True)]).ids
        self._cr.execute(
            "SELECT SOL.product_id, sum(SOL.product_uom_qty) as qty FROM "
            "sale_order_line SOL "
            "INNER JOIN sale_order  SO ON SO.id = SOL.order_id "
            "INNER JOIN stock_location_route SLR  ON SLR.id = SOL.route_id "
            "WHERE SOL.product_id in %s "
            "AND SO.state in ('lqdr', 'pending', 'progress_lqdr', 'progress',"
            " 'proforma') "
            "AND not SLR.no_stock AND SO.company_id NOT IN %s "
            "group BY SOL.product_id", [tuple(self.ids), tuple(company_ids)])
        sale_line_data = dict(self._cr.fetchall())

        ctx = self._context.copy()
        ctx.update({'location': not_deposit_ids})
        qty_available_d = dict(
            [(p['id'], p['qty_available'])
             for p in self.with_context(ctx).sudo().read(['qty_available'])])
        ctx.update({'no_move_ic': True})
        outgoing_qty_d = dict(
            [(p['id'], p['outgoing_qty'])
             for p in self.with_context(ctx).sudo().read(['outgoing_qty'])])
        global_real_stock = qty_available_d
        global_available_stock = dict(
            [(p, qty_available_d[p] - outgoing_qty_d[p])
             for p in qty_available_d.keys()])

        company_real_stock = dict([(x.id, 0) for x in self])
        company_available_stock = dict([(x.id, 0) for x in self])
        if company_ids:
            for company in company_ids:
                ctx = self._context.copy()
                ctx.update({'force_company': company})
                company_available = dict(
                    [(p['id'], p['qty_available']) for p in
                     self.with_context(ctx).sudo().read(['qty_available'])])
                company_outgoing = dict(
                    [(p['id'], p['outgoing_qty']) for p in
                     self.with_context(ctx).sudo().read(['outgoing_qty'])])

                company_real_stock = {
                    k: company_real_stock.get(k, 0) +
                    company_available.get(k, 0)
                    for k in set(company_real_stock) | set(company_available)}

                company_available_stock_ = dict(
                    [(p, company_available[p] - company_outgoing[p])
                     for p in company_available.keys()])
                company_available_stock = {
                    k: company_available_stock.get(k, 0) +
                    company_available_stock_.get(k, 0)
                    for k in set(company_available_stock) |
                    set(company_available_stock_)}<commit_msg>[FIX]No se vuelve a crear la variable ctx para que al buscar el stock de cada compañía siga haciendolo en las ubicaciones indicadas.<commit_after># -*- coding: utf-8 -*-
# © 2016 Comunitea - <NAME> <<EMAIL>>
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models, api, _
from odoo.addons import decimal_precision as dp
from odoo.exceptions import UserError
from odoo.addons.stock.models.product import OPERATORS


class ProductTemplate(models.Model):
    _inherit = "product.template"

    def _search_global_real_stock(self, operator, value):
        domain = [('global_real_stock', operator, value)]
        product_variant_ids = self.env['product.product'].search(domain)
        return [('product_variant_ids', 'in', product_variant_ids.ids)]

    def _search_global_avail_stock(self, operator, value):
        domain = [('global_available_stock', operator, value)]
        product_variant_ids = self.env['product.product'].search(domain)
        return [('product_variant_ids', 'in', product_variant_ids.ids)]

    global_real_stock = fields.Float('Global Real Stock',
                                     compute='_compute_global_stock',
                                     digits=dp.get_precision
                                     ('Product Unit of Measure'),
                                     help="Real stock in all companies.",
                                     search='_search_global_real_stock')
    global_available_stock = fields.Float('Global Available Stock',
                                          compute='_compute_global_stock',
                                          digits=dp.get_precision
                                          ('Product Unit of Measure'),
                                          help="Real stock minus outgoing "
                                          " in all companies.",
                                          search='_search_global_avail_stock')

    @api.multi
    def _compute_global_stock(self):
        for template in self:
            global_real_stock = 0.0
            global_available_stock = 0.0
            for p in template.product_variant_ids:
                global_real_stock += p.global_real_stock
                global_available_stock += p.global_available_stock
            template.global_real_stock = global_real_stock
            template.global_available_stock = global_available_stock


class ProductProduct(models.Model):
    _inherit = "product.product"

    def _search_global_product_quantity(self, operator, value, field):
        if field not in ('global_available_stock', 'global_real_stock', 'web_global_stock'):
            raise UserError(_('Invalid domain left operand %s') % field)
        if operator not in ('<', '>', '=', '!=', '<=', '>='):
            raise UserError(_('Invalid domain operator %s') % operator)
        if not isinstance(value, (float, int)):
            raise UserError(_('Invalid domain right operand %s') % value)

        ids = []
        for product in self.search([]):
            if OPERATORS[operator](product[field], value):
                ids.append(product.id)
        return [('id', 'in', ids)]

    def _search_global_real_stock(self, operator, value):
        if value == 0.0 and operator in ('=', '>=', '<='):
            return self._search_global_product_quantity(operator, value,
                                                        'global_real_stock')

    def _search_global_avail_stock(self, operator, value):
        return self.\
            _search_global_product_quantity(operator, value,
                                            'global_available_stock')

    def _search_web_global_stock(self, operator, value):
        return self._search_global_product_quantity(operator, value,
                                                        'web_global_stock')

    global_real_stock = fields.Float('Global Real Stock',
                                     compute='_compute_global_stock',
                                     digits=dp.get_precision
                                     ('Product Unit of Measure'),
                                     help="Real stock in all companies.",
                                     search='_search_global_real_stock')
    global_available_stock = fields.Float('Global Available Stock',
                                          compute='_compute_global_stock',
                                          digits=dp.get_precision
                                          ('Product Unit of Measure'),
                                          help="Real stock minus outgoing "
                                          " in all companies.",
                                          search='_search_global_avail_stock')
    web_global_stock = fields.Float('Web stock', readonly=True,
                                    digits=dp.get_precision
                                    ('Product Unit of Measure'),
                                    compute="_compute_global_stock")

    @api.multi
    def _calculate_globals(self):
        not_deposit_ids = \
            self.env['stock.location'].sudo().search(
                [('deposit', '!=', True), ('usage', '=', 'internal')]).ids
        company_ids = \
            self.env['res.company'].sudo().search(
                [('no_stock', '=', True)]).ids
        self._cr.execute(
            "SELECT SOL.product_id, sum(SOL.product_uom_qty) as qty FROM "
            "sale_order_line SOL "
            "INNER JOIN sale_order  SO ON SO.id = SOL.order_id "
            "INNER JOIN stock_location_route SLR  ON SLR.id = SOL.route_id "
            "WHERE SOL.product_id in %s "
            "AND SO.state in ('lqdr', 'pending', 'progress_lqdr', 'progress',"
            " 'proforma') "
            "AND not SLR.no_stock AND SO.company_id NOT IN %s "
            "group BY SOL.product_id", [tuple(self.ids), tuple(company_ids)])
        sale_line_data = dict(self._cr.fetchall())

        ctx = self._context.copy()
        ctx.update({'location': not_deposit_ids})
        qty_available_d = dict(
            [(p['id'], p['qty_available'])
             for p in self.with_context(ctx).sudo().read(['qty_available'])])
        ctx.update({'no_move_ic': True})
        outgoing_qty_d = dict(
            [(p['id'], p['outgoing_qty'])
             for p in self.with_context(ctx).sudo().read(['outgoing_qty'])])
        global_real_stock = qty_available_d
        global_available_stock = dict(
            [(p, qty_available_d[p] - outgoing_qty_d[p])
             for p in qty_available_d.keys()])

        company_real_stock = dict([(x.id, 0) for x in self])
        company_available_stock = dict([(x.id, 0) for x in self])
        if company_ids:
            for company in company_ids:
                ctx.update({'force_company': company})
                company_available = dict(
                    [(p['id'], p['qty_available']) for p in
                     self.with_context(ctx).sudo().read(['qty_available'])])
                company_outgoing = dict(
                    [(p['id'], p['outgoing_qty']) for p in
                     self.with_context(ctx).sudo().read(['outgoing_qty'])])

                company_real_stock = {
                    k: company_real_stock.get(k, 0) +
                    company_available.get(k, 0)
                    for k in set(company_real_stock) | set(company_available)}

                company_available_stock_ = dict(
                    [(p, company_available[p] - company_outgoing[p])
                     for p in company_available.keys()])
                company_available_stock = {
                    k: company_available_stock.get(k, 0) +
                    company_available_stock_.get(k, 0)
                    for k in set(company_available_stock) |
                    set(company_available_stock_)}
{'fraction_non_alphanumeric': 0.1051554304720481, 'fraction_numerical': 0.002558526288857618, 'mean_word_length': 1.696154509398172, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 86, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4010086', 'n_tokens_mistral': 4163, 'n_tokens_neox': 3937, 'n_words': 861}