<commit_before># -*- coding: utf-8 -*-
# © 2016 Comunitea Servicios Tecnologicos (<http://www.comunitea.com>)
# <NAME> (<<EMAIL>>)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import fields, models, tools, api, _

from odoo.exceptions import AccessError, UserError, ValidationError
from datetime import datetime, timedelta

import os
import re

SGA_STATE = [('NI', 'No Integrado'), ('AC', 'Actualizado'), ('PA', 'Pendiente actualizar'), ('BA', 'Baja'), ('ER', 'Error')]
SGA_PRODUCT_TYPES = ('product', 'consu')

class SGADestination(models.Model):

    _name ="sga.destination"

    code = fields.Char("Code")
    name = fields.Char("Description")

class SGAProductCategory(models.Model):

    _inherit = "product.category"
    code = fields.Char("Codigo de categoria", size=12)
    parent_code = fields.Char(related="parent_id.code")
    sga_state = fields.Selection(SGA_STATE,
                                 'Estado Mecalux',
                                 default='PA',
                                 help="Estado integracion con mecalux")

    _sql_constraints = [
        ('code_uniq', 'unique(code)', 'producttype code must be unique.'),
    ]

    @api.onchange('name', 'parent_id', 'code')
    def onchange_picking_type(self):
        for categ in self:
            categ.sga_state = 'PA'

    @api.multi
    def write(self, values):
        to_mecalux = False
        fields_to_check = ('name', 'parent_id', 'code')
        fields = sorted(list(set(values).intersection(set(fields_to_check))))
        if fields:
            values['sga_state'] = 'PA'
            to_mecalux = True
        res = super(SGAProductCategory, self).write(values)

        if to_mecalux:
            icp = self.env['ir.config_parameter']
            if icp.get_param('product_auto'):
                self.export_category_to_mecalux(operation="F")

        return res

    @api.model
    def create(self, values):
        icp = self.env['ir.config_parameter']
        res = super(SGAProductCategory, self).create(values)
        if icp.get_param('product_auto'):
            #Siempre F (modificacion + alta)
            res.export_category_to_mecalux(operation="F")
            res.sga_state = 'AC'
        return res

    def new_mecalux_file(self, operation='F'):
        return self.export_category_to_mecalux(self, operation=operation)

    @api.multi
    def export_category_to_mecalux(self, operation=False):

        def get_ids(cat):

            res = []
            while cat:
                if cat.sga_state != 'AC':
                    if not res:
                        res.append(cat.id)
                    elif not cat.sga_state:
                        res.append(cat.id)
                cat = cat.parent_id
            return res

        ids = [self.id]
        ctx = self._context.copy()
        force = ctx.get('force', True)
        for x in self:
            ids += get_ids(x)
        ids = sorted(list(set(ids)))
        if not ids:
            raise ValidationError("No hay registros modificados para actualizar")
        if operation:
            ctx['operation'] = operation
        if 'operation' not in ctx:
            ctx['operation'] = 'F'
        try:
            new_sga_file = self.env['sga.file'].with_context(ctx).check_sga_file('product.category', ids, code='TPR')
            self.env['product.category'].browse(ids).write({'sga_state': 'AC'})
            return True
        except:
            self.env['product.category'].browse(ids).write({'sga_state': 'ER'})
            return False

class SGAContainerTypeCode(models.Model):

    _name ="sga.containertype"
    _rec_name = 'code'

    code = fields.Char("Codigo de contenedor (SGA)", size=10)
    description = fields.Char("Descripcion de contenedor (SGA)")

