You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

148 lines
6.0 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2010-2018 Akretion (Alexis de Lattre <alexis.delattre@akretion.com>)
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from odoo import models, api
  5. import logging
  6. _logger = logging.getLogger(__name__)
  7. try:
  8. import phonenumbers
  9. except ImportError:
  10. _logger.debug('Cannot `import phonenumbers`.')
  11. class PhoneCommon(models.AbstractModel):
  12. _name = 'phone.common'
  13. _description = 'Common methods for phone features'
  14. @api.model
  15. def get_name_from_phone_number(self, presented_number):
  16. '''Function to get name from phone number. Usefull for use from IPBX
  17. to add CallerID name to incoming calls.'''
  18. res = self.get_record_from_phone_number(presented_number)
  19. if res:
  20. return res[2]
  21. else:
  22. return False
  23. @api.model
  24. def get_record_from_phone_number(self, presented_number):
  25. '''If it finds something, it returns (object name, ID, record name)
  26. For example : ('res.partner', 42, 'Alexis de Lattre (Akretion)')
  27. '''
  28. _logger.debug(
  29. "Call get_name_from_phone_number with number = %s"
  30. % presented_number)
  31. if not isinstance(presented_number, str):
  32. _logger.warning(
  33. "Number '%s' should be a 'str' but it is a '%s'"
  34. % (presented_number, type(presented_number)))
  35. return False
  36. if not presented_number.isdigit():
  37. _logger.warning(
  38. "Number '%s' should only contain digits." % presented_number)
  39. nr_digits_to_match_from_end = \
  40. self.env.user.company_id.number_of_digits_to_match_from_end
  41. if len(presented_number) >= nr_digits_to_match_from_end:
  42. end_number_to_match = presented_number[
  43. -nr_digits_to_match_from_end:len(presented_number)]
  44. else:
  45. end_number_to_match = presented_number
  46. sorted_phonemodels = self._get_phone_models()
  47. for obj_dict in sorted_phonemodels:
  48. obj = obj_dict['object']
  49. pg_search_number = '%' + end_number_to_match
  50. _logger.debug(
  51. "Will search phone and mobile numbers in %s ending with '%s'",
  52. obj._name, end_number_to_match)
  53. sql = "SELECT id FROM %s WHERE " % obj._table
  54. sql_where = []
  55. sql_args = []
  56. for field in obj_dict['fields']:
  57. sql_where.append("replace(%s, ' ', '') ilike %%s" % field)
  58. sql_args.append(pg_search_number)
  59. sql = sql + ' or '.join(sql_where)
  60. _logger.debug("get_record_from_phone_number sql=%s", sql)
  61. self._cr.execute(sql, tuple(sql_args))
  62. res_sql = self._cr.fetchall()
  63. #res_obj = obj.search(domain)
  64. if len(res_sql) > 1:
  65. _logger.warning(
  66. u"There are several %s (IDS = %s) with a phone number "
  67. "ending with '%s'. Taking the first one.",
  68. obj._name, res_obj.ids, end_number_to_match)
  69. if res_sql:
  70. obj_id = res_sql[0][0]
  71. res_obj = obj.browse(obj_id)
  72. name = res_obj.display_name
  73. res = (obj._name, res_obj.id, name)
  74. _logger.debug(
  75. u"Answer get_record_from_phone_number: (%s, %d, %s)",
  76. res[0], res[1], res[2])
  77. return res
  78. else:
  79. _logger.debug(
  80. u"No match on %s for end of phone number '%s'",
  81. obj._name, end_number_to_match)
  82. return False
  83. @api.model
  84. def _get_phone_models(self):
  85. phoneobj = []
  86. for model_name in self.env.registry.keys():
  87. senv = False
  88. try:
  89. senv = self.with_context(callerid=True).env[model_name]
  90. except:
  91. continue
  92. if (
  93. hasattr(senv, '_phone_name_sequence') and
  94. isinstance(senv._phone_name_sequence, int) and
  95. hasattr(senv, '_phone_name_fields') and
  96. isinstance(senv._phone_name_fields, list)):
  97. cdict = {
  98. 'object': senv,
  99. 'fields': senv._phone_name_fields,
  100. }
  101. phoneobj.append((senv._phone_name_sequence, cdict))
  102. phoneobj_sorted = sorted(phoneobj, key=lambda element: element[0])
  103. res = []
  104. for l in phoneobj_sorted:
  105. res.append(l[1])
  106. # [{'fields': ['fax', 'phone', 'mobile'], 'object': res.partner()},
  107. # {'fields': ['fax', 'phone', 'mobile'], 'object': crm.lead()}]
  108. return res
  109. @api.model
  110. def click2dial(self, erp_number):
  111. '''This function is designed to be overridden in IPBX-specific
  112. modules, such as asterisk_click2dial or ovh_telephony_connector'''
  113. return {'dialed_number': erp_number}
  114. @api.model
  115. def convert_to_dial_number(self, erp_number):
  116. '''
  117. This function is dedicated to the transformation of the number
  118. available in Odoo to the number that can be dialed.
  119. You may have to inherit this function in another module specific
  120. for your company if you are not happy with the way I reformat
  121. the numbers.
  122. '''
  123. assert(erp_number), 'Missing phone number'
  124. _logger.debug('Number before reformat = %s' % erp_number)
  125. # erp_number are supposed to be in International format, so no need to
  126. # give a country code here
  127. parsed_num = phonenumbers.parse(erp_number, None)
  128. country_code = self.env.user.company_id.country_id.code
  129. assert(country_code), 'Missing country on company'
  130. _logger.debug('Country code = %s' % country_code)
  131. to_dial_number = phonenumbers.format_out_of_country_calling_number(
  132. parsed_num, country_code.upper())
  133. to_dial_number = to_dial_number.translate(
  134. to_dial_number.maketrans('', '', ' -.()/'))
  135. _logger.debug('Number to be sent to phone system: %s' % to_dial_number)
  136. return to_dial_number