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.

277 lines
12 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.osv import orm, fields
  22. from openerp.tools.translate import _
  23. import logging
  24. # Lib for phone number reformating -> pip install phonenumbers
  25. import phonenumbers
  26. _logger = logging.getLogger(__name__)
  27. class phone_common(orm.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 phonefields is None:
  61. phonefields = [
  62. 'phone', 'partner_phone', 'work_phone', 'fax',
  63. 'mobile', 'partner_mobile', 'mobile_phone',
  64. ]
  65. if any([vals.get(field) for field in phonefields]):
  66. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  67. # country_id on res.company is a fields.function that looks at
  68. # company_id.partner_id.addres(default).country_id
  69. if user.company_id.country_id:
  70. user_countrycode = user.company_id.country_id.code
  71. else:
  72. # We need to raise an exception here because, if we pass None
  73. # as second arg of phonenumbers.parse(), it will raise an
  74. # exception when you try to enter a phone number in
  75. # national format... so it's better to raise the exception here
  76. raise orm.except_orm(
  77. _('Error:'),
  78. _("You should set a country on the company '%s'")
  79. % user.company_id.name)
  80. for field in phonefields:
  81. if vals.get(field):
  82. init_value = vals.get(field)
  83. try:
  84. res_parse = phonenumbers.parse(
  85. vals.get(field), user_countrycode)
  86. except Exception, e:
  87. # I do BOTH logger and raise, because:
  88. # raise is usefull when the record is created/written
  89. # by a user via the Web interface
  90. # logger is usefull when the record is created/written
  91. # via the webservices
  92. _logger.error(
  93. "Cannot reformat the phone number %s to "
  94. "international format" % vals.get(field))
  95. raise orm.except_orm(
  96. _('Error:'),
  97. _("Cannot reformat the phone number '%s' to "
  98. "international format. Error message: %s")
  99. % (vals.get(field), e))
  100. vals[field] = phonenumbers.format_number(
  101. res_parse, phonenumbers.PhoneNumberFormat.E164)
  102. if init_value != vals[field]:
  103. _logger.info(
  104. "%s initial value: '%s' updated value: '%s'"
  105. % (field, init_value, vals[field]))
  106. return vals
  107. def get_name_from_phone_number(
  108. self, cr, uid, presented_number, context=None):
  109. '''Function to get name from phone number. Usefull for use from IPBX
  110. to add CallerID name to incoming calls.'''
  111. res = self.get_record_from_phone_number(
  112. cr, uid, presented_number, context=context)
  113. if res:
  114. return res[2]
  115. else:
  116. return False
  117. def get_record_from_phone_number(
  118. self, cr, uid, presented_number, context=None):
  119. '''If it finds something, it returns (object name, ID, record name)
  120. For example : ('res.partner', 42, u'Alexis de Lattre (Akretion)')
  121. '''
  122. if context is None:
  123. context = {}
  124. ctx_phone = context.copy()
  125. ctx_phone['callerid'] = True
  126. _logger.debug(
  127. u"Call get_name_from_phone_number with number = %s"
  128. % presented_number)
  129. if not isinstance(presented_number, (str, unicode)):
  130. _logger.warning(
  131. u"Number '%s' should be a 'str' or 'unicode' but it is a '%s'"
  132. % (presented_number, type(presented_number)))
  133. return False
  134. if not presented_number.isdigit():
  135. _logger.warning(
  136. u"Number '%s' should only contain digits." % presented_number)
  137. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  138. nr_digits_to_match_from_end = \
  139. user.company_id.number_of_digits_to_match_from_end
  140. if len(presented_number) >= nr_digits_to_match_from_end:
  141. end_number_to_match = presented_number[
  142. -nr_digits_to_match_from_end:len(presented_number)]
  143. else:
  144. end_number_to_match = presented_number
  145. phonefieldsdict = self._get_phone_fields(cr, uid, context=context)
  146. phonefieldslist = []
  147. for objname, prop in phonefieldsdict.iteritems():
  148. if prop.get('get_name_sequence'):
  149. phonefieldslist.append({objname: prop})
  150. phonefieldslist_sorted = sorted(
  151. phonefieldslist,
  152. key=lambda element: element.values()[0]['get_name_sequence'])
  153. for phonedict in phonefieldslist_sorted:
  154. objname = phonedict.keys()[0]
  155. prop = phonedict.values()[0]
  156. phonefields = prop['phonefields']
  157. obj = self.pool[objname]
  158. pg_search_number = str('%' + end_number_to_match)
  159. _logger.debug(
  160. "Will search phone and mobile numbers in %s ending with '%s'"
  161. % (objname, end_number_to_match))
  162. domain = []
  163. for phonefield in phonefields:
  164. domain.append((phonefield, '=like', pg_search_number))
  165. if len(phonefields) > 1:
  166. domain = ['|'] * (len(phonefields) - 1) + domain
  167. res_ids = obj.search(cr, uid, domain, context=context)
  168. if len(res_ids) > 1:
  169. _logger.warning(
  170. u"There are several %s (IDS = %s) with a phone number "
  171. "ending with '%s'. Taking the first one."
  172. % (objname, res_ids, end_number_to_match))
  173. if res_ids:
  174. name = obj.name_get(
  175. cr, uid, res_ids[0], context=ctx_phone)[0][1]
  176. res = (objname, res_ids[0], name)
  177. _logger.debug(
  178. u"Answer get_record_from_phone_number: (%s, %d, %s)"
  179. % (res[0], res[1], res[2]))
  180. return res
  181. else:
  182. _logger.debug(
  183. u"No match on %s for end of phone number '%s'"
  184. % (objname, end_number_to_match))
  185. return False
  186. def _get_phone_fields(self, cr, uid, context=None):
  187. '''Returns a dict with key = object name
  188. and value = list of phone fields'''
  189. res = {
  190. 'res.partner': {
  191. 'phonefields': ['phone', 'mobile'],
  192. 'faxfields': ['fax'],
  193. 'get_name_sequence': 10,
  194. },
  195. }
  196. return res
  197. def click2dial(self, cr, uid, erp_number, context=None):
  198. '''This function is designed to be overridden in IPBX-specific
  199. modules, such as asterisk_click2dial'''
  200. return {'dialed_number': erp_number}
  201. class res_partner(orm.Model):
  202. _name = 'res.partner'
  203. _inherit = ['res.partner', 'phone.common']
  204. def create(self, cr, uid, vals, context=None):
  205. vals_reformated = self._generic_reformat_phonenumbers(
  206. cr, uid, vals, context=context)
  207. return super(res_partner, self).create(
  208. cr, uid, vals_reformated, context=context)
  209. def write(self, cr, uid, ids, vals, context=None):
  210. vals_reformated = self._generic_reformat_phonenumbers(
  211. cr, uid, vals, context=context)
  212. return super(res_partner, self).write(
  213. cr, uid, ids, vals_reformated, context=context)
  214. def name_get(self, cr, uid, ids, context=None):
  215. if context is None:
  216. context = {}
  217. if context.get('callerid'):
  218. res = []
  219. if isinstance(ids, (int, long)):
  220. ids = [ids]
  221. for partner in self.browse(cr, uid, ids, context=context):
  222. if partner.parent_id and partner.parent_id.is_company:
  223. name = u'%s (%s)' % (partner.name, partner.parent_id.name)
  224. else:
  225. name = partner.name
  226. res.append((partner.id, name))
  227. return res
  228. else:
  229. return super(res_partner, self).name_get(
  230. cr, uid, ids, context=context)
  231. class res_company(orm.Model):
  232. _inherit = 'res.company'
  233. _columns = {
  234. 'number_of_digits_to_match_from_end': fields.integer(
  235. 'Number of Digits To Match From End',
  236. help="In several situations, OpenERP will have to find a "
  237. "Partner/Lead/Employee/... from a phone number presented by the "
  238. "calling party. As the phone numbers presented by your phone "
  239. "operator may not always be displayed in a standard format, "
  240. "the best method to find the related Partner/Lead/Employee/... "
  241. "in OpenERP is to try to match the end of the phone number in "
  242. "OpenERP with the N last digits of the phone number presented "
  243. "by the calling party. N is the value you should enter in this "
  244. "field."),
  245. }
  246. _defaults = {
  247. 'number_of_digits_to_match_from_end': 8,
  248. }
  249. _sql_constraints = [(
  250. 'number_of_digits_to_match_from_end_positive',
  251. 'CHECK (number_of_digits_to_match_from_end > 0)',
  252. "The value of the field 'Number of Digits To Match From End' must "
  253. "be positive."),
  254. ]