<commit_before># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
import logging
_logger = logging.getLogger(__name__)


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

    # TODO this field should be move to PRC (product_replenishment_cost)
    replenishment_cost_last_update = fields.Datetime(
        'Replenishment Cost Last Update',
        track_visibility='onchange',
    )
    # TODO this field should be move to PRC (product_replenishment_cost)
    replenishment_base_cost = fields.Float(
        'Replenishment Base Cost',
        digits=dp.get_precision('Product Price'),
        track_visibility='onchange',
        help="Replanishment Cost expressed in 'Replenishment Base Cost "
        "Currency'."
    )
    replenishment_base_cost_currency_id = fields.Many2one(
        'res.currency',
        'Replenishment Base Cost Currency',
        auto_join=True,
        track_visibility='onchange',
        help="Currency used for the Replanishment Base Cost."
    )
    # TODO borrar, ya lo cambiamos en nustro modulo base de rep cost
    # lo que si dejamos es sobreescribir el metodo de computar, algo que
    # deberiamos mejorar tmb
    replenishment_cost = fields.Float(
        compute='_get_replenishment_cost',
    )
    # for now we make replenshiment cost field only on template and not in
    # product (this should be done in PRC)
    #     string='Replenishment Cost',
    #     store=False,
    #     digits=dp.get_precision('Product Price'),
    #     help="The cost that you have to support in order to produce or "
    #          "acquire the goods. Depending on the modules installed, "
    #          "this cost may be computed based on various pieces of "
    #          "information, for example Bills of Materials or latest "
    #          "Purchases."

    @api.model
    def cron_update_cost_from_replenishment_cost(self):
        # como es property no podemos hacer el search
        _logger.info('Running cron update cost from replenishment')
        domain = [
            ('replenishment_base_cost', '!=', False),
            ('replenishment_base_cost_currency_id', '!=', False),
        ]
        # el prefetch nos dio una mejora de 57 contra 46 segs para 1500 prods
        return self.with_context({'prefetch_fields': False}).search(
            domain)._update_cost_from_replenishment_cost()

    @api.multi
    def _update_cost_from_replenishment_cost(self):
        _logger.info(
            'Running update cost from replenishment for %s products' % (
                len(self.ids)))
        for rec in self:
            # TODO ver si lo storearon o mejoraron para poder incluirlo
            # no hacemos mas la comparación porque tira la performance muy
            # abajo porque es campo calculado que a su vez usa properties
            # if rec.cost_method != 'standard' or not rec.replenishment_cost:
            if not rec.replenishment_cost:
                continue
            rec.standard_price = rec.replenishment_cost
        return True

    @api.multi
    @api.constrains(
        'replenishment_base_cost',
        'replenishment_base_cost_currency_id',
    )
    def update_replenishment_cost_last_update(self):
        self.write({'replenishment_cost_last_update': fields.Datetime.now()})<commit_msg>IMP cost update performance<commit_after># -*- coding: utf-8 -*-
##############################################################################
# For copyright and license notices, see __openerp__.py file in module root
# directory
##############################################################################
from openerp import models, fields, api
import openerp.addons.decimal_precision as dp
import logging
_logger = logging.getLogger(__name__)


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

    # TODO this field should be move to PRC (product_replenishment_cost)
    replenishment_cost_last_update = fields.Datetime(
        'Replenishment Cost Last Update',
        track_visibility='onchange',
    )
    # TODO this field should be move to PRC (product_replenishment_cost)
    replenishment_base_cost = fields.Float(
        'Replenishment Base Cost',
        digits=dp.get_precision('Product Price'),
        track_visibility='onchange',
        help="Replanishment Cost expressed in 'Replenishment Base Cost "
        "Currency'."
    )
    replenishment_base_cost_currency_id = fields.Many2one(
        'res.currency',
        'Replenishment Base Cost Currency',
        auto_join=True,
        track_visibility='onchange',
        help="Currency used for the Replanishment Base Cost."
    )
    # TODO borrar, ya lo cambiamos en nustro modulo base de rep cost
    # lo que si dejamos es sobreescribir el metodo de computar, algo que
    # deberiamos mejorar tmb
    replenishment_cost = fields.Float(
        compute='_get_replenishment_cost',
    )
    # for now we make replenshiment cost field only on template and not in
    # product (this should be done in PRC)
    #     string='Replenishment Cost',
    #     store=False,
    #     digits=dp.get_precision('Product Price'),
    #     help="The cost that you have to support in order to produce or "
    #          "acquire the goods. Depending on the modules installed, "
    #          "this cost may be computed based on various pieces of "
    #          "information, for example Bills of Materials or latest "
    #          "Purchases."

    @api.model
    def cron_update_cost_from_replenishment_cost(self, limit=None):
        _logger.info('Running cron update cost from replenishment')
        return self._update_cost_from_replenishment_cost()

    @api.multi
    def _update_cost_from_replenishment_cost(self):
        """
        If we came from tree list, we update only in selected list
        """
        # hacemos search de nuevo por si se llama desde vista lista
        domain = [
            ('replenishment_base_cost', '!=', False),
            ('replenishment_base_cost_currency_id', '!=', False),
        ]
        if self:
            domain.append(('id', 'in', self.ids))

        batch_size = 1000
        product_ids = self.search(domain).ids
        sliced_product_ids = [
            product_ids[i:i + batch_size] for i in range(
                0, len(product_ids), batch_size)]
        cr = self.env.cr
        run = 0
        for product_ids in sliced_product_ids:
            run += 1
            # hacemos invalidate cache para que no haga prefetch de todos,
            # solo los del slice
            self.invalidate_cache()
            recs = self.browse(product_ids)
            _logger.info(
                'Running update update cost for %s products. Run %s of %s' % (
                    len(recs), run, len(sliced_product_ids)))
            for rec in recs:
                replenishment_cost = rec.replenishment_cost
                # TODO we should check if standar_price type is standar and
                # not by quants or similar, we remove that because it makes
                # it slower
                if not replenishment_cost:
                    continue
                rec.standard_price = replenishment_cost
                # we can not use sql because standar_price is a property,
                # perhups we can do it writing directly on the property but
                # we need to check if record exists, we can copy some code of
                # def set_multi
                # tal vez mejor que meter mano en esto hacer que solo se
                # actualicen los que se tienen que actualizar
                # seguramente en la v10 se mejoro el metodo de set de property
                # tmb
                # cr.execute(
                #     "UPDATE product_template SET standard_price=%s WHERE "
                #     "id=%s", (replenishment_cost, rec.id))

            # commit update (fo free memory?) also to have results stored
            # in the future, if we store the date, we can update only newones
            cr.commit()
            _logger.info('Finish updating cost of run %s' % run)

        return True

    @api.multi
    @api.constrains(
        'replenishment_base_cost',
        'replenishment_base_cost_currency_id',
    )
    def update_replenishment_cost_last_update(self):
        self.write({'replenishment_cost_last_update': fields.Datetime.now()})
{'fraction_non_alphanumeric': 0.10701064322073114, 'fraction_numerical': 0.0024294308190652477, 'mean_word_length': 2.501417577966788, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '6986019', 'n_tokens_mistral': 2437, 'n_tokens_neox': 2346, 'n_words': 737}