class SGAProductPackaging(models.Model):

    _inherit = "product.packaging"

    ul_type = fields.Selection(selection_add=[('sga', 'Mecalux')])

    sga_uom_base_code = fields.Char(related='product_tmpl_id.uom_id.sga_uom_base_code')
    sga_desc_uom_base_code = fields.Char(related='product_tmpl_id.uom_id.name')
    sga_complete_percent = fields.Integer('SGA complete percent', default=1,
                                          help="Porcentaje para servir el palet completo")
    sga_min_quantity = fields.Float('SGA min quantity', default=1, help="Cantidad minima a servir")
    sga_operation = fields.Char('SGA Operation', default="A")
    sga_containertype_code_id = fields.Many2one('sga.containertype',
                                                "Tipo de contenedor",
                                                help="Tipo de contenedor de Mecalux")
    sga_containertype_code = fields.Char(related="sga_containertype_code_id.code")
    sga_desc_containertype_code = fields.Char(related="sga_containertype_code_id.description")

    @api.model
    def default_get(self, fields):
        res = super(SGAProductPackaging, self).default_get(fields)
        #### Que carallo hice aquí ?????
        if self._context.get('template_id') and 'model_id' in fields and not res.get('model_id'):
            res['model_id'] = self.env['mail.template'].browse(self._context['template_id']).model_id.id
        return res

    @api.model
    def create(self, vals):
        new_sga = super(SGAProductPackaging, self).create(vals)
        # si está asociado a un template
        if new_sga.product_tmpl_id and new_sga.product_tmpl_id.sga_state != 'AC':
            new_sga.product_tmpl_id.sga_state = 'PA'
            new_sga.product_tmpl_id.export_template_to_mecalux()
        return new_sga

    @api.multi
    def write(self, vals):
        res_write = super(SGAProductPackaging, self).write(vals)
        # Si están asociados a templates ....
        for pack in self:
            if pack.product_tmpl_id and pack.product_tmpl_id.sga_state != 'AC':
                pack.product_tmpl_id.sga_state = 'PA'
                pack.product_tmpl_id.export_template_to_mecalux()
        return res_write

class SGAProductProduct(models.Model):

    _inherit = "product.product"

    @api.multi
    def get_sga_name_get(self):
        for prod in self:
            #nombre sin la referencia
            sga_name_get = prod.display_name
            if sga_name_get and ']' in sga_name_get:
                sga_name_get = sga_name_get.split(']')[1].strip()
            prod.sga_name_get = sga_name_get


    sga_name_get = fields.Char("Mecalux name", compute='get_sga_name_get')
    sga_prod_shortdesc = fields.Char("Nombre Radiofrecuencia", size=50)
    sga_stock = fields.Float('Stock (SGA)', help="Last PST from Mecalux")
    sga_change_material_abc = fields.Selection ([('0', "NO"), ('1', "SI")],
                                                default='1',
                                                string="Cambio rotabilidad",
                                                required=True)
    sga_material_abc_code = fields.Selection ([('A', 'A'), ('B', 'B'), ('C', 'C')],
                                              default="C",
                                              string="Tipo de rotabilidad",
                                              required=True)
    sga_state = fields.Selection(SGA_STATE,  'Estado Mecalux',
                                 default='PA',
                                 help="Estado integracion con mecalux")

    sga_product_type_code = fields.Char(related='categ_id.code')
    sga_uom_base_code = fields.Char(related='uom_id.sga_uom_base_code')
    sga_desc_uom_base_code = fields.Char(related='uom_id.name')
    sga_warehouse_code = fields.Char(related="warehouse_id.code")


    @api.onchange('name')
    def on_change(self):
        if self.name and self.sga_name_get:
            self.sga_prod_shortdesc = self.sga_name_get[0:50]

    @api.multi
    def toggle_active(self):
        return super(SGAProductProduct, self).toggle_active()

    @api.multi
    def write(self, values):

        if values.get('type') in SGA_PRODUCT_TYPES:
            values.update ({'sga_state':'PA'})
        else:
            values.update({'sga_state': 'NI'})

        fields_to_check = ('default_code', 'barcode', 'categ_id',
                           'sga_material_abc_code', 'sga_change_material_abc',
                           'name', 'packaging_ids', 'sga_prod_shortdesc')

        fields = sorted(list(set(values).intersection(set(fields_to_check))))
        if not fields:
            return super(SGAProductProduct, self).write(values)

        create_product_product = False

        res = super(SGAProductProduct, self).write(values)

        create_product_product = self._context.get('create_product_product', False)
        if create_product_product:
            self.export_product_to_mecalux()

        return res

    @api.multi
    def export_product_to_mecalux(self, operation="F"):
        res = self.new_mecalux_file(operation)
        return res

    @api.model
    def create(self, values):
        return super(SGAProductProduct, self).create(values)


    @api.multi
    def new_mecalux_file(self, operation=False):
        ids = self.check_mecalux_ok()
        try:
            ctx = self._context.copy()
            if operation:
                ctx['operation'] = operation
            if 'operation' not in ctx:
                ctx['operation'] = 'F'
            print "Enviando a Mecalux los id %s"%ids
            new_sga_file = self.env['sga.file'].with_context(ctx).check_sga_file('product.product', ids, code='PRO')
            if new_sga_file:
                self.filtered(lambda x:x.id in ids).write({'sga_state': 'AC'})
            return new_sga_file
        except:
            self.filtered(lambda x: x.id in ids).write({'sga_state': 'ER'})
            return False

    @api.multi
    def check_mecalux_ok(self):
        ids = []
        for product in self:
            ok = True

            if not product.barcode or \
                            type not in SGA_PRODUCT_TYPES:
                ok = False

            if not product.sga_prod_shortdesc:
                product.sga_prod_shortdesc = product.sga_name_get[0:50]

            if ok:
                ids.append(product.id)
            else:
                product.sga_state = "PA"
        return ids

    @api.multi
    def check_mecalux_stock(self):
        try:
            ids = [x.id for x in self if x.type == 'product']
            if not ids:
                return<commit_msg>[BUG] Error al enviar a mecalux<commit_after># -*- coding: utf-8 -*-
