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.

668 lines
36 KiB

13 years ago
  1. # -*- encoding: utf-8 -*-
  2. ##############################################################################
  3. #
  4. # Asterisk Click2dial module for OpenERP
  5. # Copyright (C) 2010-2012 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 osv import osv, fields
  22. # Lib required to open a socket (needed to communicate with Asterisk server)
  23. import socket
  24. # Lib required to print logs
  25. import logging
  26. # Lib to translate error messages
  27. from tools.translate import _
  28. # Lib for regexp
  29. import re
  30. _logger = logging.getLogger(__name__)
  31. class asterisk_server(osv.osv):
  32. '''Asterisk server object, to store all the parameters of the Asterisk IPBXs'''
  33. _name = "asterisk.server"
  34. _description = "Asterisk Servers"
  35. _columns = {
  36. 'name': fields.char('Asterisk server name', size=50, required=True, help="Asterisk server name."),
  37. 'active': fields.boolean('Active', help="The active field allows you to hide the Asterisk server without deleting it."),
  38. 'ip_address': fields.char('Asterisk IP addr. or DNS', size=50, required=True, help="IP address or DNS name of the Asterisk server."),
  39. 'port': fields.integer('Port', required=True, help="TCP port on which the Asterisk Manager Interface listens. Defined in /etc/asterisk/manager.conf on Asterisk."),
  40. 'out_prefix': fields.char('Out prefix', size=4, help="Prefix to dial to place outgoing calls. If you don't use a prefix to place outgoing calls, leave empty."),
  41. 'national_prefix': fields.char('National prefix', size=4, help="Prefix for national phone calls (don't include the 'out prefix'). For e.g., in France, the phone numbers look like '01 41 98 12 42' : the National prefix is '0'."),
  42. 'international_prefix': fields.char('International prefix', required=True, size=4, help="Prefix to add to make international phone calls (don't include the 'out prefix'). For e.g., in France, the International prefix is '00'."),
  43. 'country_prefix': fields.char('My country prefix', required=True, size=4, help="Phone prefix of the country where the Asterisk server is located. For e.g. the phone prefix for France is '33'. If the phone number to dial starts with the 'My country prefix', OpenERP will remove the country prefix from the phone number and add the 'out prefix' followed by the 'national prefix'. If the phone number to dial doesn't start with the 'My country prefix', OpenERP will add the 'out prefix' followed by the 'international prefix'."),
  44. 'national_format_allowed': fields.boolean('National format allowed ?', help="Do we allow to use click2dial on phone numbers written in national format, e.g. 01 41 98 12 42, or only in the international format, e.g. +33 1 41 98 12 42 ?"),
  45. 'login': fields.char('AMI login', size=30, required=True, help="Login that OpenERP will use to communicate with the Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf on your Asterisk server."),
  46. 'password': fields.char('AMI password', size=30, required=True, help="Password that Asterisk will use to communicate with the Asterisk Manager Interface. Refer to /etc/asterisk/manager.conf on your Asterisk server."),
  47. 'context': fields.char('Dialplan context', size=50, required=True, help="Asterisk dialplan context from which the calls will be made. Refer to /etc/asterisk/extensions.conf on your Asterisk server."),
  48. 'wait_time': fields.integer('Wait time (sec)', required=True, help="Amount of time (in seconds) Asterisk will try to reach the user's phone before hanging up."),
  49. 'extension_priority': fields.integer('Extension priority', required=True, help="Priority of the extension in the Asterisk dialplan. Refer to /etc/asterisk/extensions.conf on your Asterisk server."),
  50. 'alert_info': fields.char('Alert-Info SIP header', size=255, help="Set Alert-Info header in SIP request to user's IP Phone for the click2dial feature. If empty, the Alert-Info header will not be added. You can use it to have a special ring tone for click2dial (a silent one !) or to activate auto-answer for example. If you want to have several variable headers, separate them with '|'."),
  51. 'company_id': fields.many2one('res.company', 'Company', help="Company who uses the Asterisk server."),
  52. }
  53. _defaults = {
  54. 'active': True,
  55. 'port': 5038, # Default AMI port
  56. 'out_prefix': '0',
  57. 'national_prefix': '0',
  58. 'international_prefix': '00',
  59. 'extension_priority': 1,
  60. 'wait_time': 15,
  61. }
  62. def _check_validity(self, cr, uid, ids):
  63. for server in self.browse(cr, uid, ids):
  64. country_prefix = ('Country prefix', server.country_prefix)
  65. international_prefix = ('International prefix', server.international_prefix)
  66. out_prefix = ('Out prefix', server.out_prefix)
  67. national_prefix = ('National prefix', server.national_prefix)
  68. dialplan_context = ('Dialplan context', server.context)
  69. alert_info = ('Alert-Info SIP header', server.alert_info)
  70. login = ('AMI login', server.login)
  71. password = ('AMI password', server.password)
  72. for digit_prefix in [country_prefix, international_prefix, out_prefix, national_prefix]:
  73. if digit_prefix[1] and not digit_prefix[1].isdigit():
  74. raise osv.except_osv(_('Error :'), _("Only use digits for the '%s' on the Asterisk server '%s'" % (digit_prefix[0], server.name)))
  75. if server.wait_time < 1 or server.wait_time > 120:
  76. raise osv.except_osv(_('Error :'), _("You should set a 'Wait time' value between 1 and 120 seconds for the Asterisk server '%s'" % server.name))
  77. if server.extension_priority < 1:
  78. raise osv.except_osv(_('Error :'), _("The 'extension priority' must be a positive value for the Asterisk server '%s'" % server.name))
  79. if server.port > 65535 or server.port < 1:
  80. raise osv.except_osv(_('Error :'), _("You should set a TCP port between 1 and 65535 for the Asterik server '%s'" % server.name))
  81. for check_string in [dialplan_context, alert_info, login, password]:
  82. if check_string[1]:
  83. try:
  84. string = check_string[1].encode('ascii')
  85. except UnicodeEncodeError:
  86. raise osv.except_osv(_('Error :'), _("The '%s' should only have ASCII caracters for the Asterisk server '%s'" % (check_string[0], server.name)))
  87. return True
  88. _constraints = [
  89. (_check_validity, "Error message in raise", ['out_prefix', 'country_prefix', 'national_prefix', 'international_prefix', 'wait_time', 'extension_priority', 'port', 'context', 'alert_info', 'login', 'password']),
  90. ]
  91. def _reformat_number(self, cr, uid, erp_number, ast_server, context=None):
  92. '''
  93. This function is dedicated to the transformation of the number
  94. available in OpenERP to the number that Asterisk should dial.
  95. You may have to inherit this function in another module specific
  96. for your company if you are not happy with the way I reformat
  97. the OpenERP numbers.
  98. '''
  99. error_title_msg = _("Invalid phone number")
  100. invalid_international_format_msg = _("The phone number is not written in valid international format. Example of valid international format : +33 1 41 98 12 42")
  101. invalid_national_format_msg = _("The phone number is not written in valid national format.")
  102. invalid_format_msg = _("The phone number is not written in valid format.")
  103. # Let's call the variable tmp_number now
  104. tmp_number = erp_number
  105. _logger.debug('Number before reformat = %s' % tmp_number)
  106. # Check if empty
  107. if not tmp_number:
  108. raise osv.except_osv(error_title_msg, invalid_format_msg)
  109. # First, we remove all stupid caracters and spaces
  110. for char_to_remove in [' ', '.', '(', ')', '[', ']', '-', '/']:
  111. tmp_number = tmp_number.replace(char_to_remove, '')
  112. # Before starting to use prefix, we convert empty prefix whose value
  113. # is False to an empty string
  114. country_prefix = (ast_server.country_prefix or '')
  115. national_prefix = (ast_server.national_prefix or '')
  116. international_prefix = (ast_server.international_prefix or '')
  117. out_prefix = (ast_server.out_prefix or '')
  118. # International format
  119. if tmp_number[0] == '+':
  120. # Remove the starting '+' of the number
  121. tmp_number = tmp_number.replace('+','')
  122. _logger.debug('Number after removal of special char = %s' % tmp_number)
  123. # At this stage, 'tmp_number' should only contain digits
  124. if not tmp_number.isdigit():
  125. raise osv.except_osv(error_title_msg, invalid_format_msg)
  126. _logger.debug('Country prefix = %s' % country_prefix)
  127. if country_prefix == tmp_number[0:len(country_prefix)]:
  128. # If the number is a national number,
  129. # remove 'my country prefix' and add 'national prefix'
  130. tmp_number = (national_prefix) + tmp_number[len(country_prefix):len(tmp_number)]
  131. _logger.debug('National prefix = %s - Number with national prefix = %s' % (national_prefix, tmp_number))
  132. else:
  133. # If the number is an international number,
  134. # add 'international prefix'
  135. tmp_number = international_prefix + tmp_number
  136. _logger.debug('International prefix = %s - Number with international prefix = %s' % (international_prefix, tmp_number))
  137. # National format, allowed
  138. elif ast_server.national_format_allowed:
  139. # No treatment required
  140. if not tmp_number.isdigit():
  141. raise osv.except_osv(error_title_msg, invalid_national_format_msg)
  142. # National format, disallowed
  143. elif not ast_server.national_format_allowed:
  144. raise osv.except_osv(error_title_msg, invalid_international_format_msg)
  145. # Add 'out prefix' to all numbers
  146. tmp_number = out_prefix + tmp_number
  147. _logger.debug('Out prefix = %s - Number to be sent to Asterisk = %s' % (out_prefix, tmp_number))
  148. return tmp_number
  149. def _convert_number_to_international_format(self, cr, uid, number, ast_server, context=None):
  150. '''Convert the number presented by the phone network to a number
  151. in international format e.g. +33141981242'''
  152. if number and number.isdigit() and len(number) > 5:
  153. if ast_server.international_prefix and number[0:len(ast_server.international_prefix)] == ast_server.international_prefix:
  154. number = number[len(ast_server.international_prefix):]
  155. number = '+' + number
  156. elif ast_server.national_prefix and number[0:len(ast_server.national_prefix)] == ast_server.national_prefix:
  157. number = number[len(ast_server.national_prefix):]
  158. number = '+' + ast_server.country_prefix + number
  159. return number
  160. def _get_asterisk_server_from_user(self, cr, uid, user, context=None):
  161. '''Returns an asterisk.server browse object'''
  162. # We check if the user has an Asterisk server configured
  163. if user.asterisk_server_id.id:
  164. ast_server = user.asterisk_server_id
  165. else:
  166. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  167. # If no asterisk server is configured on the user, we take the first one
  168. if not asterisk_server_ids:
  169. raise osv.except_osv(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  170. else:
  171. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  172. return ast_server
  173. def _parse_asterisk_answer(self, cr, uid, sock, end_string='\r\n\r\n', context=None):
  174. '''Parse the answer of the Asterisk Manager Interface'''
  175. answer = ''
  176. data = ''
  177. while end_string not in data:
  178. data = sock.recv(1024)
  179. if data:
  180. answer += data
  181. # remove end_string from answer
  182. if answer[-len(end_string):] == end_string:
  183. answer = answer[:-len(end_string)]
  184. return answer
  185. def _connect_to_asterisk(self, cr, uid, method='dial', options=None, context=None):
  186. '''
  187. Open the socket to the Asterisk Manager Interface (AMI)
  188. and send instructions to Dial to Asterisk. That's the important function !
  189. '''
  190. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  191. # Note : if I write 'Error' without ' :', it won't get translated...
  192. # I don't understand why !
  193. ast_server = self._get_asterisk_server_from_user(cr, uid, user, context=context)
  194. # We check if the current user has a chan type
  195. if not user.asterisk_chan_type:
  196. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  197. # We check if the current user has an internal number
  198. if not user.internal_number:
  199. raise osv.except_osv(_('Error :'), _('No internal phone number configured for the current user'))
  200. _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.internal_number))
  201. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  202. # Connect to the Asterisk Manager Interface, using IPv6-ready code
  203. try:
  204. res = socket.getaddrinfo(str(ast_server.ip_address), ast_server.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  205. except:
  206. _logger.warning("Can't resolve the DNS of the Asterisk server '%s'" % ast_server.ip_address)
  207. raise osv.except_osv(_('Error :'), _("Can't resolve the DNS of the Asterisk server : '%s'" % ast_server.ip_address))
  208. for result in res:
  209. af, socktype, proto, canonname, sockaddr = result
  210. sock = socket.socket(af, socktype, proto)
  211. try:
  212. sock.connect(sockaddr)
  213. header_received = sock.recv(1024)
  214. _logger.debug('Header received from Asterisk : %s' % header_received)
  215. # Login to Asterisk
  216. login_act = 'Action: login\r\n' + \
  217. 'Events: off\r\n' + \
  218. 'Username: ' + ast_server.login + '\r\n' + \
  219. 'Secret: ' + ast_server.password + '\r\n\r\n'
  220. sock.send(login_act.encode('ascii'))
  221. login_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  222. if 'Response: Success' in login_answer:
  223. _logger.debug("Successful authentification to Asterisk :\n%s" % login_answer)
  224. else:
  225. raise osv.except_osv(_('Error :'), _("Authentification to Asterisk failed :\n%s" % login_answer))
  226. if method == 'dial':
  227. # Convert the phone number in the format that will be sent to Asterisk
  228. erp_number = options.get('erp_number')
  229. if not erp_number:
  230. raise osv.except_osv(_('Error :'), "Hara kiri : you must call the function with erp_number in the options")
  231. ast_number = self._reformat_number(cr, uid, erp_number, ast_server, context=context)
  232. # The user should have a CallerID
  233. if not user.callerid:
  234. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  235. # Dial with Asterisk
  236. originate_act = 'Action: originate\r\n' + \
  237. 'Channel: ' + user.asterisk_chan_type + '/' + user.internal_number + '\r\n' + \
  238. 'Priority: ' + str(ast_server.extension_priority) + '\r\n' + \
  239. 'Timeout: ' + str(ast_server.wait_time*1000) + '\r\n' + \
  240. 'CallerId: ' + user.callerid + '\r\n' + \
  241. 'Exten: ' + ast_number + '\r\n' + \
  242. 'Context: ' + ast_server.context + '\r\n'
  243. if ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  244. for server_alertinfo in ast_server.alert_info.split('|'):
  245. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + server_alertinfo.strip() + '\r\n'
  246. if user.alert_info and user.asterisk_chan_type == 'SIP':
  247. for user_alertinfo in user.alert_info.split('|'):
  248. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + user_alertinfo.strip() + '\r\n'
  249. if user.variable:
  250. for user_variable in user.variable.split('|'):
  251. originate_act += 'Variable: ' + user_variable.strip() + '\r\n'
  252. originate_act += '\r\n'
  253. sock.send(originate_act.encode('ascii'))
  254. originate_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  255. if 'Response: Success' in originate_answer:
  256. _logger.debug('Successfull originate command : %s' % originate_answer)
  257. else:
  258. raise osv.except_osv(_('Error :'), _("Click to dial with Asterisk failed :\n%s" % originate_answer))
  259. elif method == "get_calling_number":
  260. status_act = 'Action: Status\r\n\r\n' # TODO : add ActionID
  261. sock.send(status_act.encode('ascii'))
  262. status_answer = self._parse_asterisk_answer(cr, uid, sock, end_string='Event: StatusComplete', context=context)
  263. if 'Response: Success' in status_answer:
  264. _logger.debug('Successfull Status command :\n%s' % status_answer)
  265. else:
  266. raise osv.except_osv(_('Error :'), _("Status command to Asterisk failed :\n%s" % status_answer))
  267. # Parse answer
  268. calling_party_number = False
  269. status_answer_split = status_answer.split('\r\n\r\n')
  270. for event in status_answer_split:
  271. string_match = 'BridgedChannel: ' + user.asterisk_chan_type + '/' + user.internal_number
  272. if not string_match in event:
  273. continue
  274. event_split = event.split('\r\n')
  275. for event_line in event_split:
  276. if not 'CallerIDNum' in event_line:
  277. continue
  278. line_detail = event_line.split(': ')
  279. if len(line_detail) <> 2:
  280. raise osv.except_osv('Error :', "Hara kiri... this is not possible")
  281. calling_party_number = line_detail[1]
  282. # Logout of Asterisk
  283. sock.send(('Action: Logoff\r\n\r\n').encode('ascii'))
  284. logout_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  285. if 'Response: Goodbye' in logout_answer:
  286. _logger.debug('Successfull logout from Asterisk :\n%s' % logout_answer)
  287. else:
  288. _logger.warning('Logout from Asterisk failed :\n%s' % logout_answer)
  289. # we catch only network problems here
  290. except socket.error:
  291. _logger.warning("Unable to connect to the Asterisk server '%s' IP '%s:%d'" % (ast_server.name, ast_server.ip_address, ast_server.port))
  292. raise osv.except_osv(_('Error :'), _("The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk."))
  293. finally:
  294. sock.close()
  295. if method == 'dial':
  296. _logger.info("Asterisk Click2Dial from %s/%s to %s" % (user.asterisk_chan_type, user.internal_number, ast_number))
  297. return True
  298. elif method == "get_calling_number":
  299. _logger.debug("Calling party number: %s" % calling_party_number)
  300. return calling_party_number
  301. else:
  302. return False
  303. asterisk_server()
  304. # Parameters specific for each user
  305. class res_users(osv.osv):
  306. _inherit = "res.users"
  307. _columns = {
  308. 'internal_number': fields.char('Internal number', size=15,
  309. help="User's internal phone number."),
  310. 'callerid': fields.char('Caller ID', size=50,
  311. help="Caller ID used for the calls initiated by this user."),
  312. # You'd probably think : Asterisk should reuse the callerID of sip.conf !
  313. # But it cannot, cf http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  314. 'asterisk_chan_type': fields.selection([
  315. ('SIP', 'SIP'),
  316. ('IAX2', 'IAX2'),
  317. ('DAHDI', 'DAHDI'),
  318. ('Zap', 'Zap'),
  319. ('Skinny', 'Skinny'),
  320. ('MGCP', 'MGCP'),
  321. ('mISDN', 'mISDN'),
  322. ('H323', 'H323'),
  323. ], 'Asterisk channel type',
  324. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  325. 'alert_info': fields.char('User-specific Alert-Info SIP header', size=255, help="Set a user-specific Alert-Info header in SIP request to user's IP Phone for the click2dial feature. If empty, the Alert-Info header will not be added. You can use it to have a special ring tone for click2dial (a silent one !) or to activate auto-answer for example. If you want to have several variable headers, separate them with '|'."),
  326. 'variable': fields.char('User-specific Variable', size=255, help="Set a user-specific 'Variable' field in the Asterisk Manager Interface 'originate' request for the click2dial feature. If you want to have several variable headers, separate them with '|'."),
  327. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  328. help="Asterisk server on which the user's phone is connected. If you leave this field empty, it will use the first Asterisk server of the user's company."),
  329. }
  330. _defaults = {
  331. 'asterisk_chan_type': 'SIP',
  332. }
  333. def _check_validity(self, cr, uid, ids):
  334. for user in self.browse(cr, uid, ids):
  335. for check_string in [('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  336. if check_string[1]:
  337. try:
  338. plom = check_string[1].encode('ascii')
  339. except UnicodeEncodeError:
  340. raise osv.except_osv(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  341. return True
  342. _constraints = [
  343. (_check_validity, "Error message in raise", ['internal_number', 'callerid']),
  344. ]
  345. res_users()
  346. class res_partner_address(osv.osv):
  347. _inherit = "res.partner.address"
  348. def dial(self, cr, uid, ids, phone_field='phone', context=None):
  349. '''Read the number to dial and call _connect_to_asterisk the right way'''
  350. erp_number = self.read(cr, uid, ids, [phone_field], context=context)[0][phone_field]
  351. # Check if the number to dial is not empty
  352. if not erp_number:
  353. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  354. options = {'erp_number': erp_number}
  355. return self.pool.get('asterisk.server')._connect_to_asterisk(cr, uid, method='dial', options=options, context=context)
  356. def action_dial_phone(self, cr, uid, ids, context=None):
  357. '''Function called by the button 'Dial' next to the 'phone' field
  358. in the partner address view'''
  359. return self.dial(cr, uid, ids, phone_field='phone', context=context)
  360. def action_dial_mobile(self, cr, uid, ids, context=None):
  361. '''Function called by the button 'Dial' next to the 'mobile' field
  362. in the partner address view'''
  363. return self.dial(cr, uid, ids, phone_field='mobile', context=context)
  364. def get_name_from_phone_number(self, cr, uid, number, context=None):
  365. '''Function to get name from phone number. Usefull for use from Asterisk
  366. to add CallerID name to incoming calls.
  367. The "scripts/" subdirectory of this module has an AGI script that you can
  368. install on your Asterisk IPBX : the script will be called from the Asterisk
  369. dialplan via the AGI() function and it will use this function via an XML-RPC
  370. request.
  371. '''
  372. res = self.get_partner_from_phone_number(cr, uid, number, context=context)
  373. if res:
  374. return res[2]
  375. else:
  376. return False
  377. def get_partner_from_phone_number(self, cr, uid, number, context=None):
  378. res = {}
  379. # We check that "number" is really a number
  380. if not isinstance(number, str):
  381. return False
  382. if not number.isdigit():
  383. return False
  384. _logger.debug(u"Call get_name_from_phone_number with number = %s" % number)
  385. # Get all the partner addresses :
  386. all_ids = self.search(cr, uid, [], context=context)
  387. # For each partner address, we check if the number matches on the "phone" or "mobile" fields
  388. for entry in self.browse(cr, uid, all_ids, context=context):
  389. if entry.phone:
  390. # We use a regexp on the phone field to remove non-digit caracters
  391. if re.sub(r'\D', '', entry.phone).endswith(number):
  392. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  393. return (entry.id, entry.partner_id.id, entry.name)
  394. if entry.mobile:
  395. if re.sub(r'\D', '', entry.mobile).endswith(number):
  396. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  397. return (entry.id, entry.partner_id.id, entry.name)
  398. _logger.debug(u"No match for phone number %s" % number)
  399. return False
  400. res_partner_address()
  401. class wizard_open_calling_partner(osv.osv_memory):
  402. _name = "wizard.open.calling.partner"
  403. _description = "Open calling partner"
  404. _columns = {
  405. 'calling_number': fields.char('Calling number', size=30, readonly=True, help="Phone number of calling party that has been obtained from Asterisk."),
  406. 'partner_address_id': fields.many2one('res.partner.address', 'Contact name', readonly=True, help="Partner contact related to the calling number"),
  407. 'partner_id': fields.many2one('res.partner', 'Partner', readonly=True, help="Partner related to the calling number"),
  408. 'to_update_partner_address_id': fields.many2one('res.partner.address', 'Contact to update', help="Partner contact on which the phone or mobile number will be written"),
  409. 'current_phone': fields.related('to_update_partner_address_id', 'phone', type='char', relation='res.partner.address', string='Current phone', readonly=True),
  410. 'current_mobile': fields.related('to_update_partner_address_id', 'mobile', type='char', relation='res.partner.address', string='Current mobile', readonly=True),
  411. }
  412. def default_get(self, cr, uid, fields, context=None):
  413. '''Thanks to the default_get method, we are able to query Asterisk and
  414. get the corresponding partner when we launch the wizard'''
  415. res = {}
  416. calling_number = self.pool.get('asterisk.server')._connect_to_asterisk(cr, uid, method='get_calling_number', context=context)
  417. #To test the code without Asterisk server
  418. #calling_number = "0141981242"
  419. if calling_number:
  420. res['calling_number'] = calling_number
  421. # We match only on the end of the phone number
  422. if len(calling_number) >= 9:
  423. number_to_search = calling_number[-9:len(calling_number)]
  424. else:
  425. number_to_search = calling_number
  426. partner = self.pool.get('res.partner.address').get_partner_from_phone_number(cr, uid, number_to_search, context=context)
  427. if partner:
  428. res['partner_address_id'] = partner[0]
  429. res['partner_id'] = partner[1]
  430. else:
  431. res['partner_id'] = False
  432. res['partner_address_id'] = False
  433. else:
  434. _logger.debug("Could not get the calling number from Asterisk.")
  435. raise osv.except_osv(_('Error :'), _("Could not get the calling number from Asterisk. Are you currently on the phone ? If yes, check your setup and look at the OpenERP debug logs."))
  436. return res
  437. def open_filtered_object(self, cr, uid, ids, oerp_object, context=None):
  438. '''Returns the action that opens the list view of the 'oerp_object'
  439. given as argument filtered on the partner'''
  440. # This module only depends on "base"
  441. # and I don't want to add a dependancy on "sale" or "account"
  442. # So I just check here that the model exists, to avoid a crash
  443. if not self.pool.get('ir.model').search(cr, uid, [('model', '=', oerp_object._name)], context=context):
  444. raise osv.except_osv(_('Error :'), _("The object '%s' is not found in your OpenERP database, probably because the related module is not installed." % oerp_object._description))
  445. partner = self.read(cr, uid, ids[0], ['partner_id'], context=context)['partner_id']
  446. if partner:
  447. action = {
  448. 'name': oerp_object._description,
  449. 'view_type': 'form',
  450. 'view_mode': 'tree,form',
  451. 'res_model': oerp_object._name,
  452. 'type': 'ir.actions.act_window',
  453. 'nodestroy': False, # close the pop-up wizard after action
  454. 'target': 'current',
  455. 'domain': [('partner_id', '=', partner[0])],
  456. }
  457. return action
  458. else:
  459. return False
  460. def open_sale_orders(self, cr, uid, ids, context=None):
  461. '''Function called by the related button of the wizard'''
  462. return self.open_filtered_object(cr, uid, ids, self.pool.get('sale.order'), context=context)
  463. def open_invoices(self, cr, uid, ids, context=None):
  464. '''Function called by the related button of the wizard'''
  465. return self.open_filtered_object(cr, uid, ids, self.pool.get('account.invoice'), context=context)
  466. def simple_open(self, cr, uid, ids, object_name='res.partner', context=None):
  467. if object_name == 'res.partner':
  468. field = 'partner_id'
  469. label = 'Partner'
  470. elif object_name == 'res.partner.address':
  471. field = 'partner_address_id'
  472. label = 'Contact'
  473. else:
  474. raise osv.except_osv(_('Error :'), "This object '%s' is not supported" % object_name)
  475. record_to_open = self.read(cr, uid, ids[0], [field], context=context)[field]
  476. if record_to_open:
  477. return {
  478. 'name': label,
  479. 'view_type': 'form',
  480. 'view_mode': 'form,tree',
  481. 'res_model': object_name,
  482. 'type': 'ir.actions.act_window',
  483. 'nodestroy': False, # close the pop-up wizard after action
  484. 'target': 'current',
  485. 'res_id': [record_to_open[0]],
  486. }
  487. else:
  488. return False
  489. def open_partner(self, cr, uid, ids, context=None):
  490. '''Function called by the related button of the wizard'''
  491. return self.simple_open(cr, uid, ids, object_name='res.partner', context=context)
  492. def open_partner_address(self, cr, uid, ids, context=None):
  493. '''Function called by the related button of the wizard'''
  494. return self.simple_open(cr, uid, ids, object_name='res.partner.address', context=context)
  495. def create_partner_address(self, cr, uid, ids, phone_type='phone', context=None):
  496. '''Function called by the related button of the wizard'''
  497. calling_number = self.read(cr, uid, ids[0], ['calling_number'], context=context)['calling_number']
  498. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  499. ast_server = self.pool.get('asterisk.server')._get_asterisk_server_from_user(cr, uid, user, context=context)
  500. # Convert the number to the international format
  501. number_to_write = self.pool.get('asterisk.server')._convert_number_to_international_format(cr, uid, calling_number, ast_server, context=context)
  502. new_partner_address_id = self.pool.get('res.partner.address').create(cr, uid, {phone_type: number_to_write}, context=context)
  503. action = {
  504. 'name': 'Create new contact',
  505. 'view_type': 'form',
  506. 'view_mode': 'form,tree',
  507. 'res_model': 'res.partner.address',
  508. 'type': 'ir.actions.act_window',
  509. 'nodestroy': False,
  510. 'target': 'current',
  511. 'res_id': [new_partner_address_id],
  512. }
  513. return action
  514. def create_partner_address_phone(self, cr, uid, ids, context=None):
  515. return self.create_partner_address(cr, uid, ids, phone_type='phone', context=context)
  516. def create_partner_address_mobile(self, cr, uid, ids, context=None):
  517. return self.create_partner_address(cr, uid, ids, phone_type='mobile', context=context)
  518. def update_partner_address(self, cr, uid, ids, phone_type='mobile', context=None):
  519. cur_wizard = self.browse(cr, uid, ids[0], context=context)
  520. if not cur_wizard.to_update_partner_address_id:
  521. raise osv.except_osv(_('Error :'), _("Select the contact to update."))
  522. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  523. ast_server = self.pool.get('asterisk.server')._get_asterisk_server_from_user(cr, uid, user, context=context)
  524. number_to_write = self.pool.get('asterisk.server')._convert_number_to_international_format(cr, uid, cur_wizard.calling_number, ast_server, context=context)
  525. self.pool.get('res.partner.address').write(cr, uid, cur_wizard.to_update_partner_address_id.id, {phone_type: number_to_write}, context=context)
  526. action = {
  527. 'name': 'Contact: ' + cur_wizard.to_update_partner_address_id.name,
  528. 'view_type': 'form',
  529. 'view_mode': 'form,tree',
  530. 'res_model': 'res.partner.address',
  531. 'type': 'ir.actions.act_window',
  532. 'nodestroy': False,
  533. 'target': 'current',
  534. 'res_id': [cur_wizard.to_update_partner_address_id.id]
  535. }
  536. return action
  537. def update_partner_address_phone(self, cr, uid, ids, context=None):
  538. return self.update_partner_address(cr, uid, ids, phone_type='phone', context=context)
  539. def update_partner_address_mobile(self, cr, uid, ids, context=None):
  540. return self.update_partner_address(cr, uid, ids, phone_type='mobile', context=context)
  541. def onchange_to_update_partner_address(self, cr, uid, ids, to_update_partner_address_id, context=None):
  542. res = {}
  543. res['value'] = {}
  544. if to_update_partner_address_id:
  545. to_update_partner_address = self.pool.get('res.partner.address').browse(cr, uid, to_update_partner_address_id, context=context)
  546. res['value'].update({'current_phone': to_update_partner_address.phone,
  547. 'current_mobile': to_update_partner_address.mobile})
  548. else:
  549. res['value'].update({'current_phone': False, 'current_mobile': False})
  550. return res
  551. wizard_open_calling_partner()
  552. # This module supports multi-company
  553. class res_company(osv.osv):
  554. _inherit = "res.company"
  555. _columns = {
  556. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  557. }
  558. res_company()