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.

310 lines
14 KiB

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