# © 2016 Comunitea Servicios Tecnologicos (<http://www.comunitea.com>)
# <NAME> (<<EMAIL>>)
# License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html

from odoo import fields, models, tools, api, _

from odoo.exceptions import AccessError, UserError, ValidationError
from datetime import datetime, timedelta

import os
import re

SGA_STATE = [('NI', 'No Integrado'), ('AC', 'Actualizado'), ('PA', 'Pendiente actualizar'), ('BA', 'Baja'), ('ER', 'Error')]
SGA_PRODUCT_TYPES = ('product', 'consu')

class SGADestination(models.Model):

    _name ="sga.destination"

    code = fields.Char("Code")
    name = fields.Char("Description")

class SGAProductCategory(models.Model):

    _inherit = "product.category"
    code = fields.Char("Codigo de categoria", size=12)
    parent_code = fields.Char(related="parent_id.code")
    sga_state = fields.Selection(SGA_STATE,
                                 'Estado Mecalux',
                                 default='PA',
                                 help="Estado integracion con mecalux")

    _sql_constraints = [
        ('code_uniq', 'unique(code)', 'producttype code must be unique.'),
    ]

    @api.onchange('name', 'parent_id', 'code')
    def onchange_picking_type(self):
        for categ in self:
            categ.sga_state = 'PA'

    @api.multi
    def write(self, values):
        to_mecalux = False
        fields_to_check = ('name', 'parent_id', 'code')
        fields = sorted(list(set(values).intersection(set(fields_to_check))))
        if fields:
            values['sga_state'] = 'PA'
            to_mecalux = True
        res = super(SGAProductCategory, self).write(values)

        if to_mecalux:
            icp = self.env['ir.config_parameter']
            if icp.get_param('product_auto'):
                self.export_category_to_mecalux(operation="F")

        return res

    @api.model
    def create(self, values):
        icp = self.env['ir.config_parameter']
        res = super(SGAProductCategory, self).create(values)
        if icp.get_param('product_auto'):
            #Siempre F (modificacion + alta)
            res.export_category_to_mecalux(operation="F")
            res.sga_state = 'AC'
        return res

    def new_mecalux_file(self, operation='F'):
        return self.export_category_to_mecalux(self, operation=operation)

    @api.multi
    def export_category_to_mecalux(self, operation=False):

        def get_ids(cat):
            res = []
            while cat:
                if cat.sga_state != 'AC':
                    if not res:
                        res.append(cat.id)
                    elif not cat.sga_state:
                        res.append(cat.id)
                cat = cat.parent_id
            return res

        ids = [self.id]
        ctx = self._context.copy()
        force = ctx.get('force', True)
        for x in self:
            ids += get_ids(x)
        ids = sorted(list(set(ids)))
        if not ids:
            raise ValidationError("No hay registros modificados para actualizar")
        if operation:
            ctx['operation'] = operation
        if 'operation' not in ctx:
            ctx['operation'] = 'F'
        try:
            new_sga_file = self.env['sga.file'].with_context(ctx).check_sga_file('product.category', ids, code='TPR')
            self.env['product.category'].browse(ids).write({'sga_state': 'AC'})
            return True
        except:
            self.env['product.category'].browse(ids).write({'sga_state': 'ER'})
            return False

