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.

572 lines
31 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 _parse_asterisk_answer(self, cr, uid, sock, end_string='\r\n\r\n', context=None):
  150. '''Parse the answer of the Asterisk Manager Interface'''
  151. answer = ''
  152. data = ''
  153. while end_string not in data:
  154. data = sock.recv(1024)
  155. if data:
  156. answer += data
  157. # remove end_string from answer
  158. if answer[-len(end_string):] == end_string:
  159. answer = answer[:-len(end_string)]
  160. return answer
  161. def _connect_to_asterisk(self, cr, uid, method='dial', options=None, context=None):
  162. '''
  163. Open the socket to the Asterisk Manager Interface (AMI)
  164. and send instructions to Dial to Asterisk. That's the important function !
  165. '''
  166. user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
  167. # Note : if I write 'Error' without ' :', it won't get translated...
  168. # I don't understand why !
  169. # We check if the user has an Asterisk server configured
  170. if user.asterisk_server_id.id:
  171. ast_server = user.asterisk_server_id
  172. else:
  173. asterisk_server_ids = self.search(cr, uid, [('company_id', '=', user.company_id.id)], context=context)
  174. # If no asterisk server is configured on the user, we take the first one
  175. if not asterisk_server_ids:
  176. raise osv.except_osv(_('Error :'), _("No Asterisk server configured for the company '%s'.") % user.company_id.name)
  177. else:
  178. ast_server = self.browse(cr, uid, asterisk_server_ids[0], context=context)
  179. # We check if the current user has a chan type
  180. if not user.asterisk_chan_type:
  181. raise osv.except_osv(_('Error :'), _('No channel type configured for the current user.'))
  182. # We check if the current user has an internal number
  183. if not user.internal_number:
  184. raise osv.except_osv(_('Error :'), _('No internal phone number configured for the current user'))
  185. _logger.debug("User's phone : %s/%s" % (user.asterisk_chan_type, user.internal_number))
  186. _logger.debug("Asterisk server = %s:%d" % (ast_server.ip_address, ast_server.port))
  187. # Connect to the Asterisk Manager Interface, using IPv6-ready code
  188. try:
  189. res = socket.getaddrinfo(str(ast_server.ip_address), ast_server.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
  190. except:
  191. _logger.warning("Can't resolve the DNS of the Asterisk server '%s'" % ast_server.ip_address)
  192. raise osv.except_osv(_('Error :'), _("Can't resolve the DNS of the Asterisk server : '%s'" % ast_server.ip_address))
  193. for result in res:
  194. af, socktype, proto, canonname, sockaddr = result
  195. sock = socket.socket(af, socktype, proto)
  196. try:
  197. sock.connect(sockaddr)
  198. header_received = sock.recv(1024)
  199. _logger.debug('Header received from Asterisk : %s' % header_received)
  200. # Login to Asterisk
  201. login_act = 'Action: login\r\n' + \
  202. 'Events: off\r\n' + \
  203. 'Username: ' + ast_server.login + '\r\n' + \
  204. 'Secret: ' + ast_server.password + '\r\n\r\n'
  205. sock.send(login_act.encode('ascii'))
  206. login_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  207. if 'Response: Success' in login_answer:
  208. _logger.debug("Successful authentification to Asterisk :\n%s" % login_answer)
  209. else:
  210. raise osv.except_osv(_('Error :'), _("Authentification to Asterisk failed :\n%s" % login_answer))
  211. if method == 'dial':
  212. # Convert the phone number in the format that will be sent to Asterisk
  213. erp_number = options.get('erp_number')
  214. if not erp_number:
  215. raise osv.except_osv(_('Error :'), "Hara kiri : you must call the function with erp_number in the options")
  216. ast_number = self._reformat_number(cr, uid, erp_number, ast_server, context=context)
  217. # The user should have a CallerID
  218. if not user.callerid:
  219. raise osv.except_osv(_('Error :'), _('No callerID configured for the current user'))
  220. # Dial with Asterisk
  221. originate_act = 'Action: originate\r\n' + \
  222. 'Channel: ' + user.asterisk_chan_type + '/' + user.internal_number + '\r\n' + \
  223. 'Priority: ' + str(ast_server.extension_priority) + '\r\n' + \
  224. 'Timeout: ' + str(ast_server.wait_time*1000) + '\r\n' + \
  225. 'CallerId: ' + user.callerid + '\r\n' + \
  226. 'Exten: ' + ast_number + '\r\n' + \
  227. 'Context: ' + ast_server.context + '\r\n'
  228. if ast_server.alert_info and user.asterisk_chan_type == 'SIP':
  229. for server_alertinfo in ast_server.alert_info.split('|'):
  230. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + server_alertinfo + '\r\n'
  231. if user.alert_info and user.asterisk_chan_type == 'SIP':
  232. for user_alertinfo in user.alert_info.split('|'):
  233. originate_act += 'Variable: SIPAddHeader=Alert-Info: ' + user_alertinfo + '\r\n'
  234. originate_act += '\r\n'
  235. sock.send(originate_act.encode('ascii'))
  236. originate_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  237. if 'Response: Success' in originate_answer:
  238. _logger.debug('Successfull originate command : %s' % originate_answer)
  239. else:
  240. raise osv.except_osv(_('Error :'), _("Click to dial with Asterisk failed :\n%s" % originate_answer))
  241. elif method == "get_calling_number":
  242. status_act = 'Action: Status\r\n\r\n' # TODO : add ActionID
  243. sock.send(status_act.encode('ascii'))
  244. status_answer = self._parse_asterisk_answer(cr, uid, sock, end_string='Event: StatusComplete', context=context)
  245. if 'Response: Success' in status_answer:
  246. _logger.debug('Successfull Status command :\n%s' % status_answer)
  247. else:
  248. raise osv.except_osv(_('Error :'), _("Status command to Asterisk failed :\n%s" % status_answer))
  249. # Parse answer
  250. calling_party_number = False
  251. status_answer_split = status_answer.split('\r\n\r\n')
  252. for event in status_answer_split:
  253. string_match = 'BridgedChannel: ' + user.asterisk_chan_type + '/' + user.internal_number
  254. if not string_match in event:
  255. continue
  256. event_split = event.split('\r\n')
  257. for event_line in event_split:
  258. if not 'CallerIDNum' in event_line:
  259. continue
  260. line_detail = event_line.split(': ')
  261. if len(line_detail) <> 2:
  262. raise osv.except_osv('Error :', "Hara kiri... this is not possible")
  263. calling_party_number = line_detail[1]
  264. # Logout of Asterisk
  265. sock.send(('Action: Logoff\r\n\r\n').encode('ascii'))
  266. logout_answer = self._parse_asterisk_answer(cr, uid, sock, context=context)
  267. if 'Response: Goodbye' in logout_answer:
  268. _logger.debug('Successfull logout from Asterisk :\n%s' % logout_answer)
  269. else:
  270. _logger.warning('Logout from Asterisk failed :\n%s' % logout_answer)
  271. # we catch only network problems here
  272. except socket.error:
  273. _logger.warning("Unable to connect to the Asterisk server '%s' IP '%s:%d'" % (ast_server.name, ast_server.ip_address, ast_server.port))
  274. raise osv.except_osv(_('Error :'), _("The connection from OpenERP to the Asterisk server failed. Please check the configuration on OpenERP and on Asterisk."))
  275. finally:
  276. sock.close()
  277. if method == 'dial':
  278. _logger.info("Asterisk Click2Dial from %s/%s to %s" % (user.asterisk_chan_type, user.internal_number, ast_number))
  279. return True
  280. elif method == "get_calling_number":
  281. _logger.debug("Calling party number: %s" % calling_party_number)
  282. return calling_party_number
  283. else:
  284. return False
  285. asterisk_server()
  286. # Parameters specific for each user
  287. class res_users(osv.osv):
  288. _inherit = "res.users"
  289. _columns = {
  290. 'internal_number': fields.char('Internal number', size=15,
  291. help="User's internal phone number."),
  292. 'callerid': fields.char('Caller ID', size=50,
  293. help="Caller ID used for the calls initiated by this user."),
  294. # You'd probably think : Asterisk should reuse the callerID of sip.conf !
  295. # But it cannot, cf http://lists.digium.com/pipermail/asterisk-users/2012-January/269787.html
  296. 'asterisk_chan_type': fields.selection([
  297. ('SIP', 'SIP'),
  298. ('IAX2', 'IAX2'),
  299. ('DAHDI', 'DAHDI'),
  300. ('Zap', 'Zap'),
  301. ('Skinny', 'Skinny'),
  302. ('MGCP', 'MGCP'),
  303. ('mISDN', 'mISDN'),
  304. ('H323', 'H323'),
  305. ], 'Asterisk channel type',
  306. help="Asterisk channel type, as used in the Asterisk dialplan. If the user has a regular IP phone, the channel type is 'SIP'."),
  307. '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 '|'."),
  308. 'asterisk_server_id': fields.many2one('asterisk.server', 'Asterisk server',
  309. 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."),
  310. }
  311. _defaults = {
  312. 'asterisk_chan_type': 'SIP',
  313. }
  314. def _check_validity(self, cr, uid, ids):
  315. for user in self.browse(cr, uid, ids):
  316. for check_string in [('Internal number', user.internal_number), ('Caller ID', user.callerid)]:
  317. if check_string[1]:
  318. try:
  319. plom = check_string[1].encode('ascii')
  320. except UnicodeEncodeError:
  321. raise osv.except_osv(_('Error :'), _("The '%s' for the user '%s' should only have ASCII caracters" % (check_string[0], user.name)))
  322. return True
  323. _constraints = [
  324. (_check_validity, "Error message in raise", ['internal_number', 'callerid']),
  325. ]
  326. res_users()
  327. class res_partner_address(osv.osv):
  328. _inherit = "res.partner.address"
  329. def dial(self, cr, uid, ids, phone_field='phone', context=None):
  330. '''Read the number to dial and call _connect_to_asterisk the right way'''
  331. erp_number = self.read(cr, uid, ids, [phone_field], context=context)[0][phone_field]
  332. # Check if the number to dial is not empty
  333. if not erp_number:
  334. raise osv.except_osv(_('Error :'), _('There is no phone number !'))
  335. options = {'erp_number': erp_number}
  336. return self.pool.get('asterisk.server')._connect_to_asterisk(cr, uid, method='dial', options=options, context=context)
  337. def action_dial_phone(self, cr, uid, ids, context=None):
  338. '''Function called by the button 'Dial' next to the 'phone' field
  339. in the partner address view'''
  340. return self.dial(cr, uid, ids, phone_field='phone', context=context)
  341. def action_dial_mobile(self, cr, uid, ids, context=None):
  342. '''Function called by the button 'Dial' next to the 'mobile' field
  343. in the partner address view'''
  344. return self.dial(cr, uid, ids, phone_field='mobile', context=context)
  345. def get_name_from_phone_number(self, cr, uid, number, context=None):
  346. '''Function to get name from phone number. Usefull for use from Asterisk
  347. to add CallerID name to incoming calls.
  348. The "scripts/" subdirectory of this module has an AGI script that you can
  349. install on your Asterisk IPBX : the script will be called from the Asterisk
  350. dialplan via the AGI() function and it will use this function via an XML-RPC
  351. request.
  352. '''
  353. res = self.get_partner_from_phone_number(cr, uid, number, context=context)
  354. if res:
  355. return res[2]
  356. else:
  357. return False
  358. def get_partner_from_phone_number(self, cr, uid, number, context=None):
  359. res = {}
  360. # We check that "number" is really a number
  361. if not isinstance(number, str):
  362. return False
  363. if not number.isdigit():
  364. return False
  365. _logger.debug(u"Call get_name_from_phone_number with number = %s" % number)
  366. # Get all the partner addresses :
  367. all_ids = self.search(cr, uid, [], context=context)
  368. # For each partner address, we check if the number matches on the "phone" or "mobile" fields
  369. for entry in self.browse(cr, uid, all_ids, context=context):
  370. if entry.phone:
  371. # We use a regexp on the phone field to remove non-digit caracters
  372. if re.sub(r'\D', '', entry.phone).endswith(number):
  373. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  374. return (entry.id, entry.partner_id.id, entry.name)
  375. if entry.mobile:
  376. if re.sub(r'\D', '', entry.mobile).endswith(number):
  377. _logger.debug(u"Answer get_name_from_phone_number with name = %s" % entry.name)
  378. return (entry.id, entry.partner_id.id, entry.name)
  379. _logger.debug(u"No match for phone number %s" % number)
  380. return False
  381. res_partner_address()
  382. class wizard_open_calling_partner(osv.osv_memory):
  383. _name = "wizard.open.calling.partner"
  384. _description = "Open calling partner"
  385. _columns = {
  386. 'calling_number': fields.char('Calling number', size=30, help="Phone number of calling party that has been obtained from Asterisk."),
  387. 'partner_address_id': fields.many2one('res.partner.address', 'Partner address', help="Partner address related to the calling number"),
  388. 'partner_id': fields.many2one('res.partner', 'Partner', help="Partner related to the calling number"),
  389. }
  390. def default_get(self, cr, uid, fields, context=None):
  391. '''Thanks to the default_get method, we are able to query Asterisk and
  392. get the corresponding partner when we launch the wizard'''
  393. res = {}
  394. calling_number = self.pool.get('asterisk.server')._connect_to_asterisk(cr, uid, method='get_calling_number', context=context)
  395. #To test the code without Asterisk server
  396. #calling_number = "0141981242"
  397. if calling_number:
  398. res['calling_number'] = calling_number
  399. # We match only on the end of the phone number
  400. if len(calling_number) >= 9:
  401. number_to_search = calling_number[-9:len(calling_number)]
  402. else:
  403. number_to_search = calling_number
  404. partner = self.pool.get('res.partner.address').get_partner_from_phone_number(cr, uid, number_to_search, context=context)
  405. if partner:
  406. res['partner_address_id'] = partner[0]
  407. res['partner_id'] = partner[1]
  408. else:
  409. res['partner_id'] = False
  410. res['partner_address_id'] = False
  411. else:
  412. _logger.debug("Could not get the calling number from Asterisk.")
  413. raise osv.except_osv(_('Error :'), _("Could not get the calling number from Asterisk. Check your setup and look at the OpenERP debug logs."))
  414. return res
  415. def open_filtered_object(self, cr, uid, ids, oerp_object, context=None):
  416. '''Returns the action that opens the list view of the 'oerp_object'
  417. given as argument filtered on the partner'''
  418. # This module only depends on "base"
  419. # and I don't want to add a dependancy on "sale" or "account"
  420. # So I just check here that the model exists, to avoid a crash
  421. if not self.pool.get('ir.model').search(cr, uid, [('model', '=', oerp_object._name)], context=context):
  422. 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))
  423. partner = self.read(cr, uid, ids[0], ['partner_id'], context=context)['partner_id']
  424. if partner:
  425. action = {
  426. 'name': oerp_object._description,
  427. 'view_type': 'form',
  428. 'view_mode': 'tree,form',
  429. 'res_model': oerp_object._name,
  430. 'type': 'ir.actions.act_window',
  431. 'nodestroy': False, # close the pop-up wizard after action
  432. 'target': 'current',
  433. 'domain': [('partner_id', '=', partner[0])],
  434. }
  435. return action
  436. else:
  437. return False
  438. def open_sale_orders(self, cr, uid, ids, context=None):
  439. '''Function called by the related button of the wizard'''
  440. return self.open_filtered_object(cr, uid, ids, self.pool.get('sale.order'), context=context)
  441. def open_invoices(self, cr, uid, ids, context=None):
  442. '''Function called by the related button of the wizard'''
  443. return self.open_filtered_object(cr, uid, ids, self.pool.get('account.invoice'), context=context)
  444. def open_partner(self, cr, uid, ids, context=None):
  445. '''Function called by the related button of the wizard'''
  446. partner = self.read(cr, uid, ids[0], ['partner_id'], context=context)['partner_id']
  447. if partner:
  448. action = {
  449. 'name': 'Calling partner',
  450. 'view_type': 'form',
  451. 'view_mode': 'form,tree',
  452. 'res_model': 'res.partner',
  453. 'type': 'ir.actions.act_window',
  454. 'nodestroy': False, # close the pop-up wizard after action
  455. 'target': 'current',
  456. 'res_id': [partner[0]],
  457. }
  458. return action
  459. else:
  460. return False
  461. def create_new_partner(self, cr, uid, ids, phone_type='phone', context=None):
  462. '''Function called by the related button of the wizard'''
  463. calling_number = self.read(cr, uid, ids[0], ['calling_number'], context=context)['calling_number']
  464. # TODO : convert the number to the international format +33141981242
  465. new_partner_dict = {'name': 'ENTER PARTNER NAME',
  466. 'address': [(0,0, {phone_type: calling_number})]}
  467. new_partner_id = self.pool.get('res.partner').create(cr, uid, new_partner_dict, context=context)
  468. action = {
  469. 'name': 'Create new partner',
  470. 'view_type': 'form',
  471. 'view_mode': 'form,tree',
  472. 'res_model': 'res.partner',
  473. 'type': 'ir.actions.act_window',
  474. 'nodestroy': False,
  475. 'target': 'current',
  476. 'res_id': [new_partner_id],
  477. }
  478. return action
  479. def create_new_partner_phone(self, cr, uid, ids, context=None):
  480. return self.create_new_partner(cr, uid, ids, phone_type='phone', context=context)
  481. def create_new_partner_mobile(self, cr, uid, ids, context=None):
  482. return self.create_new_partner(cr, uid, ids, phone_type='mobile', context=context)
  483. wizard_open_calling_partner()
  484. # This module supports multi-company
  485. class res_company(osv.osv):
  486. _inherit = "res.company"
  487. _columns = {
  488. 'asterisk_server_ids': fields.one2many('asterisk.server', 'company_id', 'Asterisk servers', help="List of Asterisk servers.")
  489. }
  490. res_company()