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.

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