class SGAContainerTypeCode(models.Model):

    _name ="sga.containertype"
    _rec_name = 'code'

    code = fields.Char("Codigo de contenedor (SGA)", size=10)
    description = fields.Char("Descripcion de contenedor (SGA)")

class SGAProductPackaging(models.Model):

    _inherit = "product.packaging"

    ul_type = fields.Selection(selection_add=[('sga', 'Mecalux')])

    sga_uom_base_code = fields.Char(related='product_tmpl_id.uom_id.sga_uom_base_code')
    sga_desc_uom_base_code = fields.Char(related='product_tmpl_id.uom_id.name')
    sga_complete_percent = fields.Integer('SGA complete percent', default=1,
                                          help="Porcentaje para servir el palet completo")
    sga_min_quantity = fields.Float('SGA min quantity', default=1, help="Cantidad minima a servir")
    sga_operation = fields.Char('SGA Operation', default="A")
    sga_containertype_code_id = fields.Many2one('sga.containertype',
                                                "Tipo de contenedor",
                                                help="Tipo de contenedor de Mecalux")
    sga_containertype_code = fields.Char(related="sga_containertype_code_id.code")
    sga_desc_containertype_code = fields.Char(related="sga_containertype_code_id.description")

    @api.model
    def default_get(self, fields):
        res = super(SGAProductPackaging, self).default_get(fields)
        #### Que carallo hice aquí ?????
        if self._context.get('template_id') and 'model_id' in fields and not res.get('model_id'):
            res['model_id'] = self.env['mail.template'].browse(self._context['template_id']).model_id.id
        return res

    @api.model
    def create(self, vals):
        new_sga = super(SGAProductPackaging, self).create(vals)
        # si está asociado a un template
        if new_sga.product_tmpl_id and new_sga.product_tmpl_id.sga_state != 'AC':
            new_sga.product_tmpl_id.sga_state = 'PA'
            new_sga.product_tmpl_id.export_template_to_mecalux()
        return new_sga

    @api.multi
    def write(self, vals):
        res_write = super(SGAProductPackaging, self).write(vals)
        # Si están asociados a templates ....
        for pack in self:
            if pack.product_tmpl_id and pack.product_tmpl_id.sga_state != 'AC':
                pack.product_tmpl_id.sga_state = 'PA'
                pack.product_tmpl_id.export_template_to_mecalux()
        return res_write

