<commit_before># -*- coding: utf-8 -*-
# © 2016 Comunitea
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models, api, _


class ProcurementRule(models.Model):
    """ Pull rules """
    _inherit = 'procurement.rule'

    procure_method = fields.Selection(
        selection_add=[('company', 'According to Product Company')])
    ic_picking_type_id = fields.Many2one(
        'stock.picking.type', 'IC Picking Type ',
        required=False,
        help="Picking Type for Intercompany purchase, ...")

    @api.model
    def _get_action(self):
        res = super(ProcurementRule, self)._get_action()
        res.append(('intercompany_buy', _('Intercompany Buy')))
        res.append(('product_company', _('Intercompany Buy or Move According to Product Company')))
        return res


class ProcurementOrder(models.Model):
    _inherit = "procurement.order"

    move_dest_IC_id = fields.Many2one('stock.move', 'Destination Move IC',
                                      copy=False, index=True,
                                      help="Optional: next IC stock move when "
                                           "chaining them")
    purchase_line_IC = fields.Many2one('purchase.order.line',
                                       'Related purchase line', copy=False,
                                       index=True)


    @api.model
    def create(self, values):
        if self.env.context.get('user_company'):
            values.update({'company_id': self.env.context.get('user_company')})
        return super(ProcurementOrder, self).create(values)

    def _get_stock_move_values(self):
        vals = super(ProcurementOrder, self)._get_stock_move_values()
        if vals['procure_method'] == 'company':
            if self.env['product.product'].browse(vals['product_id']).\
                    company_id.id == vals['company_id']:
                vals['procure_method'] = 'make_to_stock'
            else:
                vals['procure_method'] = 'make_to_order'
        vals['move_dest_IC_id'] = self.move_dest_IC_id.id
        if self.purchase_line_IC:
            ml_IC = self.env['stock.move'].search([('purchase_line_id', '=',
                                            self.purchase_line_IC.id)])
            if ml_IC:
                if len(ml_IC) > 1:
                    for m in ml_IC:
                        res = self.env['stock.move'].search(
                            [('move_purchase_IC_id', '=', m.id)])
                        if not res:
                            def_ml_IC = m
                            break
                else:
                    def_ml_IC = ml_IC
                vals['move_purchase_IC_id'] = def_ml_IC.id
        return vals

    @api.multi
    def _check(self):
        if self.rule_id and self.rule_id.action == 'product_company':
            # Si depende de la compañia pero es de la misma compañia es
            # movimiento
            if self.company_id.id == self.product_id.company_id.id or \
                            self.company_id.no_ic or self.product_id.no_ic:

                # In case Phantom BoM splits only into procurements
                if not self.move_ids:
                    return True
                move_all_done_or_cancel = all(
                    move.state in ['done', 'cancel'] for move in self.move_ids)
                move_all_cancel = all(
                    move.state == 'cancel' for move in self.move_ids)
                if not move_all_done_or_cancel:
                    return False
                elif move_all_done_or_cancel and not move_all_cancel:
                    return True
                else:
                    self.message_post(body=_(
                        'All stock moves have been cancelled for this procurement.'))
                    # TDE FIXME: strange that a check method actually modified the procurement...
                    self.write({'state': 'cancel'})
                    return False
            else:
                #Lo comprueba como una compra...
                if self.purchase_line_id:
                    if not self.move_ids:
                        return False
                    return all(move.state == 'done' for move in self.move_ids)
        return super(ProcurementOrder, self)._check()


    @api.multi
    def _run(self):
        if self.rule_id and self.rule_id.action == 'product_company':
            if self.company_id.id == self.product_id.company_id.id or \
                            self.company_id.no_ic or self.product_id.no_ic:
                # get the product only with move
                if not self.rule_id.location_src_id:
                    self.message_post(body=_('No source location defined!'))
                    return False
                # create the move as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)
                move = self.env['stock.move'].sudo().create(self._get_stock_move_values())
                move.action_confirm()
                return True
            else:
                # if product belongs to another compamy generate intercompany_buy
                return self.make_intercompany_buy_po()

        if self.rule_id and self.rule_id.action == 'intercompany_buy' and \
                not self.company_id.no_ic:
            return self.po_or_ic_po()

        return super(ProcurementOrder, self)._run()

    @api.multi
    def po_or_ic_po(self):
        if self.company_id.id == self.product_id.company_id.id:
            return self.make_po()
        else:
            return self.make_intercompany_buy_po()

    @api.multi
    def make_intercompany_buy_po(self):
        """
        COPY OF MAKE PO except buy:
        * Partner id from prodcut company
        * Price for intercomany_price of product.product
        These changes are commented, the other is the original code
        """
        cache = {}
        res = []

        for procurement in self:
            if not procurement.product_id.company_id:
                procurement.message_post(body=_('No company to product %s. \
                    Please set one to fix this procurement.')
                                         % (procurement.product_id.name))
                continue

            # CHANGED, GET PARTNER FROM PRODUCT COMPANY
            partner = procurement.product_id.company_id.partner_id

            gpo = procurement.rule_id.group_propagation_option
            group = (gpo == 'fixed' and procurement.rule_id.group_id) or \
                    (gpo == 'propagate' and procurement.group_id) or False

            domain = (
                ('partner_id', '=', partner.id),<commit_msg>[FIX] jim_inetercompany. Problema acceso compañía<commit_after># -*- coding: utf-8 -*-
# © 2016 Comunitea
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html
from odoo import fields, models, api, _


class ProcurementRule(models.Model):
    """ Pull rules """
    _inherit = 'procurement.rule'

    procure_method = fields.Selection(
        selection_add=[('company', 'According to Product Company')])
    ic_picking_type_id = fields.Many2one(
        'stock.picking.type', 'IC Picking Type ',
        required=False,
        help="Picking Type for Intercompany purchase, ...")

    @api.model
    def _get_action(self):
        res = super(ProcurementRule, self)._get_action()
        res.append(('intercompany_buy', _('Intercompany Buy')))
        res.append(('product_company', _('Intercompany Buy or Move According to Product Company')))
        return res


class ProcurementOrder(models.Model):
    _inherit = "procurement.order"

    move_dest_IC_id = fields.Many2one('stock.move', 'Destination Move IC',
                                      copy=False, index=True,
                                      help="Optional: next IC stock move when "
                                           "chaining them")
    purchase_line_IC = fields.Many2one('purchase.order.line',
                                       'Related purchase line', copy=False,
                                       index=True)


    @api.model
    def create(self, values):
        if self.env.context.get('user_company'):
            values.update({'company_id': self.env.context.get('user_company')})
        return super(ProcurementOrder, self).create(values)

    def _get_stock_move_values(self):
        vals = super(ProcurementOrder, self)._get_stock_move_values()
        if vals['procure_method'] == 'company':
            if self.env['product.product'].browse(vals['product_id']).\
                    company_id.id == vals['company_id']:
                vals['procure_method'] = 'make_to_stock'
            else:
                vals['procure_method'] = 'make_to_order'
        vals['move_dest_IC_id'] = self.move_dest_IC_id.id
        if self.purchase_line_IC:
            ml_IC = self.env['stock.move'].search([('purchase_line_id', '=',
                                            self.purchase_line_IC.id)])
            if ml_IC:
                if len(ml_IC) > 1:
                    for m in ml_IC:
                        res = self.env['stock.move'].search(
                            [('move_purchase_IC_id', '=', m.id)])
                        if not res:
                            def_ml_IC = m
                            break
                else:
                    def_ml_IC = ml_IC
                vals['move_purchase_IC_id'] = def_ml_IC.id
        return vals

    @api.multi
    def _check(self):
        if self.rule_id and self.rule_id.action == 'product_company':
            # Si depende de la compañia pero es de la misma compañia es
            # movimiento
            if self.company_id.id == self.product_id.company_id.id or \
                            self.company_id.no_ic or self.product_id.no_ic:

                # In case Phantom BoM splits only into procurements
                if not self.move_ids:
                    return True
                move_all_done_or_cancel = all(
                    move.state in ['done', 'cancel'] for move in self.move_ids)
                move_all_cancel = all(
                    move.state == 'cancel' for move in self.move_ids)
                if not move_all_done_or_cancel:
                    return False
                elif move_all_done_or_cancel and not move_all_cancel:
                    return True
                else:
                    self.message_post(body=_(
                        'All stock moves have been cancelled for this procurement.'))
                    # TDE FIXME: strange that a check method actually modified the procurement...
                    self.write({'state': 'cancel'})
                    return False
            else:
                #Lo comprueba como una compra...
                if self.purchase_line_id:
                    if not self.move_ids:
                        return False
                    return all(move.state == 'done' for move in self.move_ids)
        return super(ProcurementOrder, self)._check()


    @api.multi
    def _run(self):
        if self.rule_id and self.rule_id.action == 'product_company':
            if self.company_id.id == self.product_id.company_id.id or \
                            self.company_id.no_ic or self.product_id.no_ic:
                # get the product only with move
                if not self.rule_id.location_src_id:
                    self.message_post(body=_('No source location defined!'))
                    return False
                # create the move as SUPERUSER because the current user may not have the rights to do it (mto product launched by a sale for example)
                move = self.env['stock.move'].sudo().create(self._get_stock_move_values())
                move.action_confirm()
                return True
            else:
                # if product belongs to another compamy generate intercompany_buy
                return self.make_intercompany_buy_po()

        if self.rule_id and self.rule_id.action == 'intercompany_buy' and \
                not self.company_id.no_ic:
            return self.po_or_ic_po()

        return super(ProcurementOrder, self)._run()

    @api.multi
    def po_or_ic_po(self):
        if self.company_id.id == self.product_id.company_id.id:
            return self.make_po()
        else:
            return self.make_intercompany_buy_po()

    @api.multi
    def make_intercompany_buy_po(self):
        """
        COPY OF MAKE PO except buy:
        * Partner id from prodcut company
        * Price for intercomany_price of product.product
        These changes are commented, the other is the original code
        """
        cache = {}
        res = []

        for procurement in self:
            if not procurement.product_id.company_id:
                procurement.message_post(body=_('No company to product %s. \
                    Please set one to fix this procurement.')
                                         % (procurement.product_id.name))
                continue

            # CHANGED, GET PARTNER FROM PRODUCT COMPANY
            partner = procurement.product_id.sudo().company_id.partner_id

            gpo = procurement.rule_id.group_propagation_option
            group = (gpo == 'fixed' and procurement.rule_id.group_id) or \
                    (gpo == 'propagate' and procurement.group_id) or False

            domain = (
                ('partner_id', '=', partner.id),
{'fraction_non_alphanumeric': 0.0911182013801291, 'fraction_numerical': 0.001780811753357572, 'mean_word_length': 1.6349951124144673, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 20, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '960301', 'n_tokens_mistral': 3831, 'n_tokens_neox': 3603, 'n_words': 883}