def saveDashboardAjax(request): ''' save user's omdashboard setting input: request return: json author: Arthur ''' #Server Side Rule Check username = request.user.username postdata = getPostdata(request) if username: require_field = ['content'] checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #static variable dashboard = OmDashboard.objects.get_or_create(user=request.user)[0] setattr(dashboard, "content", postdata.get('content', '')) dashboard.save() info('%s update Dashboard success' % username, request) return ResponseAjax(statusEnum.success, _('儲存成功')).returnJSON() else: info('%s update Dashboard error' % username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s update Dashboard with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def getFormObjAjax(request): ''' load service_object's form_object return: json author: Arthur ''' username = request.user.username postdata = getPostdata(request) result = {} if username: require_field = ['api_path'] checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': flow_uuid = FlowActiveGlobalObject.APIgetUUID( postdata.get('api_path')) thisQuery = list( FlowActive.objects.filter(flow_uuid=flow_uuid, undeploy_flag=False).values( 'formobject', 'attachment')) if len(thisQuery): result = thisQuery[0] language = get_language() app_id = FlowActiveGlobalObject.UUIDSearch( flow_uuid).flow_app_id formobject = Translator('formobject', 'active', language, app_id, None).Do(result['formobject']) result['formobject'] = json.dumps(formobject) return ResponseAjax(statusEnum.success, _('讀取成功。'), result).returnJSON() else: error('%s get form_object with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def saveServiceAjax(request): ''' save manager's service setting input: request return: json author: Arthur ''' #Server Side Rule Check username = request.user.username postdata = getPostdata(request) if username: require_field = ['content'] checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #是否存入翻譯 lan_package = postdata.get('lan_package', None) if lan_package: FlowActiveGlobalObject.setSysLanDict("service", None, lan_package) #static variable box_object = json.loads(postdata.get('content', '')) OmServiceDesign.objects.create( content=json.dumps(box_object), language_package=json.dumps( FlowActiveGlobalObject.getSysLanDict('service'))) OmService.objects.all().delete() ServiceList = [] for key in box_object["list"]: thisSer = box_object["list"][key] if thisSer["type"] == "service": flow_uuid = FlowActiveGlobalObject.APIgetUUID( thisSer['api_path']) ser = OmService(service_id=thisSer['id'], flow_uuid=flow_uuid, role=thisSer['setting']['setRole'], default_value=json.dumps( thisSer['default_value'])) ServiceList.append(ser) OmService.objects.bulk_create(ServiceList) info('%s update Service success' % username, request) return ResponseAjax(statusEnum.success, _('儲存成功。')).returnJSON() else: info('%s update Service error' % username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s update Service with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def requestAjax(request): ''' send user's service request return: json author: Arthur ''' username = request.user.username postdata = request.POST.copy() files = request.FILES.getlist('files', '') result = {} #print(postdata) if username: require_field = ['api_path', 'service_id', 'formdata'] checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #判斷權限 postdata['flow_uuid'] = FlowActiveGlobalObject.APIgetUUID( postdata.get('api_path')) thisQuery = list( OmService.objects.filter( service_id=postdata.get('service_id'))) if len(thisQuery): service_obj = thisQuery[0] #print(service_obj.default_value) service_obj = json.loads(service_obj.default_value) postdata["formdata"] = json.loads(postdata["formdata"]) for default_col in service_obj: postdata["formdata"].append(default_col) postdata["formdata"] = json.dumps(postdata["formdata"]) else: info('%s update Service error' % username, request) return ResponseAjax(statusEnum.error, _('查無此服務。')).returnJSON() result = createOmData(postdata, request.user.username, files) if result['status']: return ResponseAjax(statusEnum.success, result['message']).returnJSON() else: return ResponseAjax(statusEnum.not_found, result['message']).returnJSON() else: return ResponseAjax(statusEnum.not_found, _('缺少必填欄位。')).returnJSON() else: error('%s request_service with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def listFilesAjax(request): ''' list files input: request return: list author: Kolin Hsu ''' if request.user.is_superuser: #function variable field_list = [] query = '' #server side rule check require_field = ['app_name'] postdata = getPostdata(request) checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #get post data app_name = postdata.get('app_name', '') createtime = postdata.get('createtime', '') if app_name == 'ommessage': field_list = ['file__icontains'] query = MessageHistoryFiles.objects.filter( delete=False, createtime__lte=createtime).values('file', 'size', 'createtime', 'main_id') if app_name == 'omformflow': field_list = ['file__icontains'] query = OmdataFiles.objects.filter( delete=False, createtime__lte=createtime).values('file', 'size', 'createtime') if field_list or query: result = DatatableBuilder(request, query, field_list) info('%s list file success.' % request.user.username, request) return JsonResponse(result) else: info('%s list file error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, _('請提供正確的APP名稱。')).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s has no permission.' % request.user.username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def importTranslationAjax(request): ''' import service language package input: request return: json author: Arthur ''' #function variable require_field = ['language'] #server side rule check postdata = getPostdata(request) language_str = postdata.get('language_list', '') language = postdata.get('language', '') checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #wa = WorkspaceApplication.objects.get(id=app_id) #language_dict = json.loads(wa.language_package) max = OmServiceDesign.objects.all().aggregate(Max('id')).get('id__max') this_service = OmServiceDesign.objects.get(id=max) language_dict = json.loads(this_service.language_package) temp_dict = {} language_list = language_str.split('\r\n') for line in language_list: if line: sp_index = line.find(':') if line[:sp_index] == 'original': key = line[sp_index + 1:] else: temp_dict[key] = line[sp_index + 1:] language_dict[language] = temp_dict language_str = json.dumps(language_dict) this_service.language_package = language_str this_service.save() #set global FlowActiveGlobalObject.setSysLanDict("service", language, temp_dict) info('%s import language package success.' % request.user.username, request) return ResponseAjax(statusEnum.success, _('匯入成功。')).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, checker.get('message', ''), checker).returnJSON()
def deleteFilesAjax(request): ''' delete files input: request return: status author: Kolin Hsu ''' if request.user.is_superuser: #server side rule check require_field = ['app_name', 'path'] postdata = getPostdata(request) checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': #get post data app_name = postdata.get('app_name', '') path_list = postdata.get('path', '') if app_name == 'ommessage': for path in path_list: file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.isfile(file_path): os.remove(file_path) messagehistoryfile = MessageHistoryFiles.objects.get( file=path) messagehistoryfile.delete = True messagehistoryfile.save() elif app_name == 'omformflow': for path in path_list: file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.isfile(file_path): os.remove(file_path) omdatafiles = OmdataFiles.objects.get(file=path) omdatafiles.delete = True omdatafiles.save() info('%s delete file success.' % request.user.username, request) return ResponseAjax(statusEnum.success, _('刪除成功。')).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s has no permission.' % request.user.username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def deletePositionAjax(request): ''' delete position input: request return: json author: Kolin Hsu ''' #function variable require_field = ['id'] #server side rule check postdata = getPostdata(request) checker = DataChecker(postdata, require_field) #get post data id_list = postdata.get('id','') if checker.get('status') == 'success': Position.objects.filter(id__in=id_list).delete() info('%s update position success.' % request.user.username,request) return ResponseAjax(statusEnum.success, _('刪除成功。')).returnJSON() else: info('%s missing some require variable or the variable type error.' % request.user.username,request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON()
def updatePositionAjax(request): ''' update position input: request return: json author: Kolin Hsu ''' #function variable require_field = ['id'] #server side rule check postdata = getPostdata(request) checker = DataChecker(postdata, require_field) #get post data pos_id = postdata.get('id','') display_name = postdata.get('display_name','') description = postdata.get('description','') if checker.get('status') == 'success': Position.objects.filter(id=pos_id).update(display_name=display_name,description=description) info('%s update position success.' % request.user.username,request) return ResponseAjax(statusEnum.success, _('更新成功。')).returnJSON() else: info('%s missing some require variable or the variable type error.' % request.user.username,request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON()
def updateGridAjax(request): ''' update grid information input: request return: json author: Arthur ''' username = request.user.username postdata = getPostdata(request) #判斷必填 require_field = ['content'] checker = DataChecker(postdata, require_field) result = {} result["labels"] = [] result["dataset"] = [] if username and checker.get('status') == 'success': #static variable error_message = "" QueryJson = json.loads(postdata.get('content')) # QueryJson = { # "type":"word", # "form":"OmUser_View", # "column":[ # { # "column":"department", # "value":"max" # }, # ], # "time_range":"this_year", # #"groupby":["gender"], # "orderby":[] # } #thisQuery = OmUser.objects.filter(updatetime__lte=datetime.date.today()).aggregate(**{"max":Max("department")}) has_group = False if "groupby" in QueryJson: for key in QueryJson["groupby"]: if len(key): has_group = True gte_list = [] lt_list = [] #判斷圖片類型 if "type" in QueryJson and "form" in QueryJson: #判斷時間格式 if "time_range" in QueryJson: today = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) #print(today.strftime("%Y-%m-%d %H:%M:%S")) if QueryJson["time_range"] == "today": gte_list.append(today) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(hours=1)) #print((gte_list[0] + datetime.timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")) result["labels"].append('00:00') for i in range(23): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(hours=1)) result["labels"].append(switch00(i + 1) + ':00') #else: #lt_list.appecnd(gte_list[0] + datetime.timedelta(days=1)) #result["labels"].append(_('今日')) elif QueryJson["time_range"] == "yesterday": gte_list.append(today - datetime.timedelta(days=1)) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(hours=1)) result["labels"].append('00:00') for i in range(23): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(hours=1)) result["labels"].append(switch00(i + 1) + ':00') #else: #lt_list.append(today) #result["labels"].append(_('昨日')) elif QueryJson["time_range"] == "this_week": gte_list.append(today - datetime.timedelta(days=today.weekday())) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(days=1)) result["labels"].append(translateW(1)) for i in range(6): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(days=1)) result["labels"].append(translateW(i + 2)) #else: #lt_list.append(today + datetime.timedelta(days=-today.weekday(), weeks=1)) #result["labels"].append(_('本周')) elif QueryJson["time_range"] == "last_week": gte_list.append( today - datetime.timedelta(days=today.weekday(), weeks=1)) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(days=1)) result["labels"].append(translateW(1)) for i in range(6): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(days=1)) result["labels"].append(translateW(i + 2)) #else: #lt_list.append(today - datetime.timedelta(days=today.weekday())) #result["labels"].append(_('上周')) elif QueryJson["time_range"] == "this_month": gte_list.append(today.replace(day=1)) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(days=1)) result["labels"].append( str(gte_list[0].month) + '/' + str(gte_list[0].day)) for i in range(monthrange(today.year, today.month)[1] - 1): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(days=1)) result["labels"].append( str(lt_list[i].month) + '/' + str(lt_list[i].day)) #else: #lt_list.append(gte_list[0] + datetime.timedelta(days=monthrange(gte_list[0].year, gte_list[0].month)[1])) #result["labels"].append(_('今月')) elif QueryJson["time_range"] == "last_month": if today.month == 1: gte_list.append(today.replace( day=1, month=switchM(today.month - 1)), year=today.year - 1) else: gte_list.append( today.replace(day=1, month=switchM(today.month - 1))) #if has_group: lt_list.append(gte_list[0] + datetime.timedelta(days=1)) result["labels"].append( str(gte_list[0].month) + '/' + str(gte_list[0].day)) for i in range( monthrange(today.year, switchM(today.month - 1))[1] - 1): gte_list.append(lt_list[i]) lt_list.append(lt_list[i] + datetime.timedelta(days=1)) result["labels"].append( str(lt_list[i].month) + '/' + str(lt_list[i].day)) #else: #lt_list.append(today.replace(day=1)) #result["labels"].append(_('上月')) elif QueryJson["time_range"] == "this_year": gte_list.append(today.replace(day=1, month=1)) #if has_group: lt_list.append(gte_list[0].replace(month=2)) result["labels"].append(translateM(1)) for i in range(11): gte_list.append(lt_list[i]) result["labels"].append(translateM(i + 2)) if i != 11: lt_list.append( lt_list[i].replace(month=switchM(i + 3))) else: lt_list.append( today.replace(year=today.year + 1, day=1, month=1)) #else: #lt_list.append(today.replace(year=today.year+1,day=1,month=1)) #result["labels"].append(_('今年')) elif QueryJson["time_range"] == "last_year": gte_list.append( today.replace(year=today.year - 1, day=1, month=1)) #if has_group: lt_list.append(gte_list[0].replace(month=2)) result["labels"].append(translateM(1)) for i in range(11): gte_list.append(lt_list[i]) result["labels"].append(translateM(i + 2)) if i != 11: lt_list.append( lt_list[i].replace(month=switchM(i + 3))) else: lt_list.append(today.replace(day=1, month=1)) #else: #lt_list.append(today.replace(day=1,month=1)) #result["labels"].append(_('去年')) else: gte_list.append(today.replace(year=1970)) lt_list.append(today + datetime.timedelta(days=1)) result["labels"].append(_('所有時間')) #print(gte_list) #print(lt_list) #print(result["labels"]) #解析json #permission = QueryJson["form"] permission = "Omdata_" + QueryJson["form"] + "_View" this_model = list( filter( lambda x: x.__name__ == re.findall("^(.+)_View", permission)[0], apps.get_models())) getModel = False isPolicy = False if len(this_model) and request.user.has_perm( str(this_model[0]._meta.app_label) + "." + permission): getModel = True else: this_model = list( filter(lambda x: x.__name__ == QueryJson["form"], apps.get_models())) if len(this_model) and request.user.has_perm( "OmMonitor_Manage"): getModel = True isPolicy = True if getModel: #setCondition filter_count = 0 for i in range(len(gte_list)): #print(gte_list[i].strftime("%Y-%m-%d %H:%M:%S")) if isPolicy: QueryJson["condition"] = [{ "column": "createtime__gte", "value": gte_list[i] }, { "column": "createtime__lt", "value": lt_list[i] }] else: QueryJson["condition"] = [{ "column": "updatetime__gte", "value": gte_list[i] }, { "column": "updatetime__lt", "value": lt_list[i] }] if not isPolicy: #取得各ticket最新id_List value_list = ["data_no"] thisQuery = this_model[0].objects.all().values( *tuple(value_list)) thisQuery = thisQuery.annotate(New=Max('id')) thisQuery = thisQuery.filter(id__in=list( thisQuery.values_list('New', flat=True))) #id_list = list(thisQuery.values_list('New', flat=True)) #print(id_list) else: thisQuery = this_model[0].objects.all() this_condition = Q() for cObj in QueryJson["condition"]: this_condition.add( Q(**{cObj["column"]: cObj["value"]}), Q.AND) #a = OmUser.objects.filter(Q(email="*****@*****.**")).values('nick_name').order_by('nick_name').annotate(count=Count('username')) #thisQuery = this_model[0].objects.filter(this_condition) thisQuery = thisQuery.filter(this_condition) value_list = [] if has_group: for key in QueryJson["groupby"]: if len(key): value_list.append(key) #產出 thisQuery = thisQuery.values(*tuple(value_list)) #QuerySet QueryList = [] #List物件 thisQueryJson = {} #aggregate產出 for cObj in QueryJson["column"]: #有分類 if has_group: if cObj["value"] == "max": thisQuery = thisQuery.annotate( **{cObj["column"]: Max(cObj["column"])}) elif cObj["value"] == "min": thisQuery = thisQuery.annotate( **{cObj["column"]: Min(cObj["column"])}) elif cObj["value"] == "count": thisQuery = thisQuery.annotate( **{cObj["column"]: Count(cObj["column"])}) elif cObj["value"] == "sum": thisQuery = thisQuery.annotate( **{cObj["column"]: Sum(cObj["column"])}) elif cObj["value"] == "avg": thisQuery = thisQuery.annotate( **{cObj["column"]: Avg(cObj["column"])}) else: if isPolicy: thisQuery = thisQuery.annotate( New=Max('createtime')) thisQuery = thisQuery.filter( createtime__in=list( thisQuery.values_list('New', flat=True))) else: thisQuery = thisQuery.annotate( New=Max('updatetime')) thisQuery = thisQuery.filter( updatetime__in=list( thisQuery.values_list('New', flat=True))) has_static = False for cObj in QueryJson["column"]: if cObj["value"] == "static": value_list.append(cObj["column"]) has_static = True if has_static: thisQuery = thisQuery.values( *tuple(value_list)) if "orderby" in QueryJson: for key in QueryJson["orderby"]: thisQuery = thisQuery.order_by(key) QueryList = list(thisQuery) #無分類 else: if cObj["value"] == "max": thisQueryJson = thisQuery.aggregate( **{cObj["column"]: Max(cObj["column"])}) elif cObj["value"] == "min": thisQueryJson = thisQuery.aggregate( **{cObj["column"]: Min(cObj["column"])}) elif cObj["value"] == "count": thisQueryJson = thisQuery.aggregate( **{cObj["column"]: Count(cObj["column"])}) elif cObj["value"] == "sum": thisQueryJson = thisQuery.aggregate( **{cObj["column"]: Sum(cObj["column"])}) elif cObj["value"] == "avg": thisQueryJson = thisQuery.aggregate( **{cObj["column"]: Avg(cObj["column"])}) QueryList = [thisQueryJson] if cObj["value"] == "static": if isPolicy: thisQueryJson = thisQuery.aggregate( New=Max('createtime')) thisQuery = thisQuery.filter( createtime__in=list( [thisQueryJson.get('New')])) else: thisQueryJson = thisQuery.aggregate( New=Max('updatetime')) thisQuery = thisQuery.filter( updatetime__in=list( [thisQueryJson.get('New')])) QueryList = list(thisQuery) if QueryJson["type"] and QueryJson["type"] != "table": for row in QueryList: if has_group: this_value_list = list( filter( lambda x: x['name'] == row.get( QueryJson["groupby"][0], ""), result["dataset"])) else: this_value_list = result["dataset"] if len(this_value_list) == 0: value_list = {} value = [] for j in range(filter_count): value.append("") for cObj in QueryJson["column"]: value.append(row.get(cObj["column"], "")) if has_group: value_list["name"] = row.get( QueryJson["groupby"][0], "") value_list["data"] = value result["dataset"].append(value_list) else: for cObj in QueryJson["column"]: this_value_list[0]['data'].append( row.get(cObj["column"], "")) filter_count = filter_count + 1 for this_value_list in result["dataset"]: if len(this_value_list['data']) < filter_count: this_value_list['data'].append("") else: #表格查詢 result["dataset"] = QueryList result["column"] = [] for k in thisQuery[0].keys(): this_field = list( filter(lambda x: x.name == k, this_model[0]._meta.fields)) if len(this_field) > 0: result["column"].append( this_field[0].verbose_name) #print(result) if error_message == "": if result: return ResponseAjax(statusEnum.success, _('查詢成功'), result).returnJSON() else: return ResponseAjax(statusEnum.error, _('查詢失敗')).returnJSON() else: return ResponseAjax(statusEnum.error, error_message).returnJSON() else: return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def getColumnListAjax(request): ''' get model column-list with permission input: request return: json author: Arthur ''' username = request.user.username postdata = getPostdata(request) if username: require_field = ['model'] checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': permission = "Omdata_" + postdata.get('model', '') + "_View" this_model = list( filter( lambda x: x.__name__ == re.findall("^(.+)_View", permission)[0], apps.get_models())) result = {} #isPolicy = False from omflow.syscom.common import License version_type = License().getVersionType() if version_type != 'C': from ommonitor.models import MonitorFlow if len(this_model) == 0 and request.user.has_perm( "OmMonitor_Manage"): policy_model = list( filter( lambda x: x.__name__ == postdata.get('model', ''), apps.get_models())) if len(policy_model): this_table_id = re.findall("OmPolicy_(.+)", postdata.get('model', ''))[0] fa = list( MonitorFlow.objects.filter( table_id=this_table_id).values('flowobject')) if len(fa): fa = json.loads(fa[0]['flowobject']) result["collector_id"] = "收集器ID" for item in fa['items']: if item['type'] == "end": for output in item['config']['output']: field_name = re.findall( '\$\((.+)\)', output['name'])[0] result[field_name] = output['des'] if len(this_model) and request.user.has_perm( str(this_model[0]._meta.app_label) + "." + permission): if re.match('Omdata_.+_View', permission): flow_uuid = re.findall("Omdata_(.+)_View", permission)[ 0] #Omdata_5d3c2cbdcf4145c3a05affaf4a74345b_View fa = FlowActiveGlobalObject.UUIDSearch( flow_uuid).merge_formobject if len(fa): fa = json.loads(fa) for field in this_model[0]._meta.fields: if 'formitm' in field.verbose_name: if field.name.upper() in fa: if fa[field.name.upper( )]["type"] == 'h_group': #result[field.name] = fa[field.name.upper] result[ field.name] = fa[field.name.upper( )]["config"]["group_title"] else: result[ field.name] = fa[field.name.upper( )]["config"]["title"] else: result[field.name] = field.verbose_name lang = get_language() app_id = FlowActiveGlobalObject.UUIDSearch( flow_uuid).flow_app_id result = Translator('single_app', 'active', lang, app_id, None).Do(result) if result != {}: info('%s get Column-List success' % username, request) return ResponseAjax(statusEnum.success, _('讀取成功。'), result).returnJSON() else: info('%s get Column-List with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON() else: info('%s get Column-List error' % username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s get Column-List with no permission' % username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def SubQueryDataAjax(request): ''' load omdata. input: request return: json author: Kolin Hsu ''' #function variable require_field = ['app_name', 'flow_name', 'data_id'] #server side rule check postdata = getPostdata(request) checker = DataChecker(postdata, require_field) #get post data app_name = postdata.get('app_name', '') flow_name = postdata.get('flow_name', '') data_id = postdata.get('data_id', '') field_list = postdata.get('fields', []) service_id = postdata.get('service_id', []) if True: if checker.get('status') == 'success': #get model fa = FlowActiveGlobalObject.NameSearch(flow_name, None, app_name) omdata_model = getModel('omformmodel', 'Omdata_' + fa.flow_uuid.hex) #整理欄位 new_field_list = [] group_user = [] group_user_id = None for f in field_list: if re.match(r'formitm_[0-9]+-.+', f): group_user_id = re.findall(r'(.+)-.+', f)[0] group_user.append(f) new_field_list.append(group_user_id) else: new_field_list.append(f) #取得資料 omdata = list( omdata_model.objects.filterformat(*new_field_list, id=data_id)) if omdata: result = omdata[0] if group_user_id: group_user_dict = json.loads(result.pop(group_user_id)) for g_u in group_user: key = re.findall(r'.+-(.+)', g_u)[0] result[g_u] = group_user_dict.get(key, '') else: result = {} info('%s load OmData success.' % request.user.username, request) return ResponseAjax(statusEnum.success, _('讀取成功。'), result).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, checker.get('message'), checker).returnJSON() else: info('%s has no permission.' % request.user.username, request) return ResponseAjax(statusEnum.no_permission, _('您沒有權限進行此操作。')).returnJSON()
def exportTranslationAjax(request): ''' export workspace application language package ''' #function variable require_field = ['language'] #get postdata postdata = getPostdata(request) language_type = postdata.get('language', '') #server side rule check checker = DataChecker(postdata, require_field) if checker.get('status') == 'success': export = '' export_list = [] if OmServiceDesign.objects.all().count() > 0: max = OmServiceDesign.objects.all().aggregate( Max('id')).get('id__max') result = list( OmServiceDesign.objects.filter(id=max).values('content')) box_object = json.loads(result[0]["content"]) #翻譯語言 #language_type = get_language() lan_package = FlowActiveGlobalObject.getSysLanDict('service').get( language_type, {}) #翻譯「全部」 #export = check2addExport('全部',export,export_list,lan_package,language_type) for idx in box_object["list"]: this_service = box_object["list"][idx] #翻譯「服務名稱」 export = check2addExport(this_service["setting"]["setTitle"], export, export_list, lan_package, language_type) if this_service["type"] == "service": #翻譯「服務說明」 export = check2addExport(this_service["setting"]["setTip"], export, export_list, lan_package, language_type) for sup_idx in this_service["service"]["list"]: this_step = this_service["service"]["list"][sup_idx] #翻譯「服務步驟名稱」 export = check2addExport(this_step["name"], export, export_list, lan_package, language_type) #翻譯「服務步驟說明」 export = check2addExport(this_step["tip"], export, export_list, lan_package, language_type) info('%s export language package success.' % request.user.username, request) return ResponseAjax(statusEnum.success, _('匯出成功。'), export).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, checker.get('message', ''), checker).returnJSON()
def loadLSideAjax(request): ''' load left side bar design json for request user input: request return: json author: Kolin Hsu ''' #function variable require_field = ['draw_$'] mission = [] sidebar = [] request.session.set_expiry(130) #server side rule check postdata = getPostdata(request) data_checker = DataChecker(postdata, require_field) if data_checker.get('status') == 'success': if settings.OMFLOW_TYPE == 'collector': result = {'sidebar': sidebar, 'mission': mission} else: #get mission group_id_list = list(request.user.groups.all().values_list( 'id', flat=True)) level_list = list( Missions.objects.filter((Q(assignee_id=request.user.id) | (Q( assign_group_id__in=group_id_list) & Q(assignee_id=None))) & Q(history=False) & Q(is_active=True) & Q(deploy_flag=True)).values_list( 'level', flat=True)) green = 0 red = 0 yellow = 0 for i in level_list: if i == 'green': green += 1 elif i == 'yellow': yellow += 1 elif i == 'red': red += 1 elif i == None or i == '': green += 1 mission.append(red) mission.append(yellow) mission.append(green) #get sidebar draw = int(postdata.get('draw_$', '')) sidebar_design = GlobalObject.__sidebarDesignObj__[ 'sidebar_design'] if draw == 1: reviseLside(request, sidebar, sidebar_design) else: #get session object lside_design = request.session.get('lside_design', '') session_updatetime = request.session.get( 'design_updatetime', '') #get global object design_updatetime = GlobalObject.__sidebarDesignObj__[ 'design_updatetime'] permission_updatetime = GlobalObject.__sidebarDesignObj__[ 'permission_updatetime'] #compare updatetime if session_updatetime < str( design_updatetime) or session_updatetime < str( permission_updatetime): #compare two json array equal or not if lside_design != sidebar_design: reviseLside(request, sidebar, sidebar_design) else: sidebar = '' else: sidebar = '' #載入語言包 language = get_language() if isinstance(sidebar, list): trans_sidebar_str = json.dumps(sidebar) trans_sidebar = json.loads(trans_sidebar_str) for s in trans_sidebar: app_id = None sidebar_id = s['id'] if 'app-' in sidebar_id: app_id = sidebar_id[4:] elif 'formflow-' in sidebar_id: app_id = s['p_id'][4:] if app_id: s['name'] = Translator('single_app', 'active', language, app_id, None).Do(s['name']) else: trans_sidebar = sidebar result = {'sidebar': trans_sidebar, 'mission': mission} info('%s load LSide success.' % request.user.username, request) return ResponseAjax(statusEnum.success, _('讀取成功。'), result).returnJSON() else: info( '%s missing some require variable or the variable type error.' % request.user.username, request) return ResponseAjax(statusEnum.not_found, data_checker.get('message'), data_checker).returnJSON()