
from odoo import api,fields,models,_
from odoo.exceptions import ValidationError

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

    def get_partner_list(self,partner_objs):
        partner_list = ''
        for partner in partner_objs:
            partner_list = partner_list + ' || ' + partner.name
        return partner_list

    @api.onchange('name')
    def onchange_name(self):
        if self.name and self.env.user.has_group("abs_customer_validation.group_activate_customer_validation"):
            if self.env['res.partner'].search([('name','=',self.name)]):
                raise ValidationError(_('The record ' +self.name+' is already exist '))

    @api.onchange('phone')
    def onchange_phonenumber(self):
        if self.phone and self.env.user.has_group("abs_customer_validation.group_activate_customer_validation"):
            partner_objs = self.env['res.partner'].search([('phone','=',self.phone)])
            if self.get_partner_list(partner_objs):
                raise ValidationError(_('Phone number '+str(self.phone)+' is already exist in the following records:' + '\n' + self.get_partner_list(partner_objs)))

    @api.onchange('mobile')
    def onchange_mobilenumber(self):
        if self.mobile and self.env.user.has_group("abs_customer_validation.group_activate_customer_validation"):
            partner_objs = self.env['res.partner'].search([('mobile','=',self.mobile)])
            if self.get_partner_list(partner_objs):
                raise ValidationError(_('Mobile number '+str(self.mobile)+' is already exist in the following records:' + '\n' + self.get_partner_list(partner_objs)))

    @api.onchange('email')
    def onchange_email(self):
        if self.email and self.env.user.has_group("abs_customer_validation.group_activate_customer_validation"):
            partner_objs = self.env['res.partner'].search([('email','=',self.email)])
            if self.get_partner_list(partner_objs):
                raise ValidationError(_('Email number '+str(self.email)+' is already exist in the following records:' + '\n' + self.get_partner_list(partner_objs)))

    @api.onchange('website')
    def onchange_website(self):
        if self.website and self.env.user.has_group("abs_customer_validation.group_activate_customer_validation"):
            website_id = "http://"+str(self.website)
            partner_objs = self.env['res.partner'].search([('website','=',website_id)])
            if self.get_partner_list(partner_objs):
                raise ValidationError(_('Website number '+str(self.website)+' is already exist in the following records:' + '\n' + self.get_partner_list(partner_objs)))


