Example #1
0
	def connectToAsterisk(self):
		settings = Settings.Settings()

		try :
			asterHost = settings.GetSystemParameters("ASTERISK_HOST")
			asterPort = settings.GetSystemParameters("ASTERISK_PORT")
			asterLogin = settings.GetSystemParameters("ASTERISK_LOGIN")
			asterPass = settings.GetSystemParameters("ASTERISK_PASSWORD")

			self.amic = QAsteriskManager(asterHost, asterPort, asterLogin, asterPass)

			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('FullyBooted'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentCalled'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentConnect'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentComplete'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Newchannel'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Hangup'), self.amiEvent)

			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Join'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Leave'), self.amiEvent)

			self.amic.connectToAsterisk()

			self.uniqidQueue = {}
			# Asterisk Originate

			if self.amic.isConnected() : self.status_Asterisk_label.setText("Подключен к Астериск")

		except QWSException.QWSException as err:
			print (err.code, err.message)

		except QAsteriskError as err:
			self.status_Asterisk_label.setText("Отключен от Астериск [%s]" % err.mesg)
Example #2
0
class Main_Form(QtGui.QMainWindow):
	def __init__(self, parent=None) :
		QtGui.QMainWindow.__init__(self, parent)
		uic.loadUi("ui/MainWindow_ui.ui", self)


		# Signals handlers
			# Handle signal for disabling connection menu
		self.connect(self, QtCore.SIGNAL('Hide_Menu_Connections'), self.Disable_Connection_Menues)

		# Test comment
			# Run Asterisk thread
		self.connect(self, QtCore.SIGNAL('Connect_to_Asterisk'), self.connectToAsterisk, QtCore.Qt.QueuedConnection)
			# And for disconnect
		self.connect(self, QtCore.SIGNAL('Disconnect'), self.Enable_Connection_Menues)
			# Handle change statusbar 
		self.connect(self, QtCore.SIGNAL('Change_DB_StatusBar_Connected'), self.Show_StatusBar_DB_Connect)	 
			# Read PBX Channel data from DB
		self.connect(self, QtCore.SIGNAL('Read_PBX_Channel_Data'), self.Read_PBX_Channel)
			# Incoming call (operator on the line)
		self.connect(self, QtCore.SIGNAL('Asterisk_Incoming_Call'), self.Handle_Asterisk_IncomingCall)
		self.connect(self, QtCore.SIGNAL('amiOriginate'), self.amiOriginate)

		# Menu 'Reference Book'
		self.action_CarCategory.triggered.connect(self.Show_CarCategories_Win)
		self.action_Drivers.triggered.connect(self.Show_Drivers_Win)
		self.action_NocacheClients.triggered.connect(self.Show_Noncache_Clients_Win)
		self.action_Abonents.triggered.connect(self.Show_Abonents_Win)
		self.action_BlackList.triggered.connect(self.Show_BlacklistClients_Win)
		self.action_VIPList.triggered.connect(self.Show_VIPClients_Win)
		self.action_TaxiStates.triggered.connect(self.Show_Taxi_States_Win)
		self.action_OrderStatus.triggered.connect(self.Show_Order_Status_Win)
		self.action_Zones.triggered.connect(self.Show_Zones_Win)

		# Menu 'Work'
		self.action_DriverFastSearch.triggered.connect(partial(self.Show_FastDriverSearch_Win, None))
		self.action_NewOrder.triggered.connect(partial(self.Show_NewOrder_Win, None))
		self.action_OrderDatabase.triggered.connect(self.Show_Finished_Orders_Journal_Win)
		self.action_OperatorWorktable.triggered.connect(partial(self.Show_OperatorWorktable_Win, True))

		# Menu 'View'
		self.action_Show_Clock.triggered.connect(self.Show_Clock)

		# Menu 'Settings'
		self.action_phoneChannelsList.triggered.connect(self.showPhoneChannelsList)

		# Empty OperatorWorktable Window after start
		self.Show_OperatorWorktable_Win(False)

		# Set finishedorders widget to None
		self.Finished_Orders_Journal_Widget = None


		# Connection for db object
		self.db_connlink = QtSql.QSqlDatabase()

		# Handling DB configuration file and Create connections menu
		self.Handle_DBConf_File()

		# Set status bar and its widgets
		self.statusBar = QtGui.QStatusBar()
		self.status_DB_label = QtGui.QLabel('Отключен от БД ')
		self.status_Asterisk_label = QtGui.QLabel('Отключен от Астериск')
		self.statusBar.addWidget(self.status_DB_label)
		self.statusBar.addWidget(self.status_Asterisk_label)

		self.setStatusBar(self.statusBar)
		self.tabWidget.setTabsClosable(True)
		self.tabWidget.tabBar().tabButton(0, QtGui.QTabBar.RightSide).hide()


	def Handle_DBConf_File(self):
		# Dict in format: QAction_Link = 1 or 0 (1 for connect, 0 for disconnect type)
		self.connection_dict = {}
		params_file = open("cp.ini", "r")
		for line in params_file.readlines() :
			if line[0] != '#':
				line_arr = line.strip('\n').split(';')
				if len(line_arr) < 2 : QtGui.QMessageBox.critical(self, "Ошибка", "Ошибка чтения конфигурационного файла cp.ini.", QtGui.QMessageBox.Ok); break
				else :
					if len(line_arr) == 2 : connection_name = 'Подключиться...'; self.hostDB = line_arr[0]; self.db_name = line_arr[1]; db_alias = None
					else : connection_name = 'Подключиться к ' + line_arr[0] + '...'; self.hostDB = line_arr[1]; self.db_name = line_arr[2]; db_alias = line_arr[0]

				action_link = self.menu_Connection.addAction(QtGui.QIcon('res/connect.png'), connection_name)
				# Set DB alias
				self.connect(action_link, QtCore.SIGNAL("triggered()"), partial(self.setDBAlias, db_alias))
				# Show login win
				self.connect(action_link, QtCore.SIGNAL("triggered()"), self.showLoginWin)

				self.connection_dict[action_link] = 1

		action_link = self.menu_Connection.addAction(QtGui.QIcon('res/disconnect.png'), 'Отключиться...')
		self.connection_dict[action_link] = 0
		action_link.setEnabled(False)
		self.connect(action_link, QtCore.SIGNAL("triggered()"), self.Disconnect)

		self.menu_Connection.addSeparator()
		action_link = self.menu_Connection.addAction(QtGui.QIcon('res/close.png'), 'Выход...')
		self.connect(action_link, QtCore.SIGNAL("triggered()"), self.close)

	# Connect: Disable all connection and enable disconnect button
	def Disable_Connection_Menues(self):
		for key in self.connection_dict.keys() :
			key.setEnabled(self.connection_dict[key] != 1)

		# Set enabled flag to other menues on Main Form
		en_flag = True
		self.menu.setEnabled(en_flag)
		self.menu_2.setEnabled(en_flag)
		self.menu_4.setEnabled(en_flag)
		self.action_OrderDatabase.setEnabled(en_flag)

	# Disconnect: Enable all connection buttons and disable disconnect button		
	def Enable_Connection_Menues(self):
		for key in self.connection_dict.keys() :
			key.setEnabled(self.connection_dict[key] != 0)

		# Close db connection
		self.db_connlink.close()

		# Set disabled flag to other menues on Main Form
		dis_flag = False
		self.menu.setEnabled(dis_flag)
		self.menu_2.setEnabled(dis_flag)
		self.menu_4.setEnabled(dis_flag)
		self.action_OrderDatabase.setEnabled(dis_flag)
		# Check if finishedOrder tab is exist and close it
		if self.Finished_Orders_Journal_Widget is not None:
			self.Finished_Orders_Journal_Widget.close()
			self.Finished_Orders_Journal_Widget = None
			self.action_OrderDatabase.setChecked(False)

		 # Set status message about connect state to DB
		self.status_DB_label.setText("Отключен от БД ")
		self.status_Asterisk_label.setText("Отключен от Астериск")


	def Disconnect(self):
		self.emit(QtCore.SIGNAL('Disconnect'))


	def setDBAlias(self, dbAlias):
		self.db_alias = dbAlias


	def checkDBVersion(self):
		try:
			dbVersionQuery = QTDSqlQuery.QTDSqlQuery()
			dbVersionQuery.prepare("SELECT PARAM_VALUE FROM SETTINGS WHERE PARAM_NAME=:DBSettingName")
			dbVersionQuery.bindValue(":DBSettingName", 'db_version')
			dbVersionQuery.exec_()
			dbVersionQuery.first()
			if dbVersionQuery.value(0) != Settings.Settings().DBVersion : return False
			else: return True

		except QWSException.QWSException as err:
			print (err.code, err.message, '\n', err.sqlQuery.lastQuery(), err.sqlQuery.lastError().text())
			return False


	def connectToDB(self, login, password):
		self.db_link = QtSql.QSqlDatabase.addDatabase("QPSQL")
		self.db_link.setHostName(self.hostDB)
		self.db_link.setDatabaseName(self.db_name)
		self.db_link.setUserName(login)
		self.db_link.setPassword(password)
		login_checker = self.db_link.open()

		# If DB was open
		if login_checker:
			if self.checkDBVersion() :
				#Load OperatorWorktable Window contents after successful login
				self.emit(QtCore.SIGNAL('Update_OperatorsWorktable_Form'))
				# Hide other connections from MainWin menu
				self.emit(QtCore.SIGNAL('Hide_Menu_Connections'))
				# Change statusbar
				self.emit(QtCore.SIGNAL('Change_DB_StatusBar_Connected'), self.db_alias)
				# Get pbx channel
				self.emit(QtCore.SIGNAL('Read_PBX_Channel_Data'))
				# Signal for connect to asterisk
				self.emit(QtCore.SIGNAL('Connect_to_Asterisk'))
			else:
				QtGui.QMessageBox.critical(self, "Ошибка", "Структура базы данных не соответствует версии программы. Срочно обратитесь к системному администратору.", QtGui.QMessageBox.Ok)
				self.close()
		else :
			QtGui.QMessageBox.critical(self, "Ошибка", "Ошибка подключения\n"+self.db_link.lastError().text(), QtGui.QMessageBox.Ok)


	def connectToAsterisk(self):
		settings = Settings.Settings()

		try :
			asterHost = settings.GetSystemParameters("ASTERISK_HOST")
			asterPort = settings.GetSystemParameters("ASTERISK_PORT")
			asterLogin = settings.GetSystemParameters("ASTERISK_LOGIN")
			asterPass = settings.GetSystemParameters("ASTERISK_PASSWORD")

			self.amic = QAsteriskManager(asterHost, asterPort, asterLogin, asterPass)

			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('FullyBooted'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentCalled'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentConnect'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('AgentComplete'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Newchannel'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Hangup'), self.amiEvent)

			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Join'), self.amiEvent)
			QtCore.QObject.connect(self.amic, QtCore.SIGNAL('Leave'), self.amiEvent)

			self.amic.connectToAsterisk()

			self.uniqidQueue = {}
			# Asterisk Originate

			if self.amic.isConnected() : self.status_Asterisk_label.setText("Подключен к Астериск")

		except QWSException.QWSException as err:
			print (err.code, err.message)

		except QAsteriskError as err:
			self.status_Asterisk_label.setText("Отключен от Астериск [%s]" % err.mesg)


	def amiEvent(self, event):
