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.

311 lines
13 KiB

  1. # -*- coding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Base Phone module for Odoo
  5. # Copyright (C) 2010-2015 Alexis de Lattre <alexis@via.ecp.fr>
  6. #
  7. # This program is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU Affero General Public License as
  9. # published by the Free Software Foundation, either version 3 of the
  10. # License, or (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU Affero General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU Affero General Public License
  18. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. #
  20. ##############################################################################
  21. from openerp import models, fields, api, _
  22. from openerp.tools.safe_eval import safe_eval
  23. from openerp.exceptions import UserError
  24. import logging
  25. # Lib for phone number reformating -> pip install phonenumbers
  26. import phonenumbers
  27. _logger = logging.getLogger(__name__)
  28. class PhoneCommon(models.AbstractModel):
  29. _name = 'phone.common'
  30. @api.model
  31. def _reformat_phonenumbers_create(self, vals):
  32. assert isinstance(self._phone_fields, list),\
  33. 'self._phone_fields must be a list'
  34. if any([vals.get(field) for field in self._phone_fields]):
  35. countrycode = self._get_countrycode_from_vals(vals)
  36. countrycode = self._countrycode_fallback(countrycode)
  37. vals = self._reformat_phonenumbers(vals, countrycode)
  38. return vals
  39. @api.multi
  40. def _reformat_phonenumbers_write(self, vals):
  41. assert isinstance(self._phone_fields, list),\
  42. 'self._phone_fields must be a list'
  43. if any([vals.get(field) for field in self._phone_fields]):
  44. countrycode = self._get_countrycode_from_vals(vals)
  45. if not countrycode:
  46. if self._country_field:
  47. country = safe_eval(
  48. 'self.' + self._country_field, {'self': self})
  49. countrycode = country and country.code or None
  50. elif self._partner_field:
  51. partner = safe_eval(
  52. 'self.' + self._partner_field, {'self': self})
  53. if partner:
  54. countrycode = partner.country_id and\
  55. partner.country_id.code or None
  56. countrycode = self._countrycode_fallback(countrycode)
  57. vals = self._reformat_phonenumbers(vals, countrycode)
  58. return vals
  59. @api.model
  60. def _get_countrycode_from_vals(self, vals):
  61. assert isinstance(self._country_field, (str, unicode, type(None))),\
  62. 'Wrong self._country_field'
  63. assert isinstance(self._partner_field, (str, unicode, type(None))),\
  64. 'Wrong self._partner_field'
  65. countrycode = None
  66. if self._country_field and vals.get(self._country_field):
  67. # When updating a partner in the frontend of the POS
  68. # Odoo generate a write() with the ID of the country as unicode !!!
  69. # example : vals = {u'country_id': u'9'}
  70. # So we have to convert it to an integer before browsing
  71. country = self.env['res.country'].browse(
  72. int(vals[self._country_field]))
  73. countrycode = country.code
  74. elif self._partner_field and vals.get(self._partner_field):
  75. partner = self.env['res.partner'].browse(
  76. vals[self._partner_field])
  77. countrycode = partner.country_id.code or False
  78. return countrycode
  79. @api.model
  80. def _countrycode_fallback(self, countrycode):
  81. if not countrycode:
  82. if self.env.user.company_id.country_id:
  83. countrycode = self.env.user.company_id.country_id.code
  84. else:
  85. _logger.error(
  86. "You should set a country on the company '%s' "
  87. "to allow the reformat of phone numbers",
  88. self.env.user.company_id.name)
  89. return countrycode
  90. @api.model
  91. def _reformat_phonenumbers(self, vals, countrycode):
  92. for field in self._phone_fields:
  93. if vals.get(field):
  94. init_value = vals.get(field)
  95. try:
  96. res_parse = phonenumbers.parse(
  97. vals.get(field), countrycode.upper())
  98. vals[field] = phonenumbers.format_number(
  99. res_parse, phonenumbers.PhoneNumberFormat.E164)
  100. if init_value != vals[field]:
  101. _logger.info(
  102. "%s initial value: '%s' updated value: '%s'"
  103. % (field, init_value, vals[field]))
  104. except Exception, e:
  105. # I do BOTH logger and raise, because:
  106. # raise is usefull when the record is created/written
  107. # by a user via the Web interface
  108. # logger is usefull when the record is created/written
  109. # via the webservices
  110. _logger.error(
  111. "Cannot reformat the phone number '%s' to "
  112. "international format with region=%s",
  113. vals.get(field), countrycode)
  114. if self.env.context.get('raise_if_phone_parse_fails'):
  115. raise UserError(
  116. _("Cannot reformat the phone number '%s' to "
  117. "international format. Error message: %s")
  118. % (vals.get(field), e))
  119. return vals
  120. @api.model
  121. def get_name_from_phone_number(self, presented_number):
  122. '''Function to get name from phone number. Usefull for use from IPBX
  123. to add CallerID name to incoming calls.'''
  124. res = self.get_record_from_phone_number(presented_number)
  125. if res:
  126. return res[2]
  127. else:
  128. return False
  129. @api.model
  130. def get_record_from_phone_number(self, presented_number):
  131. '''If it finds something, it returns (object name, ID, record name)
  132. For example : ('res.partner', 42, u'Alexis de Lattre (Akretion)')
  133. '''
  134. _logger.debug(
  135. u"Call get_name_from_phone_number with number = %s"
  136. % presented_number)
  137. if not isinstance(presented_number, (str, unicode)):
  138. _logger.warning(
  139. u"Number '%s' should be a 'str' or 'unicode' but it is a '%s'"
  140. % (presented_number, type(presented_number)))
  141. return False
  142. if not presented_number.isdigit():
  143. _logger.warning(
  144. u"Number '%s' should only contain digits." % presented_number)
  145. nr_digits_to_match_from_end = \
  146. self.env.user.company_id.number_of_digits_to_match_from_end
  147. if len(presented_number) >= nr_digits_to_match_from_end:
  148. end_number_to_match = presented_number[
  149. -nr_digits_to_match_from_end:len(presented_number)]
  150. else:
  151. end_number_to_match = presented_number
  152. phoneobjects = self._get_phone_fields()
  153. phonefieldslist = [] # [('res.parter', 10), ('crm.lead', 20)]
  154. for objname in phoneobjects:
  155. if (
  156. '_phone_name_sequence' in dir(self.env[objname]) and
  157. self.env[objname]._phone_name_sequence):
  158. phonefieldslist.append(
  159. (objname, self.env[objname]._phone_name_sequence))
  160. phonefieldslist_sorted = sorted(
  161. phonefieldslist,
  162. key=lambda element: element[1])
  163. _logger.debug('phonefieldslist_sorted=%s' % phonefieldslist_sorted)
  164. for (objname, prio) in phonefieldslist_sorted:
  165. obj = self.with_context(callerid=True).env[objname]
  166. pg_search_number = str('%' + end_number_to_match)
  167. _logger.debug(
  168. "Will search phone and mobile numbers in %s ending with '%s'"
  169. % (objname, end_number_to_match))
  170. domain = []
  171. for phonefield in obj._phone_fields:
  172. domain.append((phonefield, '=like', pg_search_number))
  173. if len(obj._phone_fields) > 1:
  174. domain = ['|'] * (len(obj._phone_fields) - 1) + domain
  175. res_obj = obj.search(domain)
  176. if len(res_obj) > 1:
  177. _logger.warning(
  178. u"There are several %s (IDS = %s) with a phone number "
  179. "ending with '%s'. Taking the first one."
  180. % (objname, res_obj.ids, end_number_to_match))
  181. res_obj = res_obj[0]
  182. if res_obj:
  183. name = res_obj.name_get()[0][1]
  184. res = (objname, res_obj.id, name)
  185. _logger.debug(
  186. u"Answer get_record_from_phone_number: (%s, %d, %s)"
  187. % (res[0], res[1], res[2]))
  188. return res
  189. else:
  190. _logger.debug(
  191. u"No match on %s for end of phone number '%s'"
  192. % (objname, end_number_to_match))
  193. return False
  194. @api.model
  195. def _get_phone_fields(self):
  196. '''Returns a dict with key = object name
  197. and value = list of phone fields'''
  198. models = self.env['ir.model'].search([('transient', '=', False)])
  199. res = []
  200. for model in models:
  201. senv = False
  202. try:
  203. senv = self.env[model.model]
  204. except:
  205. continue
  206. if (
  207. '_phone_fields' in dir(senv) and
  208. isinstance(senv._phone_fields, list)):
  209. res.append(model.model)
  210. return res
  211. @api.model
  212. def click2dial(self, erp_number):
  213. '''This function is designed to be overridden in IPBX-specific
  214. modules, such as asterisk_click2dial or ovh_telephony_connector'''
  215. return {'dialed_number': erp_number}
  216. @api.model
  217. def convert_to_dial_number(self, erp_number):
  218. '''
  219. This function is dedicated to the transformation of the number
  220. available in Odoo to the number that can be dialed.
  221. You may have to inherit this function in another module specific
  222. for your company if you are not happy with the way I reformat
  223. the numbers.
  224. '''
  225. assert(erp_number), 'Missing phone number'
  226. _logger.debug('Number before reformat = %s' % erp_number)
  227. # erp_number are supposed to be in E.164 format, so no need to
  228. # give a country code here
  229. parsed_num = phonenumbers.parse(erp_number, None)
  230. country_code = self.env.user.company_id.country_id.code
  231. assert(country_code), 'Missing country on company'
  232. _logger.debug('Country code = %s' % country_code)
  233. to_dial_number = phonenumbers.format_out_of_country_calling_number(
  234. parsed_num, country_code.upper())
  235. to_dial_number = str(to_dial_number).translate(None, ' -.()/')
  236. _logger.debug('Number to be sent to phone system: %s' % to_dial_number)
  237. return to_dial_number
  238. class ResPartner(models.Model):
  239. _name = 'res.partner'
  240. _inherit = ['res.partner', 'phone.common']
  241. _phone_fields = ['phone', 'mobile', 'fax']
  242. _phone_name_sequence = 10
  243. _country_field = 'country_id'
  244. _partner_field = None
  245. @api.model
  246. def create(self, vals):
  247. vals_reformated = self._reformat_phonenumbers_create(vals)
  248. return super(ResPartner, self).create(vals_reformated)
  249. @api.multi
  250. def write(self, vals):
  251. vals_reformated = self._reformat_phonenumbers_write(vals)
  252. return super(ResPartner, self).write(vals_reformated)
  253. @api.multi
  254. def name_get(self):
  255. if self._context.get('callerid'):
  256. res = []
  257. for partner in self:
  258. if partner.parent_id and partner.parent_id.is_company:
  259. name = u'%s (%s)' % (partner.name, partner.parent_id.name)
  260. else:
  261. name = partner.name
  262. res.append((partner.id, name))
  263. return res
  264. else:
  265. return super(ResPartner, self).name_get()
  266. class ResCompany(models.Model):
  267. _inherit = 'res.company'
  268. number_of_digits_to_match_from_end = fields.Integer(
  269. string='Number of Digits To Match From End',
  270. default=8,
  271. help="In several situations, OpenERP will have to find a "
  272. "Partner/Lead/Employee/... from a phone number presented by the "
  273. "calling party. As the phone numbers presented by your phone "
  274. "operator may not always be displayed in a standard format, "
  275. "the best method to find the related Partner/Lead/Employee/... "
  276. "in OpenERP is to try to match the end of the phone number in "
  277. "OpenERP with the N last digits of the phone number presented "
  278. "by the calling party. N is the value you should enter in this "
  279. "field.")
  280. _sql_constraints = [(
  281. 'number_of_digits_to_match_from_end_positive',
  282. 'CHECK (number_of_digits_to_match_from_end > 0)',
  283. "The value of the field 'Number of Digits To Match From End' must "
  284. "be positive."),
  285. ]