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.

297 lines
13 KiB

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