def usersList(context, main=None, add=None, filterinfo=None, session=None, params=None, curvalue=None, startswith=None, firstrecord=None, recordcount=None): u'''Функция list селектора типа элемента. ''' settings=Settings() recordList = ArrayList() #raise Exception(startswith, curvalue) if settings.isUseAuthServer() and settings.loginIsSubject(): sessionId=json.loads(session)["sessioncontext"]["sessionid"] server=SecurityParamsFactory.getAuthServerUrl() users_xml=getUsersFromAuthServer(server, sessionId) for user in users_xml.getElementsByTagName("user"): if startswith and string.find(user.getAttribute("name"), curvalue)==0 or \ not startswith and string.find(user.getAttribute("name"), curvalue)>0: rec = DataRecord() rec.setId(user.getAttribute("SID")) rec.setName(user.getAttribute("login")) recordList.add(rec) else: subject = subjectsCursor(context) subject.setFilter('name', "@%s'%s'%%" % ("%"*(not startswith), curvalue.replace("'","''"))) subject.orderBy('name') subject.limit(firstrecord, recordcount) for subject in subject.iterate(): rec = DataRecord() rec.setId(subject.sid) if subject.name is not None or subject.name!='': rec.setName(subject.name) else: rec.setName(u'[Имя не назначено!]') recordList.add(rec) return ResultSelectorData(recordList, 0)
def usersCount(context, main=None, add=None, filterinfo=None, session=None, params=None, curvalue=None, startswith=None): #raise Exception(params) settings = Settings() if settings.isUseAuthServer() and settings.loginIsSubject(): server = SecurityParamsFactory.getAuthServerUrl() sessionId = json.loads(session)["sessioncontext"]["sessionid"] users_xml = getUsersFromAuthServer(server, sessionId) count = 0 for user in users_xml.getElementsByTagName("user"): if startswith and string.find(user.getAttribute("name"), curvalue)==0 or \ not startswith and string.find(user.getAttribute("name"), curvalue)>0: count += 1 #count=len(users_xml.getElementsByTagName("user")) else: subject = subjectsCursor(context) #raise Exception(useAuthServer) subject.setFilter( 'name', "@%s'%s'%%" % ("%" * (not startswith), curvalue.replace("'", "''"))) count = subject.count() return ResultSelectorData(None, count)
def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None): u'''Функция данных для карточки редактирования содержимого таблицы ролей. ''' settings=Settings() #ru.curs.showcase.security.SecurityParamsFactory.getAuthServerUrl() rolesUsers = UserRolesCursor(context) currId = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'] rolesUsers.setRange("roleid", currId) content=[] if settings.isUseAuthServer() and settings.loginIsSubject(): sessionId=json.loads(session)["sessioncontext"]["sessionid"] server=SecurityParamsFactory.getAuthServerUrl() users_xml=getUsersFromAuthServer(server, sessionId) if rolesUsers.tryFindSet(): while True: for user in users_xml.getElementsByTagName("user"): if user.getAttribute("SID")==rolesUsers.userid: content.append({"@sid" : rolesUsers.userid, "@userName" : user.getAttribute("name") }) break if not rolesUsers.nextInSet(): break else: subjects = subjectsCursor(context) if rolesUsers.tryFindSet(): while True: if subjects.tryGet(rolesUsers.userid): content.append({"@sid" : subjects.sid, "@userName" : subjects.name }) if not rolesUsers.nextInSet(): break if content==[]: xformsdata = {"schema":{"users": "" } } else: xformsdata = {"schema":{"users": {"user": content} } } xformssettings = {"properties":{"event":{"@name":"single_click", "@linkId": "1", "action":{"#sorted":[{"main_context": "current"}, {"datapanel": {"@type": "current", "@tab": "current", "element": {"@id":"id_roles_grid", "add_context": ""} } }]} } } } return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)), XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))
def gridData(context, main=None, add=None, filterinfo=None, session=None, elementId=None, sortColumnList=None, firstrecord=None, pagesize=None): u'''Функция получения данных для грида списка пользователей. ''' session = json.loads(session)["sessioncontext"] settings = Settings() logins = loginsCursor(context) if sortColumnList: sortName = toHexForXml(sortColumnList[0].id) sortType = unicode(sortColumnList[0].sorting).lower() else: sortName = None # Определяем переменную для JSON данных data = {"records": {"rec": []}} _header = { "id": ["~~id"], "sid": [u"SID"], "userName": [u"Имя пользователя"], "subject": [u"Субъект"], "employee": [u"Сотрудник"], "properties": [u"properties"] } event = { "event": { "@name": "row_single_click", "action": { "#sorted": [{ "main_context": 'current' }, { "datapanel": { "@type": "current", "@tab": "current" } }] } } } for column in _header: _header[column].append(toHexForXml(_header[column][0])) isEmployees = settings.isEmployees() if isEmployees: employeesGrain = settings.getEmployeesParam("employeesGrain") employeesTable = settings.getEmployeesParam("employeesTable") employeesName = settings.getEmployeesParam( "employeesName") # название поля с именем employeesCursor = tableCursorImport(employeesGrain, employeesTable) employees = employeesCursor(context) if settings.isUseAuthServer(): sessionId = session[ "sessionid"] # получаем из контекста сессии Id сессии server = SecurityParamsFactory.getAuthServerUrl( ) # получаем url mellophone logins_xml = func.getUsersFromAuthServer( server, sessionId) # получаем xml с пользователями if settings.isUseAuthServer() and settings.loginIsSubject(): # грид состоит из колонок sid, имя пользователя и сотрудник subjects = subjectsCursor(context) for i, user in enumerate(logins_xml.getElementsByTagName("user")): if i < firstrecord - 1: continue # пропускаем элементы с 1 по firstrecord loginsDict = {} loginsDict[_header["id"][1]] = json.dumps( [user.getAttribute("login"), user.getAttribute("SID")]) loginsDict[_header["sid"][1]] = user.getAttribute("SID") loginsDict[_header["userName"][1]] = user.getAttribute("login") if isEmployees: # если таблица сотрудников существует (прописана в настройках) # добавляем в грид сотрудника колонку Сотрудник. if logins.tryGet(user.getAttribute("login")) and \ subjects.tryGet(logins.subjectId) and\ employees.tryGet(subjects.employeeId): loginsDict[_header["employee"][1]] = getattr( employees, employeesName) else: loginsDict[_header["employee"][1]] = '' loginsDict['properties'] = event data["records"]["rec"].append(loginsDict) if i >= firstrecord + pagesize: break # прерываем цикл после достижения записи № firstrecord + pagesize elif settings.isUseAuthServer(): # грид состоит из колонок sid, имя пользователя и субъект subjects = subjectsCursor(context) for i, user in enumerate(logins_xml.getElementsByTagName("user")): if i < firstrecord - 1: continue # пропускаем элементы с 1 по firstrecord loginsDict = {} loginsDict[_header["id"][1]] = user.getAttribute("login") loginsDict[_header["sid"][1]] = user.getAttribute("SID") loginsDict[_header["userName"][1]] = user.getAttribute("login") if logins.tryGet(user.getAttribute("login")) and subjects.tryGet( logins.subjectId): loginsDict[_header["subject"][1]] = subjects.name else: loginsDict[_header["subject"][1]] = '' loginsDict['properties'] = event data["records"]["rec"].append(loginsDict) if i >= firstrecord + pagesize: break # прерываем цикл после достижения записи № firstrecord + pagesize elif not settings.isUseAuthServer() and not settings.loginIsSubject(): # грид состоит из колонок имя пользователя и субъект subjects = subjectsCursor(context) logins.limit(firstrecord - 1, pagesize) for logins in logins.iterate(): loginsDict = {} loginsDict[_header["id"][1]] = logins.userName loginsDict[_header["userName"][1]] = logins.userName if subjects.tryGet(logins.subjectId): loginsDict[_header["subject"][1]] = subjects.name else: loginsDict[_header["subject"][1]] = "" loginsDict['properties'] = event data["records"]["rec"].append(loginsDict) else: # грид состоит из колонки имя пользователя subjects = subjectsCursor(context) logins.limit(firstrecord - 1, pagesize) for logins in logins.iterate(): loginsDict = {} loginsDict[_header["id"][1]] = logins.userName loginsDict[_header["userName"][1]] = logins.userName if isEmployees and subjects.tryGet( logins.subjectId) and employees.tryGet( subjects.employeeId): loginsDict[_header["employee"][1]] = getattr( employees, employeesName) else: loginsDict[_header["employee"][1]] = "" loginsDict['properties'] = event data["records"]["rec"].append(loginsDict) # сортировка if sortColumnList: data["records"]["rec"].sort(key=lambda x: (x[unicode(sortName)].lower()), reverse=(sortType == 'desc')) res = XMLJSONConverter.jsonToXml(json.dumps(data)) return JythonDTO(res, None)
def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None): u'''Функция получения настроек грида. ''' settings = Settings() if settings.isUseAuthServer(): server = SecurityParamsFactory.getAuthServerUrl() sessionId = json.loads(session)["sessioncontext"]["sessionid"] logins_xml = func.getUsersFromAuthServer(server, sessionId) totalcount = len(logins_xml.getElementsByTagName("user")) else: logins = loginsCursor(context) # Вычисляем количества записей в таблице totalcount = logins.count() # Заголовок таблицы _header = { "sid": [u"SID"], "userName": [u"Имя пользователя"], "subject": [u"Субъект"], "employee": [u"Сотрудник"] } gridSettings = {} if settings.loginIsSubject(): number = 1 else: number = 2 gridSettings["gridsettings"] = { "columns": { "col": [] }, "properties": { "@pagesize": "50", "@gridWidth": "100%", "@gridHeight": getGridHeight(session, number, delta=40), "@totalCount": totalcount }, "labels": { "header": u"Пользователи" }, } # добавляем поля для отображения в gridsettings if settings.isUseAuthServer(): gridSettings["gridsettings"]["columns"]["col"].append({ "@id": _header["sid"][0], "@width": "320px" }) gridSettings["gridsettings"]["columns"]["col"].append({ "@id": _header["userName"][0], "@width": "320px" }) if settings.loginIsSubject() and settings.isEmployees(): gridSettings["gridsettings"]["columns"]["col"].append({ "@id": _header["employee"][0], "@width": "640px" }) elif not settings.loginIsSubject(): gridSettings["gridsettings"]["columns"]["col"].append({ "@id": _header["subject"][0], "@width": "640px" }) # Добавляем поля для отображения в gridsettings res = XMLJSONConverter.jsonToXml(json.dumps(gridSettings)) return JythonDTO(None, res)