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.

265 lines
11 KiB

  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(
  58. self, cr, uid, vals,
  59. phonefields=[
  60. 'phone', 'partner_phone', 'work_phone', 'fax',
  61. 'mobile', 'partner_mobile', 'mobile_phone',
  62. ],
  63. context=None):
  64. """Reformat phone numbers in E.164 format i.e. +33141981242"""
  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. raise orm.except_orm(
  88. _('Error :'),
  89. _("Cannot reformat the phone number '%s' to "
  90. "international format. Error message: %s")
  91. % (vals.get(field), e))
  92. vals[field] = phonenumbers.format_number(
  93. res_parse, phonenumbers.PhoneNumberFormat.E164)
  94. if init_value != vals[field]:
  95. _logger.info(
  96. "%s initial value: '%s' updated value: '%s'"
  97. % (field, init_value, vals[field]))
  98. return vals
  99. def get_name_from_phone_number(
  100. self, cr, uid, presented_number, context=None):
  101. '''Function to get name from phone number. Usefull for use from IPBX
  102. to add CallerID name to incoming calls.'''
  103. res = self.get_record_from_phone_number(
  104. cr, uid, presented_number, context=context)
  105. if res:
  106. return res[2]
  107. else:
  108. return False
  109. def get_record_from_phone_number(
  110. self, cr, uid, presented_number, context=None):
  111. '''If it finds something, it returns (object name, ID, record name)
  112. For example : ('res.partner', 42, u'Alexis de Lattre (Akretion)')
  113. '''
  114. if context is None:
  115. context = {}
  116. ctx_phone = context.copy()
  117. ctx_phone['callerid'] = True
  118. _logger.debug(
  119. u"Call get_name_from_phone_number with number = %s"
  120. % presented_number)
  121. if not isinstance(presented_number, (str, unicode)):
  122. _logger.warning(
  123. u"Number '%s' should be a 'str' or 'unicode' but it is a '%s'"
  124. % (presented_number, type(presented_number)))
  125. return False
  126. if not presented_number.isdigit():
  127. _logger.warning(
  128. u"Number '%s' should only contain digits." % presented_number)
  129. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  130. nr_digits_to_match_from_end = \
  131. user.company_id.number_of_digits_to_match_from_end
  132. if len(presented_number) >= nr_digits_to_match_from_end:
  133. end_number_to_match = presented_number[
  134. -nr_digits_to_match_from_end:len(presented_number)]
  135. else:
  136. end_number_to_match = presented_number
  137. phonefieldsdict = self._get_phone_fields(cr, uid, context=context)
  138. phonefieldslist = []
  139. for objname, prop in phonefieldsdict.iteritems():
  140. if prop.get('get_name_sequence'):
  141. phonefieldslist.append({objname: prop})
  142. phonefieldslist_sorted = sorted(
  143. phonefieldslist,
  144. key=lambda element: element.values()[0]['get_name_sequence'])
  145. for phonedict in phonefieldslist_sorted:
  146. objname = phonedict.keys()[0]
  147. prop = phonedict.values()[0]
  148. phonefields = prop['phonefields']
  149. obj = self.pool[objname]
  150. pg_search_number = str('%' + end_number_to_match)
  151. _logger.debug(
  152. "Will search phone and mobile numbers in %s ending with '%s'"
  153. % (objname, end_number_to_match))
  154. domain = []
  155. for phonefield in phonefields:
  156. domain.append((phonefield, 'like', pg_search_number))
  157. if len(phonefields) > 1:
  158. domain = ['|'] * (len(phonefields) - 1) + domain
  159. res_ids = obj.search(cr, uid, domain, context=context)
  160. if len(res_ids) > 1:
  161. _logger.warning(
  162. u"There are several %s (IDS = %s) with a phone number "
  163. "ending with '%s'. Taking the first one."
  164. % (objname, res_ids, end_number_to_match))
  165. if res_ids:
  166. name = obj.name_get(
  167. cr, uid, res_ids[0], context=ctx_phone)[0][1]
  168. res = (objname, res_ids[0], name)
  169. print "res=", res
  170. _logger.debug(
  171. u"Answer get_record_from_phone_number: (%s, %d, %s)"
  172. % (res[0], res[1], res[2]))
  173. return res
  174. else:
  175. _logger.debug(
  176. u"No match on %s for end of phone number '%s'"
  177. % (objname, end_number_to_match))
  178. return False
  179. def _get_phone_fields(self, cr, uid, context=None):
  180. '''Returns a dict with key = object name
  181. and value = list of phone fields'''
  182. res = {
  183. 'res.partner': {
  184. 'phonefields': ['phone', 'mobile'],
  185. 'faxfields': ['fax'],
  186. 'get_name_sequence': 10,
  187. },
  188. }
  189. return res
  190. class res_partner(orm.Model):
  191. _name = 'res.partner'
  192. _inherit = ['res.partner', 'phone.common']
  193. def create(self, cr, uid, vals, context=None):
  194. vals_reformated = self._generic_reformat_phonenumbers(
  195. cr, uid, vals, context=context)
  196. return super(res_partner, self).create(
  197. cr, uid, vals_reformated, context=context)
  198. def write(self, cr, uid, ids, vals, context=None):
  199. vals_reformated = self._generic_reformat_phonenumbers(
  200. cr, uid, vals, context=context)
  201. return super(res_partner, self).write(
  202. cr, uid, ids, vals_reformated, context=context)
  203. def name_get(self, cr, uid, ids, context=None):
  204. if context is None:
  205. context = {}
  206. if context.get('callerid'):
  207. res = []
  208. if isinstance(ids, (int, long)):
  209. ids = [ids]
  210. for partner in self.browse(cr, uid, ids, context=context):
  211. if partner.parent_id and partner.parent_id.is_company:
  212. name = u'%s (%s)' % (partner.name, partner.parent_id.name)
  213. else:
  214. name = partner.name
  215. res.append((partner.id, name))
  216. return res
  217. else:
  218. return super(res_partner, self).name_get(
  219. cr, uid, ids, context=context)
  220. class res_company(orm.Model):
  221. _inherit = 'res.company'
  222. _columns = {
  223. 'number_of_digits_to_match_from_end': fields.integer(
  224. 'Number of Digits To Match From End',
  225. help="In several situations, OpenERP will have to find a "
  226. "Partner/Lead/Employee/... from a phone number presented by the "
  227. "calling party. As the phone numbers presented by your phone "
  228. "operator may not always be displayed in a standard format, "
  229. "the best method to find the related Partner/Lead/Employee/... "
  230. "in OpenERP is to try to match the end of the phone number in "
  231. "OpenERP with the N last digits of the phone number presented "
  232. "by the calling party. N is the value you should enter in this "
  233. "field."),
  234. }
  235. _defaults = {
  236. 'number_of_digits_to_match_from_end': 8,
  237. }
  238. _sql_constraints = [(
  239. 'number_of_digits_to_match_from_end_positive',
  240. 'CHECK (number_of_digits_to_match_from_end > 0)',
  241. "The value of the field 'Number of Digits To Match From End' must "
  242. "be positive."),
  243. ]