def cardDataSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None): u'''Функция сохранения карточки редактирования содержимого справочника разрешений. ''' numbersSeries = numbersSeriesCursor(context) content = json.loads(xformsdata)["schema"]["numbersSeries"] #raise Exception(permissions.meta().getColumns()) # for field in permissions.meta().getColumns(): # permissions.__setattr__(field, content[field]) numbersSeries.id = content["@id"] numbersSeries.description = content["@description"] if add == 'add' and numbersSeries.canInsert() and numbersSeries.canModify(): if not numbersSeries.tryInsert(): numbersSeriesOld = numbersSeriesCursor(context) numbersSeriesOld.get(content["@id"]) numbersSeries.recversion = numbersSeriesOld.recversion numbersSeries.update() elif add == 'add' and numbersSeries.canInsert(): numbersSeries.insert() elif add == 'edit' and numbersSeries.canModify(): numbersSeriesOld = numbersSeriesCursor(context) numberSeriesTemp = numbersSeriesCursor(context) currId = json.loads(session)['sessioncontext']['related']['gridContext']['currentRecordId'] numbersSeriesOld.get(currId) if numbersSeriesOld.id==numbersSeries.id: numbersSeries.recversion = numbersSeriesOld.recversion numbersSeries.update() elif numberSeriesTemp.tryGet(content["@id"]): context.error(u'Серия номеров с данным ID уже существует. Данные не сохранены!') elif numbersSeries.canInsert(): linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) linesOfNumbersSeriesTemp = linesOfNumbersSeriesCursor(context) linesOfNumbersSeries.setRange('seriesId', numbersSeriesOld.id) numbersSeries.insert() if linesOfNumbersSeriesTemp.canInsert(): for linesOfNumbersSeries in linesOfNumbersSeries.iterate(): linesOfNumbersSeriesTemp.get(linesOfNumbersSeries.seriesId, linesOfNumbersSeries.numberOfLine) linesOfNumbersSeriesTemp.seriesId = numbersSeries.id linesOfNumbersSeriesTemp.insert() else: raise CelestaException(u"Недостаточно прав для данной операции!") linesOfNumbersSeries.deleteAll() numbersSeriesOld.delete() else: raise CelestaException(u"Недостаточно прав для данной операции!") else: raise CelestaException(u"Недостаточно прав для данной операции!")
def linesNumbersSeriesDownload(context, main=None, add=None, filterinfo=None, session=None, elementId=None, data=None): linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) fileName = 'linesOfNumbersSeries' return tableDownload(linesOfNumbersSeries, fileName)
def linesNumbersSeriesUpload(context, main=None, add=None, filterinfo=None, session=None, elementId=None, data=None, fileName=None, file=None): linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) exchange = DataBaseXMLExchange(file, linesOfNumbersSeries) exchange.uploadXML() return context.message(u"Данные успешно загружены в таблицу")
def cardDelete(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None): currentRecordId = json.loads( session)['sessioncontext']['related']['gridContext']['currentRecordId'] numbersSeries = numbersSeriesCursor(context) linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) linesOfNumbersSeries.setRange("seriesId", currentRecordId) linesOfNumbersSeries.deleteAll() numbersSeries.get(currentRecordId) numbersSeries.delete()
def cardDelete(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None): linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) #raise Exception(session) gridContext = json.loads( session)['sessioncontext']['related']['gridContext'] gridContext = gridContext if isinstance(gridContext, list) else [gridContext] currentId = {} for gc in gridContext: currentId[gc["@id"]] = gc["currentRecordId"] linesOfNumbersSeries.get(currentId["numbersSeriesGrid"], int(currentId["linesNumbersSeriesGrid"])) linesOfNumbersSeries.delete()
def getNextNoOfSeries(context, seriesId, linesOfNumbersSeries=None, updateNum=True): lonsFlag = False if linesOfNumbersSeries is None: linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) lonsFlag = True linesOfNumbersSeries.setRange('seriesId', seriesId) linesOfNumbersSeries.setRange('isOpened', True) linesOfNumbersSeries.setRange('startingDate', datetime.strptime('1900-01-01', '%Y-%m-%d'), datetime.today()) if linesOfNumbersSeries.count() > 1: raise Exception( "There is more than one opened line in the series '%s'" % seriesId) if linesOfNumbersSeries.tryFindSet(): seriesObject = GettingNextNumberOfSeries( seriesId, linesOfNumbersSeries.lastUsedNumber, linesOfNumbersSeries.startingNumber, linesOfNumbersSeries.endingNumber, linesOfNumbersSeries.incrimentByNumber, linesOfNumbersSeries.isFixedLength) nextNum = seriesObject.getNextNum() linesOfNumbersSeries.lastUsedNumber = int(nextNum) linesOfNumbersSeries.lastUsedDate = datetime.today() if updateNum: linesOfNumbersSeries.update() prefix = linesOfNumbersSeries.prefix postfix = linesOfNumbersSeries.postfix if lonsFlag: linesOfNumbersSeries.close() return '%s%s%s' % (prefix, nextNum, postfix) else: CelestaException( "There are no available opened lines in the series '%s'!" % seriesId)
def cardData(context, main=None, add=None, filterinfo=None, session=None, elementId=None): u'''Функция данных для карточки редактирования содержимого таблицы разрешения. ''' gridContext = json.loads( session)['sessioncontext']['related']['gridContext'] gridContext = gridContext if isinstance(gridContext, list) else [gridContext] currentId = {} for gc in gridContext: if "currentRecordId" in gc.keys(): currentId[gc["@id"]] = gc["currentRecordId"] if add == 'add': if "numbersSeriesGrid" in currentId.keys(): seriesId = currentId["numbersSeriesGrid"] else: seriesId = '' xformsdata = { "schema": { "numberSeries": { "@seriesId": seriesId, "@numberOfLine": "", "@startingDate": "", "@startingNumber": "", "@endingNumber": "", "@incrimentByNumber": "", "@lastUsedNumber": "", "@isOpened": "", "@lastUsedDate": "", "@prefix": "", "@postfix": "", "@isFixedLength": "" } } } elif add == 'edit': sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS") linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) linesOfNumbersSeries.get(currentId["numbersSeriesGrid"], int(currentId["linesNumbersSeriesGrid"])) xformsdata = { "schema": { "numberSeries": { "@seriesId": linesOfNumbersSeries.seriesId, "@numberOfLine": linesOfNumbersSeries.numberOfLine, "@startingDate": unicode(sdf.format(linesOfNumbersSeries.startingDate)), "@startingNumber": linesOfNumbersSeries.startingNumber, "@endingNumber": linesOfNumbersSeries.endingNumber, "@incrimentByNumber": linesOfNumbersSeries.incrimentByNumber, "@lastUsedNumber": linesOfNumbersSeries.lastUsedNumber, "@isOpened": unicode(linesOfNumbersSeries.isOpened).lower(), "@lastUsedDate": unicode(sdf.format(linesOfNumbersSeries.lastUsedDate)), "@prefix": linesOfNumbersSeries.prefix, "@postfix": linesOfNumbersSeries.postfix, "@isFixedLength": unicode(linesOfNumbersSeries.isFixedLength).lower() } } } # print xformsdata xformssettings = { "properties": { "event": { "@name": "single_click", "@linkId": "1", "action": { "#sorted": [{ "main_context": "current" }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesGrid", "add_context": "" } } }] } } } } return JythonDTO(XMLJSONConverter.jsonToXml(json.dumps(xformsdata)), XMLJSONConverter.jsonToXml(json.dumps(xformssettings)))
def cardDataSave(context, main=None, add=None, filterinfo=None, session=None, elementId=None, xformsdata=None): u'''Функция сохранения карточки редактирования содержимого справочника разрешений. ''' linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) content = json.loads(xformsdata)["schema"]["numberSeries"] #raise Exception(xformsdata) sdf = SimpleDateFormat("yyyy-MM-dd") linesOfNumbersSeries.seriesId = content["@seriesId"] linesOfNumbersSeries.numberOfLine = int(content["@numberOfLine"]) if content["@startingDate"] == '': linesOfNumbersSeries.startingDate = sdf.parse( datetime.datetime.fromtimestamp(time.time()).strftime("%Y-%m-%d")) else: linesOfNumbersSeries.startingDate = sdf.parse(content["@startingDate"]) linesOfNumbersSeries.startingNumber = content["@startingNumber"] linesOfNumbersSeries.endingNumber = content["@endingNumber"] linesOfNumbersSeries.incrimentByNumber = content["@incrimentByNumber"] linesOfNumbersSeries.isOpened = content["@isOpened"] == "true" if content["@lastUsedDate"] <> '': linesOfNumbersSeries.lastUsedDate = sdf.parse(content["@lastUsedDate"]) linesOfNumbersSeries.prefix = content["@prefix"] linesOfNumbersSeries.postfix = content["@postfix"] linesOfNumbersSeries.isFixedLength = content["@isFixedLength"] == "true" if add == 'add' and linesOfNumbersSeries.canInsert( ) and linesOfNumbersSeries.canModify(): if content["@lastUsedNumber"] == '': linesOfNumbersSeries.lastUsedNumber = int( content["@startingNumber"]) else: linesOfNumbersSeries.lastUsedNumber = int( content["@lastUsedNumber"]) if not linesOfNumbersSeries.tryInsert(): linesOfNumbersSeriesOld = linesOfNumbersSeriesCursor(context) linesOfNumbersSeriesOld.get(content["@seriesId"], int(content["@numberOfLine"])) linesOfNumbersSeries.recversion = linesOfNumbersSeriesOld.recversion linesOfNumbersSeries.update() elif add == 'add' and linesOfNumbersSeries.canInsert(): if content["@lastUsedNumber"] == '': linesOfNumbersSeries.lastUsedNumber = int( content["@startingNumber"]) else: linesOfNumbersSeries.lastUsedNumber = int( content["@lastUsedNumber"]) linesOfNumbersSeries.insert() elif add == 'edit' and linesOfNumbersSeries.canModify(): linesOfNumbersSeriesOld = linesOfNumbersSeriesCursor(context) linesOfNumberSeriesTest = linesOfNumbersSeriesCursor(context) gridContext = json.loads( session)['sessioncontext']['related']['gridContext'] gridContext = gridContext if isinstance(gridContext, list) else [gridContext] currentId = {} for gc in gridContext: if "currentRecordId" in gc.keys(): currentId[gc["@id"]] = gc["currentRecordId"] linesOfNumbersSeriesOld.get(currentId["numbersSeriesGrid"], int(currentId["linesNumbersSeriesGrid"])) if content["@lastUsedNumber"] == '': linesOfNumbersSeries.lastUsedNumber = linesOfNumbersSeriesOld.lastUsedNumber else: linesOfNumbersSeries.lastUsedNumber = int( content["@lastUsedNumber"]) if linesOfNumbersSeriesOld.numberOfLine == linesOfNumbersSeries.numberOfLine: #linesOfNumbersSeriesOld.seriesId==linesOfNumbersSeries.seriesId and \ linesOfNumbersSeries.recversion = linesOfNumbersSeriesOld.recversion linesOfNumbersSeries.update() elif linesOfNumberSeriesTest.tryGet( linesOfNumbersSeries.seriesId, int(linesOfNumbersSeries.numberOfLine)): context.error(u'Серия с данным номером уже существует.') elif linesOfNumbersSeries.canInsert(): linesOfNumbersSeriesOld.delete() linesOfNumbersSeries.insert() else: raise CelestaException(u"Недостаточно прав для данной операции!") else: raise CelestaException(u"Недостаточно прав для данной операции!")
def gridMeta(context, main=None, add=None, filterinfo=None, session=None, elementId=None): u'''Функция получения настроек грида. ''' # Курсор таблицы permissions linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) # Вычисляем количества записей в таблице totalcount = linesOfNumbersSeries.count() # Заголовок таблицы header = "Серии номеров" # В случае если таблица пустая if totalcount == 0 or totalcount is None: totalcount = "0" header = header + " ПУСТ" # Определяем список полей таблицы для отображения settings = {} settings["gridsettings"] = { "columns": { "col": [] }, "properties": { "@pagesize": "50", "@gridWidth": "100%", "@totalCount": totalcount, "@profile": "default.properties" }, "labels": { "header": header } } # Добавляем поля для отображения в gridsettings settings["gridsettings"]["columns"]["col"].append({ "@id": "Номер серии", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Начальная дата", "@width": "100px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Начальный номер", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Последний номер", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Инкремент", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Последний использованный номер", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Используется", "@width": "80px", "@type": "IMAGE" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Дата последнего использования", "@width": "80px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Префикс", "@width": "100px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Постфикс", "@width": "100px" }) settings["gridsettings"]["columns"]["col"].append({ "@id": "Фиксированная длина", "@width": "80px", "@type": "IMAGE" }) res = XMLJSONConverter.jsonToXml(json.dumps(settings)) return JythonDTO(None, res)
def gridToolBar(context, main=None, add=None, filterinfo=None, session=None, elementId=None): u'''Toolbar для грида. ''' gridContextList = json.loads( session)['sessioncontext']['related']['gridContext'] gridContextList = gridContextList if isinstance( gridContextList, list) else [gridContextList] for gridContext in gridContextList: if gridContext['@id'] == 'linesNumbersSeriesGrid': break if 'currentRecordId' not in gridContext: style = "true" else: style = "false" data = {"gridtoolbar": {"item": []}} # Курсор таблицы permissions linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) if linesOfNumbersSeries.canInsert(): data["gridtoolbar"]["item"].append({ "@img": 'gridToolBar/addDirectory.png', "@text": "Добавить", "@hint": "Добавить", "@disable": "false", "action": { "@show_in": "MODAL_WINDOW", "#sorted": [{ "main_context": "current" }, { "modalwindow": { "@caption": "Добавление серии", "@height": "500", "@width": "500" } }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesXforms", "add_context": "add" } } }] } }) if linesOfNumbersSeries.canModify(): data["gridtoolbar"]["item"].append({ "@img": 'gridToolBar/editDocument.png', "@text": "Редактировать", "@hint": "Редактировать", "@disable": style, "action": { "@show_in": "MODAL_WINDOW", "#sorted": [{ "main_context": "current" }, { "modalwindow": { "@caption": "Редактирование серии", "@height": "500", "@width": "500" } }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesXforms", "add_context": "edit" } } }] } }) if linesOfNumbersSeries.canDelete(): data["gridtoolbar"]["item"].append({ "@img": 'gridToolBar/deleteDocument.png', "@text": "Удалить", "@hint": "Удалить", "@disable": style, "action": { "@show_in": "MODAL_WINDOW", "#sorted": [{ "main_context": "current" }, { "modalwindow": { "@caption": "Удаление серии", "@height": "300", "@width": "450" } }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesXformDelete", "add_context": "delete" } } }] } }) data["gridtoolbar"]["item"].append({ "@img": 'gridToolBar/arrowDown.png', "@text": "Скачать", "@hint": "Скачать экземпляры серий номеров в xml", "@disable": "false", "action": { "@show_in": "MODAL_WINDOW", "#sorted": [{ "main_context": "current" }, { "modalwindow": { "@caption": "Скачать экземпляры серий номеров", "@height": "300", "@width": "450" } }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesDownloadXform", "add_context": "download" } } }] } }) data["gridtoolbar"]["item"].append({ "@img": 'gridToolBar/arrowUp.png', "@text": "Загрузить", "@hint": "Загрузить экземпляры серий номеров из xml", "@disable": "false", "action": { "@show_in": "MODAL_WINDOW", "#sorted": [{ "main_context": "current" }, { "modalwindow": { "@caption": "Загрузить экземпляры серий номеров", "@height": "300", "@width": "450" } }, { "datapanel": { "@type": "current", "@tab": "current", "element": { "@id": "linesNumbersSeriesUploadXform", "add_context": "upload" } } }] } }) return XMLJSONConverter.jsonToXml(json.dumps(data))
def gridData(context, main=None, add=None, filterinfo=None, session=None, elementId=None, sortColumnList=[], firstrecord=0, pagesize=50): u'''Функция получения данных для грида. ''' linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) if 'currentRecordId' in session: currId = json.loads(session)['sessioncontext']['related'][ 'gridContext']['currentRecordId'] linesOfNumbersSeries.setRange("seriesId", currId) # Определяем переменную для JSON данных data = {"records": {"rec": []}} linesOfNumbersSeries.limit(firstrecord - 1, pagesize) # Проходим по таблице и заполняем data for linesOfNumbersSeries in linesOfNumbersSeries.iterate(): linesDict = {} linesDict[toHexForXml('~~id')] = linesOfNumbersSeries.numberOfLine linesDict[toHexForXml( u"Номер серии")] = linesOfNumbersSeries.numberOfLine linesDict[toHexForXml(u"Начальная дата")] = SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(linesOfNumbersSeries.startingDate)\ if linesOfNumbersSeries.startingDate\ else linesOfNumbersSeries.startingDate linesDict[toHexForXml( u"Начальный номер")] = linesOfNumbersSeries.startingNumber linesDict[toHexForXml( u"Последний номер")] = linesOfNumbersSeries.endingNumber linesDict[u"Инкремент"] = linesOfNumbersSeries.incrimentByNumber linesDict[toHexForXml(u"Последний использованный номер" )] = linesOfNumbersSeries.lastUsedNumber linesDict[ u"Используется"] = 'gridToolBar/yes.png' if linesOfNumbersSeries.isOpened else 'gridToolBar/no.png' linesDict[toHexForXml(u"Дата последнего использования")] = SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(linesOfNumbersSeries.lastUsedDate)\ if linesOfNumbersSeries.lastUsedDate\ else linesOfNumbersSeries.lastUsedDate linesDict[u"Префикс"] = linesOfNumbersSeries.prefix linesDict[u"Постфикс"] = linesOfNumbersSeries.postfix linesDict[toHexForXml( u"Фиксированная длина" )] = 'gridToolBar/yes.png' if linesOfNumbersSeries.isFixedLength else 'gridToolBar/no.png' linesDict['properties'] = { "event": { "@name": "row_single_click", "action": { "#sorted": [{ "main_context": 'current' }, { "datapanel": { '@type': "current", '@tab': "current" } }] } } } data["records"]["rec"].append(linesDict) res = XMLJSONConverter.jsonToXml(json.dumps(data)) return JythonDTO(res, None)
def securityInit(context): u"""Функция устанавливает необходимые для работы гранулы значения таблиц: numbersSeries linesOfNumbersSeries customPermsTypes customPerms rolesCustomPerms """ numbersSeries = numbersSeriesCursor(context) linesOfNumbersSeries = linesOfNumbersSeriesCursor(context) numbersSeries.id = 'subjects' numbersSeries.description = 'subjects' if not numbersSeries.tryInsert(): numbersSeries.update() if not linesOfNumbersSeries.tryGet('subjects', 1): # sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") now = datetime.datetime.now()#fromtimestamp(time.time()).strftime("%Y-%m-%d %H:%M:%S") linesOfNumbersSeries.seriesId = 'subjects' linesOfNumbersSeries.numberOfLine = 1 linesOfNumbersSeries.startingDate = now#sdf.parse(now) linesOfNumbersSeries.startingNumber = 10 linesOfNumbersSeries.endingNumber = 100000 linesOfNumbersSeries.incrimentByNumber = 1 linesOfNumbersSeries.isOpened = True linesOfNumbersSeries.prefix = 'subject-' linesOfNumbersSeries.postfix = '-' linesOfNumbersSeries.isFixedLength = False linesOfNumbersSeries.insert() # Добавили серии номеров для таблицы subjects customPermsTypes = customPermsTypesCursor(context) if not customPermsTypes.tryGet('navigator'): customPermsTypes.name='navigator' customPermsTypes.description=u'Пункты меню навигатора' customPermsTypes.insert() # Добавили (если еще нет) тип разрешений "Пункты меню навигатора" customPerms = customPermsCursor(context) if not customPerms.tryGet('loginsSubjectsPoint'): customPerms.name='loginsSubjectsPoint' customPerms.description=u'Разрешение на отображение пункта меню Сотрудники и Пользователи' customPerms.type='navigator' customPerms.insert() if not customPerms.tryGet('rolesPoint'): customPerms.name='rolesPoint' customPerms.description=u'Разрешение на отображение пункта меню Роли' customPerms.type='navigator' customPerms.insert() if not customPerms.tryGet('permissionsPoint'): customPerms.name='permissionsPoint' customPerms.description=u'Разрешение на отображение пункта меню Разрешения' customPerms.type='navigator' customPerms.insert() if not customPerms.tryGet('numbersSeriesPoint'): customPerms.name='numbersSeriesPoint' customPerms.description=u'Разрешение на отображение пункта меню Серии номеров' customPerms.type='navigator' customPerms.insert() # Добавили (если еще нет) разрешения на отображения пунктов меню гранул common и security rolesCustomPerms = rolesCustomPermsCursor(context) if not rolesCustomPerms.tryGet('editor', 'loginsSubjectsPoint'): rolesCustomPerms.roleid='editor' rolesCustomPerms.permissionId='loginsSubjectsPoint' rolesCustomPerms.insert() if not rolesCustomPerms.tryGet('editor', 'rolesPoint'): rolesCustomPerms.roleid='editor' rolesCustomPerms.permissionId='rolesPoint' rolesCustomPerms.insert() if not rolesCustomPerms.tryGet('editor', 'permissionsPoint'): rolesCustomPerms.roleid='editor' rolesCustomPerms.permissionId='permissionsPoint' rolesCustomPerms.insert() if not rolesCustomPerms.tryGet('editor', 'numbersSeriesPoint'): rolesCustomPerms.roleid='editor' rolesCustomPerms.permissionId='numbersSeriesPoint' rolesCustomPerms.insert() #Привязываем добавленные разрешения к роли editor # Уже неактуально, так как функция userHasPermission возвращает True в любом случае, если роль - editor