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.

279 lines
12 KiB

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.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. raise_if_parse_fails=False,
  59. context=None):
  60. """Reformat phone numbers in E.164 format i.e. +33141981242"""
  61. if phonefields is None:
  62. phonefields = [
  63. 'phone', 'partner_phone', 'work_phone', 'fax',
  64. 'mobile', 'partner_mobile', 'mobile_phone',
  65. ]
  66. if any([vals.get(field) for field in phonefields]):
  67. user = self.pool['res.users'].browse(cr, uid, uid, context=context)
  68. # country_id on res.company is a fields.function that looks at
  69. # company_id.partner_id.addres(default).country_id
  70. if user.company_id.country_id:
  71. user_countrycode = user.company_id.country_id.code
  72. else:
  73. # We need to raise an exception here because, if we pass None
  74. # as second arg of phonenumbers.parse(), it will raise an
  75. # exception when you try to enter a phone number in
  76. # national format... so it's better to raise the exception here
  77. raise orm.except_orm(
  78. _('Error:'),
  79. _("You should set a country on the company '%s'")
  80. % user.company_id.name)
  81. for field in phonefields:
  82. if vals.get(field):
  83. init_value = vals.get(field)
  84. try:
  85. res_parse = phonenumbers.parse(
  86. vals.get(field), user_countrycode)
  87. vals[field] = phonenumbers.format_number(
  88. res_parse, phonenumbers.PhoneNumberFormat.E164)
  89. if init_value != vals[field]:
  90. _logger.info(
  91. "%s initial value: '%s' updated value: '%s'"
  92. % (field, init_value, vals[field]))
  93. except Exception, e:
  94. # I do BOTH logger and raise, because:
  95. # raise is usefull when the record is created/written
  96. # by a user via the Web interface
  97. # logger is usefull when the record is created/written
  98. # via the webservices
  99. _logger.error(
  100. "Cannot reformat the phone number '%s' to "
  101. "international format" % vals.get(field))
  102. if raise_if_parse_fails:
  103. raise orm.except_orm(
  104. _('Error:'),
  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. class res_partner(orm.Model):
  204. _name = 'res.partner'
  205. _inherit = ['res.partner', 'phone.common']
  206. def create(self, cr, uid, vals, context=None):
  207. vals_reformated = self._generic_reformat_phonenumbers(
  208. cr, uid, vals, context=context)
  209. return super(res_partner, self).create(
  210. cr, uid, vals_reformated, context=context)
  211. def write(self, cr, uid, ids, vals, context=None):
  212. vals_reformated = self._generic_reformat_phonenumbers(
  213. cr, uid, vals, context=context)
  214. return super(res_partner, self).write(
  215. cr, uid, ids, vals_reformated, context=context)
  216. def name_get(self, cr, uid, ids, context=None):
  217. if context is None:
  218. context = {}
  219. if context.get('callerid'):
  220. res = []
  221. if isinstance(ids, (int, long)):
  222. ids = [ids]
  223. for partner in self.browse(cr, uid, ids, context=context):
  224. if partner.parent_id and partner.parent_id.is_company:
  225. name = u'%s (%s)' % (partner.name, partner.parent_id.name)
  226. else:
  227. name = partner.name
  228. res.append((partner.id, name))
  229. return res
  230. else:
  231. return super(res_partner, self).name_get(
  232. cr, uid, ids, context=context)
  233. class res_company(orm.Model):
  234. _inherit = 'res.company'
  235. _columns = {
  236. 'number_of_digits_to_match_from_end': fields.integer(
  237. 'Number of Digits To Match From End',
  238. help="In several situations, OpenERP will have to find a "
  239. "Partner/Lead/Employee/... from a phone number presented by the "
  240. "calling party. As the phone numbers presented by your phone "
  241. "operator may not always be displayed in a standard format, "
  242. "the best method to find the related Partner/Lead/Employee/... "
  243. "in OpenERP is to try to match the end of the phone number in "
  244. "OpenERP with the N last digits of the phone number presented "
  245. "by the calling party. N is the value you should enter in this "
  246. "field."),
  247. }
  248. _defaults = {
  249. 'number_of_digits_to_match_from_end': 8,
  250. }
  251. _sql_constraints = [(
  252. 'number_of_digits_to_match_from_end_positive',
  253. 'CHECK (number_of_digits_to_match_from_end > 0)',
  254. "The value of the field 'Number of Digits To Match From End' must "
  255. "be positive."),
  256. ]