def setDinnerOrderItemsFromXML(self, xml): salad = get_xml_field_value(xml, 'SALAD') if salad is not None: salad = int(salad) else: salad = 0 first = get_xml_field_value(xml, 'FIRST') if first is not None: first = int(first) else: first = 0 second = get_xml_field_value(xml, 'SECOND') if second is not None: second = int(second) else: second = 0 if salad: self.ui.chkMenuSalad.setCheckState(Qt.Checked) else: self.ui.chkMenuSalad.setCheckState(Qt.Unchecked) if first: self.ui.chkMenuFirst.setCheckState(Qt.Checked) else: self.ui.chkMenuFirst.setCheckState(Qt.Unchecked) if second: self.ui.chkMenuSecond.setCheckState(Qt.Checked) else: self.ui.chkMenuSecond.setCheckState(Qt.Unchecked)
def get_directories_changed_at(): xml = get_data_xml("GetDirectoriesChangedAt", "") result = {} result['server_time'] = datetime.strptime( get_xml_field_value(xml, 'SERVER_TIME'), REMOTE_DATETIME_FORMAT) result['customers_changed_at'] = datetime.strptime( get_xml_field_value(xml, 'CUSTOMERS_CHANGED_AT'), REMOTE_DATETIME_FORMAT) result['task_types_changed_at'] = datetime.strptime( get_xml_field_value(xml, 'TASK_TYPES_CHANGED_AT'), REMOTE_DATETIME_FORMAT) return result
def authenticate(force=False): global session_id, user_id if not session_id or force: param = dict(aName = user_name, aPassword = user_pass, aAlias = 'home') result_xml = remote_call('authenticateUser', param) session_id = get_xml_field_value(result_xml, 'sessionID') if session_id is not None: user_id = get_xml_field_value(result_xml, 'ID') else: raise GuiException("Не удалось получить идентификатор сессии после авторизации") return session_id
def get_staff_by_user(user_id): result_xml = get_data_xml("GetStaffByUser", dict_to_xml({'PARAMS': { 'USER_ID': user_id }})) staff_id = int(get_xml_field_value(result_xml, 'RESULT')) if staff_id is None: raise GuiException('Вы не являетесь сотрудником Novelty') return staff_id
def generate_jasper_report_sync(report_id, param_xml): param = dict( aSession = authenticate(), aParamsXML = "<![CDATA[<report><name>%i</name><return>pdf</return>%s</report>]]>" % (report_id, param_xml) ) result_xml = remote_call('generateJasperReportSync', param) encoded_result = get_xml_field_value(result_xml, 'return') if encoded_result is None: raise GuiException("Неизвестный тип ответа от веб-сервиса") return base64.b64decode(encoded_result)
def request_ex(xml, servers, port, use_ssl, url=SERVICES_URL, err_msg='Невозможно установить соединение с БД'): connected = False for server in servers: host_str = '%s:%s' % (server, port) if use_ssl: h = httplib.HTTPSConnection(host_str) else: h = httplib.HTTPConnection(host_str) headers = { 'Host':host_str, 'Content-Type':'text/xml; charset=utf-8', 'Content-Length':str(len(xml)), } try: h.request('POST', url, body=xml, headers=headers) connected = True break except: pass if not connected: set_last_error(ERROR_CANT_CONNECT) raise GuiException(err_msg) r = h.getresponse() d = r.read() err = get_xml_field_value(d, 'faultstring') if err is None: err = get_xml_field_value(d, 'ErrorMessage') if err is not None: print err if 'Сессия не определена' in err: return request_ex(set_session_in_xml(xml, authenticate(force=True)), [server], port, use_ssl, url, err_msg) else: raise GuiException(err) return d
def get_data_xml(request_type, xml): try: encoded_xml = base64.b64encode(xml) except: raise GuiException('Невозможно перекодировать запрос в base64') param = dict( aSessionID = authenticate(), aRequest = dict(Type = request_type, Version = 1, Body = encoded_xml) ) result_xml = remote_call('getDataXml', param) encoded_body_xml = get_xml_field_value(result_xml, 'Body') if encoded_body_xml is None: raise GuiException("Неизвестный тип ответа от веб-сервиса") return base64.b64decode(encoded_body_xml)
def doServiceAction(self, action): global session_id item = self.currentItem() if item is not None: parent = item.parent() if parent is not None: server_data = parent.data(0, Qt.UserRole).toPyObject() service_data = item.data(0, Qt.UserRole).toPyObject() if action == self.SERVICE_ACTION_START: cmd_str = 'startService' elif action == self.SERVICE_ACTION_STOP: cmd_str = 'stopService' elif action == self.SERVICE_ACTION_RESTART: cmd_str = 'restartService' else: raise GuiException(u'Неизвестная команда') try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) xml = remote_call_ex( cmd_str, dict(serverID=server_data.id, serviceName=service_data.service_name, sessionID=authenticate()), server_data.server, server_data.port, server_data.use_ssl) QApplication.restoreOverrideCursor() result = get_xml_field_value(xml, 'return') if result is not None: result = result.strip() if result: raise GuiException(result) else: QMessageBox.information(None, PROGRAM_NAME, u'Операция завершена успешно', QMessageBox.Ok) finally: QApplication.restoreOverrideCursor()
def saveData(self): self.buttonBox.setFocus() self.cboCustomer.validateValue() self.cboTaskType.validateValue() new_desc = self.txt.toPlainText().trimmed() new_desc_utf8 = new_desc.toUtf8() if new_desc.length() == 0: self.txt.setFocus() raise GuiException('Укажите описание выполненных работ') try: new_group_id = self.cboCustomer.itemData( self.cboCustomer.currentIndex()).toInt()[0] new_task_type_id = self.cboTaskType.itemData( self.cboTaskType.currentIndex()).toInt()[0] new_time = self.txtTime.value() xml_str = dict_to_xml( dict(WORKSHEETS=dict( WORKSHEET=dict(WORKSHEET_ID=self.worksheet_id, CUSTOMER_ID=new_group_id, TASK_TYPE_ID=new_task_type_id, DESCRIPTION=prepare_string(new_desc_utf8), DURATION=new_time, STAFF_ID=self.parent_task_list.staff_id)))) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) result_xml = set_worksheet(xml_str) if '<ACTION>INSERTED</ACTION>' in result_xml: self.worksheet_id = int( get_xml_field_value(result_xml, 'WORKSHEET_ID')) if new_group_id != self.group_id: gr = self.parent_task_list.getGroupById(new_group_id) if gr is None: group_name = getCustomerNameById(new_group_id) if group_name is None: raise GuiException( 'Заказчик с ID равным %i не существет' % new_group_id) gr = task_group(self.parent_task_list) gr.setCaption(group_name) self.parent_task_list.addGroup(gr, new_group_id) old_group_id = self.group_id self.parent_task_list.moveItemToGroup(self.item_index, new_group_id) if self.parent_task_list.getItemsCountInGroup( old_group_id) == 0: if old_group_id != -1: self.parent_task_list.removeGroup(old_group_id) else: self.parent_task_list.hideNewItemGroup() self.setTaskType(new_task_type_id) self.setDesc(new_desc) self.setTime(new_time) self.stopEdit() except Exception as err: raise RaisedGuiException(err) finally: QApplication.restoreOverrideCursor()
def main(): app = tray_application( sys.argv ) initCache() user_id = tryLogin() if user_id == 0 and not DONT_EXIT_IF_CANT_CONNECT: sys.exit(0) else: # # Условия "get_last_error() != ERROR_CANT_CONNECT" никогда не будут выполняться # без установленного флага DONT_EXIT_IF_CANT_CONNECT, т.к. без этого флага, # в случае невозможности соединиться с базой, выполнение просто не дойдет до сюда. # # Флаг DONT_EXIT_IF_CANT_CONNECT предназначен только для отладочных целей и никогда # не должен использоваться в production-версиях. # if get_last_error() != ERROR_CANT_CONNECT: app.checkUpdates(False) try: QApplication.setOverrideCursor(QCursor(Qt.WaitCursor)) # # Тут получим даты последних обновлений справочников с сервера и из кэша # customers_updated_at = None task_types_updated_at = None dir_dates = get_directories_changed_at() customers_updated_at_str = getSetting('customers_updated_at') task_types_updated_at_str = getSetting('task_types_updated_at') if customers_updated_at_str is not None: customers_updated_at = datetime.strptime(customers_updated_at_str, CACHE_DATETIME_FORMAT) if task_types_updated_at_str is not None: task_types_updated_at = datetime.strptime(task_types_updated_at_str, CACHE_DATETIME_FORMAT) # # Если данные устарели, то удалим их, fillCache() подтянет их заново # if customers_updated_at is not None: if customers_updated_at < dir_dates['customers_changed_at']: deleteCacheData('customers') if task_types_updated_at is not None: if task_types_updated_at < dir_dates['task_types_changed_at']: deleteCacheData('task_types') if get_last_error() != ERROR_CANT_CONNECT: try: staff_id = get_staff_by_user(user_id) except: staff_id = None fillCache(dir_dates['server_time']) else: staff_id = None app.main_form = main_form() app.main_form.ui = Ui_frmMain() ui = app.main_form.ui ui.setupUi(app.main_form) ui.searchWidget.hide() app.main_form.setWindowTitle(PROGRAM_NAME_FULL) app.main_form.show() # # Other # QObject.connect( app.main_form.ui.tabWidget, SIGNAL('currentChanged(int)'), app.main_form.tabChanged ) try: xml = get_dinner_order_permissions() access = int(get_xml_field_value(xml, 'ACCESS_TO_ORDERS')) if access: view_all = int(get_xml_field_value(xml, 'VIEW_ALL_ORDERS')) if not view_all: ui.cmdAllDinnerOrdersToday.hide() else: ui.tabWidget.removeTab(ui.tabWidget.indexOf(ui.tabDinner)) except Exception as err: raise RaisedGuiException(err) # # Services # ui.treeServices.user_id = user_id ui.treeServices.updateServices() if not ui.treeServices.getItemsCount(): ui.tabWidget.removeTab(ui.tabWidget.indexOf(ui.tabServices)) # # Dinner # QObject.connect( ui.cmdRefreshMenu, SIGNAL('clicked()'), app.main_form.updateDinnerOrderPage ) QObject.connect( ui.cmdCreateOrder, SIGNAL('clicked()'), app.main_form.createDinnerOrder ) QObject.connect( ui.cmdAllDinnerOrdersToday, SIGNAL('clicked()'), app.main_form.printDinnerOrders ) if staff_id is not None: # # Tasks # app.main_form.tl = ui.tl app.main_form.tl.main_form = app.main_form app.main_form.tl.staff_id = staff_id ui.statusLabel.task_list = app.main_form.tl ui.countLabel.task_list = app.main_form.tl QObject.connect( app.main_form.tl, SIGNAL('totalCountChanged()'), ui.countLabel.updateCount ) QObject.connect( app.main_form.tl, SIGNAL('totalTimeChanged()'), ui.statusLabel.updateStatus ) QObject.connect( app.main_form.tl, SIGNAL('startEditItem()'), app.main_form.stopSearching ) QObject.connect( ui.cmdNew, SIGNAL('clicked()'), app.main_form.addTask ) QObject.connect( ui.cmdRefresh, SIGNAL('clicked()'), app.main_form.refreshTaskList ) QObject.connect( ui.cmdRefresh, SIGNAL('clicked()'), app.main_form.stopSearching ) QObject.connect( ui.cmdSearch, SIGNAL('clicked()'), app.main_form.startSearching ) QObject.connect( ui.cmdCancelSearch, SIGNAL('clicked()'), app.main_form.stopSearching ) QObject.connect( ui.txtSearchText, SIGNAL('textChanged(QString)'), app.main_form.searchForText ) QObject.connect( ui.dt, SIGNAL('dateChanged(QDate)'), app.main_form.tl.updateOnDate ) QObject.connect( ui.dt, SIGNAL('dateChanged(QDate)'), app.main_form.stopSearching ) app.main_form.ui.dt.setDate(QDate.currentDate()) # # Time # ui.tblWeek.staff_id = staff_id QObject.connect( ui.cmdComing, SIGNAL('clicked()'), app.main_form.setNewComingTime ) QObject.connect( ui.cmdLeaving, SIGNAL('clicked()'), app.main_form.setNewLeavingTime ) QObject.connect( ui.cmdRefreshTimeSheet, SIGNAL('clicked()'), ui.tblWeek.updateForCurrentWeek ) else: ui.tabWidget.removeTab(ui.tabWidget.indexOf(ui.tabTasks)) # # Скрываю ставшие ненужными табы # ui.tabWidget.removeTab(ui.tabWidget.indexOf(ui.tabTime)) ui.tabWidget.removeTab(ui.tabWidget.indexOf(ui.tabDinner)) app.main_form.changeCaption() finally: QApplication.restoreOverrideCursor() sys.exit( app.exec_() )
def get_new_in_version(): return get_xml_field_value( get_data_xml("GetAssistantVersionDescription", ""), 'VERSION_DESCRIPTION')
def get_program_version(): return int( get_xml_field_value(get_data_xml("GetAssistantVersion", ""), 'VERSION_NUMBER'))
def get_dinner_paths(): return get_xml_field_value(get_data_xml("GetDinnerPaths", ""), 'PATHS').split()