def call_log(self, state): """ Prepare crm.phonecall creation. """ communication_id = self.env.context.get("click2dial_id") communication = self.env["partner.communication.job"].browse( communication_id) call_vals = { "state": state, "description": self.comments, "name": communication.config_id.name, "communication_id": communication_id, "partner_id": communication.partner_id.id, } try: parsed_num = phonenumbers.parse( self.env.context.get("phone_number")) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: call_vals["partner_mobile"] = self.env.context.get( "phone_number") else: call_vals["partner_phone"] = self.env.context.get( "phone_number") except TypeError: _logger.info("Partner has no phone number") return self.env["crm.phonecall"].create(call_vals)
def can_send(self, phone): return ( isinstance(phone, PhoneNumber) and phone.is_valid() and number_type(phone) in [PhoneNumberType.MOBILE, PhoneNumberType.FIXED_LINE_OR_MOBILE,] )
def _create_open_crm_phonecall(self, direction='outbound'): teams = self.env['crm.team'].search( [('member_ids', 'in', self._uid)]) action_ctx = self.env.context.copy() action_ctx.update({ 'default_direction': direction, 'default_team_id': teams and teams[0].id or False, }) domain = False if self.env.context.get('click2dial_model') == 'res.partner': partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', 'child_of', partner_id)] elif self.env.context.get('click2dial_model') == 'crm.lead': lead_id = self.env.context.get('click2dial_id') action_ctx['default_opportunity_id'] = lead_id domain = [('opportunity_id', '=', lead_id)] parsed_num = phonenumbers.parse(self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] =\ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] =\ self.env.context.get('phone_number') action = self.env['ir.actions.act_window'].for_xml_id( 'crm_phone', 'crm_phonecall_action') action.update({ 'domain': domain, 'view_mode': 'form,tree,calendar', 'context': action_ctx, }) return action
def call_success(self): """ Prepare crm.phonecall creation. """ action_ctx = self.env.context.copy() action_ctx.update({ 'default_state': 'done', 'default_description': self.comments, 'default_name': self.env.context.get('call_name'), }) partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', '=', partner_id)] try: parsed_num = phonenumbers.parse( self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] = \ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] = \ self.env.context.get('phone_number') except TypeError: _logger.info("Partner has no phone number") return { 'name': _('Phone Call'), 'domain': domain, 'res_model': 'crm.phonecall', 'view_mode': 'form,tree,calendar', 'type': 'ir.actions.act_window', 'nodestroy': False, # close the pop-up wizard after action 'target': 'new', 'context': action_ctx, }
def default_get(self, fields_list): res = super(NumberNotFound, self).default_get(fields_list) if not res: res = {} if res.get('calling_number'): if not self.env.user.company_id.country_id: raise UserError(_( 'Missing country on company %s' % self.env.user.company_id.name)) country_code = self.env.user.company_id.country_id.code try: parsed_num = phonenumbers.parse( res['calling_number'], country_code) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' except Exception, e: _logger.error( "Cannot reformat the phone number '%s': %s", res['calling_number'], e) pass
def _create_open_crm_phonecall(self, direction='outbound'): teams = self.env['crm.team'].search([('member_ids', 'in', self._uid)]) action_ctx = self.env.context.copy() action_ctx.update({ 'default_direction': direction, 'default_team_id': teams and teams[0].id or False, }) domain = False if self.env.context.get('click2dial_model') == 'res.partner': partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', 'child_of', partner_id)] elif self.env.context.get('click2dial_model') == 'crm.lead': lead_id = self.env.context.get('click2dial_id') action_ctx['default_opportunity_id'] = lead_id domain = [('opportunity_id', '=', lead_id)] parsed_num = phonenumbers.parse(self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] =\ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] =\ self.env.context.get('phone_number') return { 'name': _('Phone Call'), 'type': 'ir.actions.act_window', 'res_model': 'crm.phonecall', 'domain': domain, 'view_mode': 'form,tree,calendar', 'nodestroy': False, # close the pop-up wizard after action 'target': 'current', 'context': action_ctx, }
def _create_open_crm_phonecall(self, direction="outbound", state="done"): teams = self.env["crm.team"].search([("member_ids", "in", self._uid)]) action_ctx = self.env.context.copy() action_ctx.update({ "default_direction": direction, "default_team_id": teams and teams[0].id or False, "default_state": state, }) if self.env.context.get("click2dial_model") == "res.partner": partner_id = self.env.context.get("click2dial_id") action_ctx["default_partner_id"] = partner_id elif self.env.context.get("click2dial_model") == "crm.lead": lead_id = self.env.context.get("click2dial_id") action_ctx["default_opportunity_id"] = lead_id parsed_num = phonenumbers.parse(self.env.context.get("phone_number")) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx["default_partner_mobile"] = self.env.context.get( "phone_number") else: action_ctx["default_partner_phone"] = self.env.context.get( "phone_number") action = self.env.ref( "crm_phone.crm_phonecall_action").sudo().read()[0] action.update({ "view_mode": "form,tree,calendar", "views": False, "context": action_ctx, }) return action
def default_get(self, fields_list): res = super().default_get(fields_list) if not res: res = {} if res.get("calling_number"): if not self.env.company.country_id: raise UserError( _("Missing country on company %s" % self.env.company.display_name)) country_code = self.env.company.country_id.code try: parsed_num = phonenumbers.parse(res["calling_number"], country_code) res["e164_number"] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res["number_type"] = "mobile" else: res["number_type"] = "phone" except Exception as e: _logger.error( "Cannot reformat the phone number '%s': %s", res["calling_number"], e, ) return res
def default_get(self, fields_list): res = super(NumberNotFound, self).default_get(fields_list) if not res: res = {} if res.get('calling_number'): if not self.env.user.company_id.country_id: raise UserError( _('Missing country on company %s' % self.env.user.company_id.name)) country_code = self.env.user.company_id.country_id.code try: parsed_num = phonenumbers.parse(res['calling_number'], country_code) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' except Exception as e: _logger.error("Cannot reformat the phone number '%s': %s", res['calling_number'], e) pass return res
def send_sms(message, phone_number, force=False, at=None): phone_number = to_phone_number(phone_number) if not force and not phone_number.is_valid(): raise SMSSendException("Le numéro ne semble pas correct") if not force and number_type(phone_number) not in [ PhoneNumberType.FIXED_LINE_OR_MOBILE, PhoneNumberType.MOBILE, ]: raise SMSSendException( "Le numéro ne semble pas être un numéro de mobile") try: result = _send_sms(message, [phone_number], at=at) except Exception: logger.exception("Le message n'a pas été envoyé.") raise SMSSendException("Le message n'a pas été envoyé.") if len(result["invalidReceivers"]) > 0: logger.error( f"Destinataires invalides {' '.join(result['invalidReceivers'])}") raise SMSSendException("Destinataire invalide.") if len(result["validReceivers"]) < 1: raise SMSSendException("Le message n'a pas été envoyé.")
def validate_number(number, country, include_description=True) -> Optional[Number]: try: p = parse_number(number, country) except NumberParseException: return if not is_valid_number(p): return is_mobile = number_type(p) in MOBILE_NUMBER_TYPES descr = None if include_description: country = country_name_for_number(p, 'en') region = description_for_number(p, 'en') descr = country if country == region else f'{region}, {country}' return Number( number=format_number(p, PhoneNumberFormat.E164), country_code=f'{p.country_code}', number_formatted=format_number(p, PhoneNumberFormat.INTERNATIONAL), descr=descr, is_mobile=is_mobile, )
def create_partner(self): """Function called by the related button of the wizard""" self.ensure_one() parsed_num = phonenumbers.parse(self.e164_number, None) phonenumbers.number_type(parsed_num) context = dict(self._context or {}) context["default_%s" % self.number_type] = self.e164_number action = { "name": _("Create New Partner"), "view_mode": "form,tree,kanban", "res_model": "res.partner", "type": "ir.actions.act_window", "target": "current", "context": context, } return action
def create_partner(self): '''Function called by the related button of the wizard''' wiz = self[0] parsed_num = phonenumbers.parse(wiz.e164_number, None) phonenumbers.number_type(parsed_num) context = dict(self._context or {}) context.update({'default_%s' % wiz.number_type: wiz.e164_number}) action = { 'name': _('Create New Partner'), 'view_mode': 'form,tree,kanban', 'res_model': 'res.partner', 'type': 'ir.actions.act_window', 'nodestroy': False, 'target': 'current', 'context': context, } return action
def validate_phone(value): try: phone_obj = phonenumbers.parse(value, 'UA') except: raise forms.ValidationError( _(u'The string is not a valid phone number.')) phone_type = phonenumbers.number_type(phone_obj) if phone_type == 99: raise forms.ValidationError(_(u"Invalid phone number.")) return f'{phone_obj.country_code}{phone_obj.national_number}'
def clean_number(self): try: data = parse(self.cleaned_data['number'], None) if not number_type(data) == PhoneNumberType.MOBILE: raise forms.ValidationError('Please enter a valid mobile phone number.') return '+{}{}'.format(data.country_code, data.national_number) except NumberParseException: raise forms.ValidationError(validate_international_phonenumber.message)
def create_partner(self, cr, uid, ids, context=None): '''Function called by the related button of the wizard''' if context is None: context = {} wiz = self.browse(cr, uid, ids[0], context=context) parsed_num = phonenumbers.parse(wiz.e164_number, None) phonenumbers.number_type(parsed_num) context['default_%s' % wiz.number_type] = wiz.e164_number action = { 'name': _('Create New Partner'), 'view_mode': 'form,tree,kanban', 'res_model': 'res.partner', 'type': 'ir.actions.act_window', 'nodestroy': False, 'target': 'current', 'context': context, } return action
def do_transform(self, request, response, config): phone = request.entity # Formats the string for the parser to understand the phone number number = "" if phone.countrycode: number += "+" + phone.countrycode + " " if phone.citycode: number += citycode if phone.areacode: number += phone.areacode number += phone.lastnumbers try: parsed = phonenumbers.parse(number) except phonenumbers.NumberParseException as e: # The phone number couldn't be parsed return response # Gets the country from the country code (if any) country_code = phonenumbers.region_code_for_number(parsed) # It may be the country, city, or any string that defines a geographical area location_str = str(description_for_number(parsed, "en")) phone_type = self.phonetype_lookup[phonenumbers.number_type(parsed)] # Returns the result in english (we don't care, as it's just the carrier's name) carrier_name = carrier.name_for_number(parsed, "en") valid_number = phonenumbers.is_valid_number(parsed) # Creates the entities to be added to the graph if not valid_number: # Adds a phrase warning about the invalid phone response += ents.Phrase(text="Possibly invalid number", link_color=LinkColor.Red, link_thickness=3) # Phrase with the carrier info if carrier_name: response += ents.Phrase("Carrier: " + carrier_name) # Phrase with the phone type if phone_type and phone_type.lower() != "unknown": response += ents.Phrase("Phone type: " + phone_type) # Location if location_str or country_code: response += self.extract_location(location_str, country_code) return response
def process_phone(phone_raw, country='ID', lang='en', metadata=True): if not phone_raw: return None if type(phone_raw) != str: phone_raw = str(phone_raw) if any(e.isalpha() or e in '#*' for e in phone_raw) or \ len(phone_raw) <= 7: if not metadata: return phone_raw else: dct = {'phone': phone_raw, 'phone_type': 'SHORT_CODE'} return dct phone = re.sub('[/;].*$', '', phone_raw) phone = re.sub('[^+#*0-9]', '', phone) if country == 'ID': phone = re.sub('^0062|^062', '+62', phone) phone = re.sub('^\+0', '0', phone) if phone in ('+62', '62'): return None try: x = phonenumbers.parse(phone, country) phone = '+{}{}'.format(x.country_code, x.national_number) if not metadata: return phone else: location = geocoder.description_for_number(x, lang) phone_type = PHONE_TYPE[phonenumbers.number_type(x)] telco = carrier.name_for_number(x, lang) dct = {'phone': phone, 'phone_type': phone_type} if location: dct['location'] = location if telco: dct['carrier'] = telco except: if not metadata: return phone_raw else: dct = {'phone': phone_raw} return dct
def isTollFreeNumber(number, region='US'): """ returns True if number is a TollFree Number """ try: p = phonenumbers.parse(number, 'US') except phonenumbers.NumberParseException: return False if phonenumbers.number_type(p) == \ phonenumbers.PhoneNumberType.TOLL_FREE: return True return False
def clean_number(self): try: data = phonenumbers.parse(self.cleaned_data['number'], None) if not phonenumbers.number_type(data) == PhoneNumberType.MOBILE: raise forms.ValidationError( 'Please enter a valid mobile phone number.') return '+{}{}'.format(data.country_code, data.national_number) except NumberParseException: raise forms.ValidationError( validate_international_phonenumber.message)
def check_valid_phonenumber(self): if not phonenumbers or self.type not in _PHONE_TYPES: return Configuration = Pool().get('party.configuration') config = Configuration(1) if config.party_phonecountry: code = config.party_phonecountry.code try: phonenumber = phonenumbers.parse(self.value, region=code) except NumberParseException: self.raise_user_error('invalid_phonenumber', { 'phone': self.value, 'party': self.party.rec_name }) else: if not phonenumbers.is_possible_number( phonenumber) or not phonenumbers.is_valid_number( phonenumber): self.raise_user_error('invalid_phonenumber', { 'phone': self.value, 'party': self.party.rec_name }) elif phonenumbers.number_type( phonenumber ) == PhoneNumberType.FIXED_LINE and self.type == 'mobile': self.raise_user_warning( 'warn_fixed_line_phone.%d' % self.id, 'The phone number "%(phone)s" is a fixed line number.', {'phone': self.value}, ) elif phonenumbers.number_type( phonenumber ) == PhoneNumberType.MOBILE and self.type != 'mobile': self.raise_user_warning( 'warn_mobile_line_phone.%d' % self.id, 'The phone number "%(phone)s" is a mobile line number.', {'phone': self.value}, )
def do(x): phonenumber = phonenumbers.parse(x, 'NZ') print "Raw: %s" % x print "PhoneNumber: %s" % phonenumber print "National: %s" % phonenumbers.format_number(phonenumber, phonenumbers.PhoneNumberFormat.NATIONAL) print "International: %s" % phonenumbers.format_number(phonenumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL) print "E164: %s" % phonenumbers.format_number(phonenumber, phonenumbers.PhoneNumberFormat.E164) print "Possible Number: %s" % phonenumbers.is_valid_number(phonenumber) print "Valid Number: %s" % phonenumbers.is_possible_number(phonenumber) print "Type: %s" % phonenumbers.number_type(phonenumber) print "*********************" print '\n'
def call_success(self): """ Prepare crm.phonecall creation. """ categ = self.with_context(lang='en_US').env['crm.case.categ'].search([ ('name', '=', 'Outbound') ]) case_section = self.env['crm.case.section'].search([('member_ids', 'in', self._uid)]) action_ctx = self.env.context.copy() now = self.env.context.get('timestamp') if isinstance(now, int): now = datetime.fromtimestamp(now / float(1000)) else: now = fields.Datetime.from_string(now) call_time = datetime.now() - now action_ctx.update({ 'default_categ_id': categ and categ[0].id or False, 'default_section_id': case_section and case_section[0].id or False, 'default_state': 'done', 'default_description': self.comments, 'default_name': self.env.context.get('call_name'), 'default_duration': call_time.total_seconds() / 60, }) partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', '=', partner_id)] parsed_num = phonenumbers.parse(self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] = \ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] = \ self.env.context.get('phone_number') return { 'name': _('Phone Call'), 'domain': domain, 'res_model': 'crm.phonecall', 'view_mode': 'form,tree', 'type': 'ir.actions.act_window', 'nodestroy': False, # close the pop-up wizard after action 'target': 'current', 'context': action_ctx, }
def lookup(phonenum): returndict = {} phoneobj = phonenumbers.parse(phonenum) returndict['valid'] = phonenumbers.is_valid_number(phoneobj) returndict['local_format'] = phonenumbers.format_in_original_format( phoneobj, 'local') returndict[ 'intl_format'] = phonenumbers.format_out_of_country_keeping_alpha_chars( phoneobj, 'world') returndict['carrier'] = carrier.name_for_number(phoneobj, "en") returndict['country_code'] = geocoder.region_code_for_number(phoneobj) returndict['country_name'] = geocoder.country_name_for_number( phoneobj, "en") returndict['location'] = geocoder.description_for_number(phoneobj, "en") returndict['line_type'] = get_type(phonenumbers.number_type(phoneobj)) return json.dumps(returndict)
def default_get(self, fields_list): res = super(NumberNotFound, self).default_get(fields_list) if not res: res = {} if res.get('calling_number'): convert = self.env['res.partner']._generic_reformat_phonenumbers( None, {'phone': res.get('calling_number')}) parsed_num = phonenumbers.parse(convert.get('phone')) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' return res
def do(x): phonenumber = phonenumbers.parse(x, 'NZ') print "Raw: %s" % x print "PhoneNumber: %s" % phonenumber print "National: %s" % phonenumbers.format_number( phonenumber, phonenumbers.PhoneNumberFormat.NATIONAL) print "International: %s" % phonenumbers.format_number( phonenumber, phonenumbers.PhoneNumberFormat.INTERNATIONAL) print "E164: %s" % phonenumbers.format_number( phonenumber, phonenumbers.PhoneNumberFormat.E164) print "Possible Number: %s" % phonenumbers.is_valid_number(phonenumber) print "Valid Number: %s" % phonenumbers.is_possible_number(phonenumber) print "Type: %s" % phonenumbers.number_type(phonenumber) print "*********************" print '\n'
def default_get(self, cr, uid, fields_list, context=None): res = super(number_not_found, self).default_get( cr, uid, fields_list, context=context) if not res: res = {} if res.get('calling_number'): convert = self.pool['phone.common']._generic_reformat_phonenumbers( cr, uid, {'phone': res.get('calling_number')}, context=context) parsed_num = phonenumbers.parse(convert.get('phone')) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' return res
def correct_mobile(mobile, country, raise_exception=False): try: mobile = mobile.replace(' ', '') country = country.upper() if country in ['KW', 'OM', 'BH', 'QA'] and not mobile.startswith('00') and mobile.startswith('0'): mobile = mobile[1:] p = phonenumbers.parse(mobile, country) fixed_line = phonenumbers.phonenumberutil.PhoneNumberType.FIXED_LINE if phonenumbers.is_valid_number(p) and phonenumbers.number_type(p) != fixed_line: mobile = phonenumbers.format_number(p, phonenumbers.PhoneNumberFormat.E164) else: raise ValueError() except (phonenumbers.NumberParseException, ValueError): if raise_exception: raise ValidationError(_("Is not valid in %(country)s") % {'country': COUNTRY_ISO[country]}) mobile = '' return mobile
def _abides_by_the_rule(self, value) -> bool: # Fail when the format of the given file is not in the formats list. try: number = phonenumbers.parse(value, None) except phonenumbers.NumberParseException: return False phoneType = phonenumbers.number_type(number) if phoneType == phonenumbers.PhoneNumberType.MOBILE: return self.phoneType == 'mobile' elif phoneType == phonenumbers.PhoneNumberType.FIXED_LINE: return self.phoneType == 'landline' elif phoneType == phonenumbers.PhoneNumberType.FIXED_LINE_OR_MOBILE: return True else: return False
def number_to_text(num): try: if not num.startswith('+'): num = '+' + num x = phonenumbers.parse(num) def number_type_desc(num_type): if num_type == PhoneNumberType.PREMIUM_RATE: return 'premium-rate' elif num_type == PhoneNumberType.TOLL_FREE: return 'toll-free' elif num_type == PhoneNumberType.MOBILE: return 'mobile' elif num_type == PhoneNumberType.FIXED_LINE: return 'fixed-line' elif num_type == PhoneNumberType.FIXED_LINE_OR_MOBILE: return 'fixed-line or mobile' elif num_type == PhoneNumberType.SHARED_COST: return 'shared cost' elif num_type == PhoneNumberType.VOIP: return 'VoIP' elif num_type == PhoneNumberType.PERSONAL_NUMBER: return 'personal number' elif num_type == PhoneNumberType.PAGER: return 'pager' elif num_type == PhoneNumberType.UAN: return 'company "universal access number"' elif num_type == PhoneNumberType.VOICEMAIL: return 'voicemail' else: return 'unknown type' number = phonenumbers.format_number(x, phonenumbers.PhoneNumberFormat.INTERNATIONAL) numtype = number_type_desc(phonenumbers.number_type(x)) country = geocoder.country_name_for_number(x, "en") desc = geocoder.description_for_number(x, "en") if not desc or desc == country: return '%s\n%s - %s' % (number, country, numtype) else: return '%s\n%s, %s - %s' % (number, desc, country, numtype) except: return '%s\ninvalid' % (num)
def _parseNumber(num): if num: try: num = num.replace(' ', '').replace('/', '').replace('-', '') if num: num = phonenumbers.parse(num, region='DE') num_type = phonenumbers.number_type(num) if phonenumbers.is_valid_number(num) and num_type in [ phonenumbers.PhoneNumberType.FIXED_LINE, phonenumbers.PhoneNumberType.PERSONAL_NUMBER, phonenumbers.PhoneNumberType.MOBILE, phonenumbers.PhoneNumberType.FIXED_LINE_OR_MOBILE ]: return phonenumbers.format_number( num, phonenumbers.PhoneNumberFormat.E164) except phonenumbers.NumberParseException as e: logger.warning(f'Number "{num}" caused an exception: ' + str(e)) return None
def check_phone_number(cls, v): if v is None: return v try: n = parse_phone_number(v, "RO") except NumberParseException as e: raise ValueError( "Please provide a valid mobile phone number") from e if not is_valid_number(n) or number_type(n) not in ( PhoneNumberType.MOBILE, PhoneNumberType.FIXED_LINE_OR_MOBILE, ): raise ValueError("Please provide a valid mobile phone number") return format_number( n, PhoneNumberFormat.NATIONAL if n.country_code == 44 else PhoneNumberFormat.INTERNATIONAL)
def default_get(self, cr, uid, fields_list, context=None): res = super(number_not_found, self).default_get( cr, uid, fields_list, context=context ) if not res: res = {} if res.get('calling_number'): convert = self.pool['res.partner']._generic_reformat_phonenumbers( cr, uid, None, {'phone': res.get('calling_number')}, context=context) parsed_num = phonenumbers.parse(convert.get('phone')) res['e164_number'] = phonenumbers.format_number( parsed_num, phonenumbers.PhoneNumberFormat.INTERNATIONAL) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: res['number_type'] = 'mobile' else: res['number_type'] = 'phone' return res
def _create_open_crm_phonecall(self, crm_categ): categ = self.with_context(lang='en_US').env['crm.case.categ'].search([ ('name', '=', crm_categ) ]) case_section = self.env['crm.case.section'].search([('member_ids', 'in', self._uid)]) action_ctx = self.env.context.copy() action_ctx.update({ 'default_categ_id': categ and categ[0].id or False, 'default_section_id': case_section and case_section[0].id or False, }) domain = False if self.env.context.get('click2dial_model') == 'res.partner': partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', '=', partner_id)] elif self.env.context.get('click2dial_model') == 'crm.lead': lead_id = self.env.context.get('click2dial_id') action_ctx['default_opportunity_id'] = lead_id domain = [('opportunity_id', '=', lead_id)] parsed_num = phonenumbers.parse(self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] =\ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] =\ self.env.context.get('phone_number') return { 'name': _('Phone Call'), 'domain': domain, 'res_model': 'crm.phonecall', 'view_mode': 'form,tree', 'type': 'ir.actions.act_window', 'nodestroy': False, # close the pop-up wizard after action 'target': 'current', 'context': action_ctx, }
def _create_open_crm_phonecall(self, crm_categ): categ = self.with_context(lang='en_US').env['crm.case.categ'].search( [('name', '=', crm_categ)]) case_section = self.env['crm.case.section'].search( [('member_ids', 'in', self._uid)]) action_ctx = self.env.context.copy() action_ctx.update({ 'default_categ_id': categ and categ[0].id or False, 'default_section_id': case_section and case_section[0].id or False, }) domain = False if self.env.context.get('click2dial_model') == 'res.partner': partner_id = self.env.context.get('click2dial_id') action_ctx['default_partner_id'] = partner_id domain = [('partner_id', '=', partner_id)] elif self.env.context.get('click2dial_model') == 'crm.lead': lead_id = self.env.context.get('click2dial_id') action_ctx['default_opportunity_id'] = lead_id domain = [('opportunity_id', '=', lead_id)] parsed_num = phonenumbers.parse(self.env.context.get('phone_number')) number_type = phonenumbers.number_type(parsed_num) if number_type == 1: action_ctx['default_partner_mobile'] =\ self.env.context.get('phone_number') else: action_ctx['default_partner_phone'] =\ self.env.context.get('phone_number') return { 'name': _('Phone Call'), 'domain': domain, 'res_model': 'crm.phonecall', 'view_mode': 'form,tree', 'type': 'ir.actions.act_window', 'nodestroy': False, # close the pop-up wizard after action 'target': 'current', 'context': action_ctx, }
def validate_phone_number(phone_number, faults): if not isinstance(phone_number, dict): faults.append('phone_number must be a dict') return if not 'number' in phone_number.keys(): faults.append('phone_number must contain the field \'number\'') return if not 'country_code' in phone_number.keys(): faults.append('phone_number must contain the field \'country_code\'') return try: number = phonenumbers.parse(str(phone_number['number']), str(phone_number['country_code'])) valid = phonenumbers.is_valid_number(number) if not valid: faults.append( 'The phone number %s (country %s) is invalid.' % (phone_number['number'], phone_number['country_code'])) return number_type = phonenumbers.number_type(number) if number_type != PhoneNumberType.MOBILE: faults.append('The phone number %s (country %s) is not a mobile number.' % (phone_number['number'], phone_number['country_code'])) except Exception as e: faults.append('The phone number %s (country %s) is invalid. Reason: %s' % ( phone_number['number'], phone_number['country_code'], str(e)))
def get_typeid(self): self.phonenumber_details['typeid'] = dicts.phonenumber_types.get(phonenumbers.number_type(self.phonenumber_object)) return self.phonenumber_details['typeid']