class SGAProductProduct(models.Model):

    _inherit = "product.product"

    @api.multi
    def get_sga_name_get(self):
        for prod in self:
            #nombre sin la referencia
            sga_name_get = prod.display_name
            if sga_name_get and ']' in sga_name_get:
                sga_name_get = sga_name_get.split(']')[1].strip()
            prod.sga_name_get = sga_name_get


    sga_name_get = fields.Char("Mecalux name", compute='get_sga_name_get')
    sga_prod_shortdesc = fields.Char("Nombre Radiofrecuencia", size=50)
    sga_stock = fields.Float('Stock (SGA)', help="Last PST from Mecalux")
    sga_change_material_abc = fields.Selection ([('0', "NO"), ('1', "SI")],
                                                default='1',
                                                string="Cambio rotabilidad",
                                                required=True)
    sga_material_abc_code = fields.Selection ([('A', 'A'), ('B', 'B'), ('C', 'C')],
                                              default="C",
                                              string="Tipo de rotabilidad",
                                              required=True)
    sga_state = fields.Selection(SGA_STATE,  'Estado Mecalux',
                                 default='PA',
                                 help="Estado integracion con mecalux")

    sga_product_type_code = fields.Char(related='categ_id.code')
    sga_uom_base_code = fields.Char(related='uom_id.sga_uom_base_code')
    sga_desc_uom_base_code = fields.Char(related='uom_id.name')
    sga_warehouse_code = fields.Char(related="warehouse_id.code")


    @api.onchange('name')
    def on_change(self):
        if self.name and self.sga_name_get:
            self.sga_prod_shortdesc = self.sga_name_get[0:50]

    @api.multi
    def toggle_active(self):
        return super(SGAProductProduct, self).toggle_active()

    @api.multi
    def write(self, values):

        if values.get('type') in SGA_PRODUCT_TYPES:
            values.update ({'sga_state':'PA'})
        else:
            values.update({'sga_state': 'NI'})

        fields_to_check = ('default_code', 'barcode', 'categ_id',
                           'sga_material_abc_code', 'sga_change_material_abc',
                           'name', 'packaging_ids', 'sga_prod_shortdesc')

        fields = sorted(list(set(values).intersection(set(fields_to_check))))
        if not fields:
            return super(SGAProductProduct, self).write(values)

        create_product_product = False

        res = super(SGAProductProduct, self).write(values)

        create_product_product = self._context.get('create_product_product', False)
        if create_product_product:
            self.export_product_to_mecalux()

        return res

    @api.multi
    def export_product_to_mecalux(self, operation="F"):
        res = self.new_mecalux_file(operation)
        return res

    @api.model
    def create(self, values):
        return super(SGAProductProduct, self).create(values)


    @api.multi
    def new_mecalux_file(self, operation=False):
        ids = self.check_mecalux_ok()
        try:
            ctx = self._context.copy()
            if operation:
                ctx['operation'] = operation
            if 'operation' not in ctx:
                ctx['operation'] = 'F'
            print "Enviando a Mecalux los id %s"%ids
            new_sga_file = self.env['sga.file'].with_context(ctx).check_sga_file('product.product', ids, code='PRO')
            if new_sga_file:
                self.filtered(lambda x:x.id in ids).write({'sga_state': 'AC'})
            return new_sga_file
        except:
            self.filtered(lambda x: x.id in ids).write({'sga_state': 'ER'})
            return False

    @api.multi
    def check_mecalux_ok(self):
        ids = []
        for product in self:
            ok = True

            if not product.barcode or \
                            product.type not in SGA_PRODUCT_TYPES:
                ok = False

            if not product.sga_prod_shortdesc:
                product.sga_prod_shortdesc = product.sga_name_get[0:50]

            if ok:
                ids.append(product.id)
            else:
                product.sga_state = "PA"
        return ids

    @api.multi
    def check_mecalux_stock(self):
        try:
            ids = [x.id for x in self if x.type == 'product']
            if not ids:
                return
{'fraction_non_alphanumeric': 0.11418021387809907, 'fraction_numerical': 0.002589555459646094, 'mean_word_length': 2.1616130988477864, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, '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': '4308158', 'n_tokens_mistral': 6618, 'n_tokens_neox': 6356, 'n_words': 1248}