#		print(event.dump())
		eventName = event.attr('Event')

		if eventName == 'FullyBooted' :
			print(event.dump())

		if eventName == 'Newchannel' and event.attr('Uniqueid') not in self.uniqidQueue:
			self.uniqidQueue[event.attr('Uniqueid')] = event.attr('CallerIDNum')

		if eventName == 'Hangup' and event.attr('Uniqueid') in self.uniqidQueue:
			del self.uniqidQueue[event.attr('Uniqueid')]

		if eventName == 'AgentConnect' and event.attr('Member') in self.pbx_channels_arr:
			self.Handle_Asterisk_IncomingCall(self.uniqidQueue[event.attr('Uniqueid')])


	def amiOriginate(self, comment, phone):
		try:
			if (self.amic.isConnected() and self.pbx_channels_arr != [] and phone != '') :
				channel = self.pbx_channels_arr[0]
				context = 'outgoing-office'
				self.callWindow = callWindow.callWindow(phone)
				self.callWindow.show()
				self.amic.originate(channel, context, phone, comment+' <'+phone+'>')
				self.callWindow.close()

		except QAsteriskError as err:
			self.callWindow.close()
			QtGui.QMessageBox.critical(self, "Ошибка", "Была предпринята попытка соединения канала %s с номером %s. "
																								 "Произошла ошибка во время вызова: %s" % (channel, phone, err), QtGui.QMessageBox.Ok)
		except AttributeError:
			QtGui.QMessageBox.critical(self, "Ошибка", "Нет соединения с Asterisk.", QtGui.QMessageBox.Ok)


	def Show_StatusBar_DB_Connect(self, alias):
		conn_name = ''
		if alias : conn_name = conn_name.join(('(',alias,')'))
		self.status_DB_label.setText("Подключен к БД %s|" % conn_name)


	def Read_PBX_Channel(self):
		self.pbx_channels_arr = Settings.Settings().GetPBXChannels()


	def Handle_Asterisk_IncomingCall(self, phone):
		try:
			exist_order_query = QTDSqlQuery.QTDSqlQuery()
			exist_order_query.prepare("SELECT ID_ORDER_ONLINE FROM ORDERS_ONLINE WHERE PHONE=:phone_num")
			exist_order_query.bindValue(":phone_num", phone)
			exist_order_query.exec_()
			exist_order_query.first()
			if exist_order_query.isValid() :
				self.Show_NewOrder_Win(exist_order_query.value(0), phone)

			else : self.Show_NewOrder_Win(None, phone)

		except QWSException.QWSException as err:
			print (err.code, err.message, '\n', err.sqlQuery.lastQuery(), err.sqlQuery.lastError().text())


	def showLoginWin(self):
		self.loginDialog = Login.Logon_Win_Class(self)
		QtCore.QObject.connect(self.loginDialog, QtCore.SIGNAL('loginToDB'), self.connectToDB)
		self.loginDialog.exec_()


	def Show_Drivers_Win(self) :
		self.Driver_Win_Widget = Drivers_Window.Drivers_Win_Class(self)
		self.Driver_Win_Widget.exec_()


	def Show_Noncache_Clients_Win(self) :
		self.Noncache_Clients_Widget = Noncache_Clients_Window.Noncache_Clients_Win_Class(self)
		self.Noncache_Clients_Widget.exec_()


	def Show_Abonents_Win(self) :
		self.Abonents_Widget = Abonents_Window.Abonents_Win_Class(self)
		self.Abonents_Widget.exec_()


	def Show_VIPClients_Win(self):
		self.VIPClients_Widget = VIP_Clients_Window.VIPClients_Win_Class(self)
		self.VIPClients_Widget.exec_()


	def Show_BlacklistClients_Win(self):
		self.BlacklistClients_Widget = Blacklist_Clients_Window.BlacklistClients_Win_Class(self)
		self.BlacklistClients_Widget.exec_()


	def Show_Taxi_States_Win(self):
		self.Driver_Status_Widget = Driver_Status_Window.Driver_Status_Win_Class(self)
		self.Driver_Status_Widget.exec_()


	def Show_Order_Status_Win(self):
		self.Order_Status_Widget = Order_Status_Window.Order_Status_Win_Class(self)
		self.Order_Status_Widget.exec_()


	def Show_Zones_Win(self) :
		self.Zones_Widget = Zones_Window.Zones_Win_Class(self)
		self.Zones_Widget.exec_()


	def Show_CarCategories_Win(self):
		self.CarCategories_Widget = CarCategories_Window.CarCategories_Win_Class(self)
		self.CarCategories_Widget.exec_()


	def Show_FastDriverSearch_Win(self, online_order_id):
		self.FastSearchWidget = Fast_DriverSearch.FastDriver_Search_Class(self, online_order_id)
		self.FastSearchWidget.exec_()


	def Show_NewOrder_Win(self, id, phone_number):
		self.NewOrder_Widget = New_Order.NewOrder_Win_Class(self, id, phone_number)
		self.NewOrder_Widget.show()


	def Show_Finished_Orders_Journal_Win(self):
		for i in range(self.tabWidget.count()):
			if self.tabWidget.widget(i) == self.Finished_Orders_Journal_Widget:
				self.Finished_Orders_Journal_Widget.close()
				return True

		self.Finished_Orders_Journal_Widget = Finished_Orders_Journal.Finished_Orders_Win_Class(self)
		self.tabWidget.addTab(self.Finished_Orders_Journal_Widget, 'Журнал выполненных заказов')
		self.connect(self.tabWidget, QtCore.SIGNAL('tabCloseRequested(int)'), self.closeTab)


	def closeTab(self, idx):
		if self.tabWidget.widget(idx) is not None:
			if self.tabWidget.widget(idx).objectName() != 'tabWorkspace' :
				self.action_OrderDatabase.setChecked(False)
				self.tabWidget.removeTab(idx)


	def Show_OperatorWorktable_Win(self, Show_Elements):
		self.OperatorWorktable_Widget = OperatorWorktable_Window.OperatorWorktable_Win_Class(self, Show_Elements)
		self.vlayoutWorkspace.addWidget(self.OperatorWorktable_Widget)


	def showPhoneChannelsList(self):
		self.phoneChannelsWidget = phoneChannelsList.phoneChannelsList(self.db_link)
		self.phoneChannelsWidget.exec_()


	def Show_Modal_Window(self, widget_link) :
		widget_link.exec_()
#		Move_Window.Move_Window(self, widget_link).Set_Center()


	def Show_Clock(self) :
		self.emit(QtCore.SIGNAL('Show_Clock'))