示例#1
0
def getQuickOverview(request, filterLock, flag, code, response=dict_ext()):

	datafilter = get_datafilter(request.GET)
	
	response.path('cache')['getSecurity'] = response.pathget('cache','getSecurity') or getSecurity(request, filterLock, flag, code, includes=['incident_type'], datafilter=datafilter, response=response.within('cache'))
	dashboard_security_response = dashboard_security(request, filterLock, flag, code, includes=[''], datafilter=datafilter, response=response.within('cache','parent_label'))
	
	return {
		'templates':{
			'panels':'dash_qoview_security.html',
		},
		'data':dict_ext(dashboard_security_response).within('panels','eq_list','add_link'),
	}
示例#2
0
	def getStats(self, request):
		query_filter_group = []
		temp_group = dict(request.POST)['query_type']
		filterLock = dict(request.POST)['filterlock']

		response = {}
		response['objects'] = []

		resource = AfgIncidentOasis.objects.all()

		if filterLock[0]!='':
			resource = resource.filter(wkb_geometry__intersects=filterLock[0])

		if len(temp_group)==1:
			resource = resource.filter(incident_date__gt=request.POST['start_date'],incident_date__lt=request.POST['end_date']).order_by('-incident_date')
		elif len(temp_group)==2:
			stat_type_filter = dict(request.POST)['incident_type']
			stat_target_filter = dict(request.POST)['incident_target']
			
			resource = resource.filter(incident_date__gt=request.POST['start_date'],incident_date__lt=request.POST['end_date']).order_by('-incident_date')

			if stat_type_filter[0]=='':
				resource = resource
				# resource = AfgIncidentOasis.objects.filter(incident_date__gt=request.POST['start_date'],incident_date__lt=request.POST['end_date']).values(temp_group[0],temp_group[1]).annotate(count=Count('uid'), affected=Sum('affected'), injured=Sum('injured'), violent=Sum('violent'), dead=Sum('dead')).order_by(temp_group[0],temp_group[1])
			else:
				resource = resource.filter(main_type__in=stat_type_filter)

			if stat_target_filter[0]=='':   
				resource = resource[:100]
			else:
				resource = resource.filter(main_target__in=stat_target_filter)[:100]
			
			
		for i in resource:
			response['objects'].append({
				'date':i.incident_date,
				'desc':i.description
			})
		response['values_titles'] = [_('Date'),_('Description'),]
		response['values'] = [[i.incident_date,i.description,] for i in resource]

		response['total_count'] = resource.count()

		with connections['geodb'].cursor() as cursor:
			cursor.execute("SELECT last_incidentdate, last_sync FROM ref_security ORDER BY id DESC LIMIT 1")  
			row = cursor.fetchall()
		
			if row:
				response['last_incidentdate'] = row[0][0].strftime("%Y-%m-%d")
				response['last_incidentsync'] = row[0][1].strftime("%Y-%m-%d")

				# cursor.close()

		response = dict_ext(response).without('objects')

		return none_to_zero(response)
示例#3
0
def geojsonadd_security(response):

	source = response['source']
	boundary = source['GeoJson']
	source['lc_child_dict'] = {v['code']:v for v in source['lc_child']}

	for k,v in enumerate(boundary.get('features',[])):
		boundary['features'][k]['properties'] = prop = dict_ext(boundary['features'][k]['properties'])

		# Checking if it's in a district
		if response['areatype'] == 'district':
			response['set_jenk_divider'] = 1
			prop['na_en']=response['parent_label']
			prop.update(dict_ext(source).within('total_dead','total_incident','total_injured','total_violent'))

		else:
			response['set_jenk_divider'] = 7
			child = source['lc_child_dict'].get(prop['code'])
			if child:
				prop.update(dict_ext(child).within('na_en','total_dead','total_incident','total_injured','total_violent'))

	return boundary
示例#4
0
文件: views.py 项目: sud0su/cacip-dev
def geojsonadd(response=dict_ext()):

	boundary = response['GeoJson']
	for feature in boundary.get('features',[]):

		#  Checking if it's in a district
		if response['areatype'] == 'district':
			response['set_jenk_divider'] = 1
			feature['properties']['Population']=response['source']['pop_total']
			feature['properties']['Buildings']=response['source']['building_total']
			feature['properties']['Area']=response['source']['area_total']
			feature['properties']['na_en']=response['parent_label']
			feature['properties'].update({'hlt_'+k:v for k,v in response['source']['healthfacility'].items()})
			feature['properties']['hlt_total']=response['source']['healthfacility_total']
			feature['properties'].update({'road_'+k:v for k,v in response['source']['road'].items()})
			feature['properties']['road_total']=response['source']['road_total']
		else:
			response['set_jenk_divider'] = 7

			feature['properties']['all_population']=response['source']['pop_total']
			feature['properties']['all_buildings']=response['source']['building_total']
			feature['properties']['all_area']=response['source']['pop_total']

			for data in response.get('adm_lc'):
				if (feature['properties']['code']==data['code']):
					feature['properties']['Population']=data['Population']
					feature['properties']['Buildings']=data['total_buildings']
					feature['properties']['Area']=data['Area']

			for data in response.get('adm_hlt_road'):
				if (feature['properties']['code']==data['code']):
					feature['properties']['na_en']=data['na_en']
					feature['properties']['hlt_h1']=data['hlt_h1']
					feature['properties']['hlt_h2']=data['hlt_h2']
					feature['properties']['hlt_h3']=data['hlt_h3']
					feature['properties']['hlt_chc']=data['hlt_chc']
					feature['properties']['hlt_bhc']=data['hlt_bhc']
					feature['properties']['hlt_shc']=data['hlt_shc']
					feature['properties']['hlt_others']=data['hlt_others']
					feature['properties']['hlt_total']=data['hlt_total']
					feature['properties']['road_highway']=data['road_highway']
					feature['properties']['road_primary']=data['road_primary']
					feature['properties']['road_secondary']=data['road_secondary']
					feature['properties']['road_tertiary']=data['road_tertiary']
					feature['properties']['road_residential']=data['road_residential']
					feature['properties']['road_track']=data['road_track']
					feature['properties']['road_path']=data['road_path']
					feature['properties']['road_total']=data['road_total']

	return boundary
示例#5
0
def getSecurityStatistic(request,filterLock, flag, code, requestbody={}):

	if 'daterange' in requestbody:
		daterange = requestbody['daterange']
	else:
		enddate = datetime.date.today()
		startdate = datetime.date.today() - datetime.timedelta(days=365)
		daterange = startdate.strftime("%Y-%m-%d")+','+enddate.strftime("%Y-%m-%d")

	datafilter = {
		'daterange':daterange,
		'incident_type':filter(None,requestbody.get('incident_type',[])),
		'incident_target':filter(None,requestbody.get('incident_target',[])),	
	}

	response_dashboard = dashboard_security(request, filterLock, flag, code, datafilter=datafilter)
	panels_list = dict_ext()

	panels_list.path('charts')['bar'] = dict_ext(response_dashboard['panels']['charts']['bar']).valueslistbykey(['number_of_casualties_by_incident_type','number_of_incidents_by_incident_type','number_of_casualties_by_target_type','number_of_incidents_by_target_type',])
	panels_list.path('charts')['spider'] = dict_ext(response_dashboard['panels']['charts']['spider']).valueslistbykey(['graph_of_incident_and_casualties_trend_by_incident_type','graph_of_incident_and_casualties_trend_by_target_type',])
	panels_list['tables'] = dict_ext(response_dashboard['panels']['tables']).valueslistbykey(['incidents_and_casualties_by_incident_type','incident_and_casualties_trend_by_target_type','number_of_incident_and_casualties_overview','list_of_latest_incidents',])

	return {'panels_list':panels_list}
示例#6
0
def build_dashboard_meta():
	# print 'def build_dashboard_meta() start'

	from geonode.settings import INSTALLED_APPS, STATICFILES_DIRS

	from django.utils.translation import ugettext as _
	from geonode.utils import dict_ext

	import django
	import importlib
	import json
	import os

    # os.environ.setdefault("DJANGO_SETTINGS_MODULE", "geonode.settings")
	# if __name__ == '__main__':
	# 	django.setup()

	# build dashboard menu data and 
	# dashboard page to app name mapping
	dashboard_to_app = {}
	dashboard_apps = []
	# menus = [{'title':_('Quick Overview'),'name':'main'},{'title':_('Baseline'),'name':'baseline'}]
	menus = []
	# print 'INSTALLED_APPS', INSTALLED_APPS
	for modname in [app for app in INSTALLED_APPS if app.startswith('dashboard.')]:
		# print 'modname', modname
		module = importlib.import_module('%s.enumerations'%(modname))
		try:
			dashboard_meta = dict_ext(module.DASHBOARD_META)
			# print 'dashboard_meta', dashboard_meta
		except Exception as e:
			continue
		else:
			try:
				dashboard_apps += [modname]
				menuitem = {
					'title':_(dashboard_meta.get('menutitle','')),
					'name':dashboard_meta.get('name',''),
					'child':[]
				}
				for v in dashboard_meta.get('pages',[]):
					menuitem['child'].append({
						'title':_(v['menutitle']),
						'name':v['name']
					})
					dashboard_to_app[v['name']] = modname
				menuitem = menuitem['child'][0] if len(menuitem['child']) == 1 else menuitem
				menus.append(menuitem)
			except Exception as e:
				pass

	DASHBOARD_META = {
		'DASHBOARD_PAGE_MENU':menus,
		'DASHBOARD_TO_APP':dashboard_to_app,
		'DASHBOARD_APPS':dashboard_apps,
	}

	# with open(os.path.join(STATICFILES_DIRS[0],'dashboard_meta.json'), 'w') as f:
	# 	f.write(json.dumps(DASHBOARD_META))

	return DASHBOARD_META
示例#7
0
	def getStats(self, request):
		# print str(request.POST['query_type']) #.strip('[]')
		# print request.POST
		query_filter_group = []
		temp_group = dict(request.POST)['query_type']
		filterLock = dict(request.POST)['filterlock']
		# print filterLock

		response = {}
		response['objects'] = []

		resource = AfgIncidentOasis.objects.all()

		if filterLock[0]:
			resource = resource.filter(wkb_geometry__intersects=filterLock[0])

		group_title = subgroup_title = None
		if len(temp_group)==1:
			group_title = temp_group[0]
			resource = resource.filter(incident_date__gt=request.POST['start_date'],incident_date__lt=request.POST['end_date'])           
			resource = resource.values(group_title).annotate(count=Count('uid'), affected=Sum('affected'), injured=Sum('injured'), violent=Sum('violent'), dead=Sum('dead')).order_by(group_title)       
		elif len(temp_group)==2:
			group_title, subgroup_title = temp_group
			stat_type_filter = dict(request.POST)['incident_type']
			stat_target_filter = dict(request.POST)['incident_target']
			
			resource = resource.filter(incident_date__gt=request.POST['start_date'],incident_date__lt=request.POST['end_date'])

			if stat_type_filter[0]=='':
				resource = resource
			else:
				resource = resource.filter(main_type__in=stat_type_filter)

			if stat_target_filter[0]=='':   
				resource = resource
			else:
				resource = resource.filter(main_target__in=stat_target_filter)
			
			resourceAgregate = resource
			resource = resource.values(group_title,subgroup_title).annotate(count=Count('uid'), affected=Sum('affected'), injured=Sum('injured'), violent=Sum('violent'), dead=Sum('dead')).order_by(group_title,subgroup_title)
			resourceAgregate = resourceAgregate.aggregate(count=Count('uid'), affected=Sum('affected'), injured=Sum('injured'), violent=Sum('violent'), dead=Sum('dead'))

			response['total_incident'] = resourceAgregate['count']
			response['total_injured'] = resourceAgregate['injured']
			response['total_violent'] = resourceAgregate['violent']
			response['total_dead'] = resourceAgregate['dead']

		response['values'] = []
		response['values_titles'] = [_('Title')]+[_(CASUALTY_TYPES[i]) for i in ['count','dead','injured','violent',]]
		if subgroup_title and len(resource):
			group = {'title':resource[0][group_title],'values':[]}
		for i in resource:
			i['visible']=True
			response['objects'].append(i)
			value = [
				i[subgroup_title or group_title],
				i['count'],
				i['dead'],
				i['injured'],
				i['violent'],
			]
			if subgroup_title:
				group['values'].append(value)
				is_newgroup = bool(group['title'] != i[group_title])
				is_lastloop = bool(i is resource[len(resource)-1])
				if is_newgroup or is_lastloop:
					response['values'].append(group)
					group = {'title':i[group_title],'values':[],}
			else:
				response['values'].append(value)

		# response['objects'] = resource
		response['total_count'] = resource.count()

		with connections['geodb'].cursor() as cursor:
			cursor.execute("SELECT last_incidentdate, last_sync FROM ref_security ORDER BY id DESC LIMIT 1")
			row = cursor.fetchall()
			# cursor.close()

			if row:
				response['last_incidentdate'] = row[0][0].strftime("%Y-%m-%d")
				response['last_incidentsync'] = row[0][1].strftime("%Y-%m-%d")

				date_N_days_ago = datetime.date.today() - row[0][0]
				response['last_incidentdate_ago'] = str(date_N_days_ago).split(',')[0]

				response['color_code'] = 'black'

				if date_N_days_ago <= datetime.timedelta(days=2):
					response['color_code'] = 'green'
				elif date_N_days_ago > datetime.timedelta(days=2) and date_N_days_ago <= datetime.timedelta(days=4):
					response['color_code'] = 'yellow'
				elif date_N_days_ago > datetime.timedelta(days=4) and date_N_days_ago <= datetime.timedelta(days=5):
					response['color_code'] = 'orange'
				elif date_N_days_ago > datetime.timedelta(days=5):
					response['color_code'] = 'red'

				# date_N_days_ago = datetime.date.today() - row[0][1]
				# response['last_incidentsync_ago'] = str(date_N_days_ago).split(',')[0]

		response = dict_ext(response).without('objects')

		return none_to_zero(response)
示例#8
0
def getSecurity(request, filterLock, flag, code, includes=[], excludes=[], datafilter={}, response=dict_ext()):
	# rawFilterLock = None
	# if 'flag' in request.GET:
	#     rawFilterLock = filterLock
	#     filterLock = 'ST_GeomFromText(\''+filterLock+'\',4326)'

	# response = getCommonUse(request, flag, code)
	# response = dict_ext()

	# enddate = datetime.date.today()
	# startdate = datetime.date.today() - datetime.timedelta(days=365)
	# daterange = startdate.strftime("%Y-%m-%d")+','+enddate.strftime("%Y-%m-%d")

	# if 'daterange' in request.GET:
	#     daterange = request.GET['daterange']

	# datestart, dateend = daterange.split(',')
	# daterange = ','.join([datestart+' 00:00:00.000000', dateend+' 23:59:59.999999'])

	daterange = datafilter.get('daterange')

	if include_section('total_casualties', includes, excludes):
		response.update(getIncidentCasualties(request, daterange, filterLock, flag, code))
	# rawCasualties = getIncidentCasualties(request, daterange, filterLock, flag, code)
	# for i in rawCasualties:
	# 	response[i]=rawCasualties[i]

	# dataHLT = []
	# dataHLT.append(['', '# of',  { 'role': 'annotation' }])
	# dataHLT.append(['Death',rawCasualties['total_dead'], rawCasualties['total_dead'] ])
	# dataHLT.append(['Violent',rawCasualties['total_violent'], rawCasualties['total_violent'] ])
	# dataHLT.append(['Injured',rawCasualties['total_injured'], rawCasualties['total_injured'] ])
	# dataHLT.append(['# Incidents',rawCasualties['total_incident'], rawCasualties['total_incident'] ])
	# response['casualties_chart'] = gchart.BarChart(
	#     SimpleDataSource(data=dataHLT),
	#     html_id="pie_chart1",
	#     options={
	#         'title': 'Security Incident Overview',
	#         'width': 300,
	#         'height': 300,
	#         'legend': { 'position': 'none' },

	#         'bars': 'horizontal',
	#         'axes': {
	#             'x': {
	#               '0': { 'side': 'top', 'label': '# of Casualties and Incident'}
	#             },

	#         },
	#         'bar': { 'groupWidth': '90%' },
	#         'chartArea': {'width': '50%'},
	#         'titleX':'# of Casualties and Incident',
	# })

	if include_section('incident_type', includes, excludes):
		response['main_type_child'] = getSAMParams(request, daterange, filterLock, flag, code, 'main_type')
		response['incident_type'] = datafilter.get('incident_type') or [i['main_type'] for i in response['main_type_child']]

		main_type_raw_data = getSAMParams(request, daterange, filterLock, flag, code, 'main_type', datafilter=datafilter)
		response['incident_type_group'] =[{
			'count':i['count'],
			'injured':i['injured'],
			'violent':i['violent']+i['affected'],
			'dead':i['dead'],
			'main_type':i['main_type'],
			'child':list(getSAMIncident(request, daterange, filterLock, flag, code, 'type', datafilter={'incident_type':[i['main_type']]}))
		} for i in main_type_raw_data]

	# data_main_type = []
	# data_main_type.append(['', 'incident',{ 'role': 'annotation' }, 'dead',{ 'role': 'annotation' }, 'violent',{ 'role': 'annotation' }, 'injured',{ 'role': 'annotation' } ])
	# for type_item in main_type_raw_data:
	#     data_main_type.append([type_item['main_type'],type_item['count'],type_item['count'], type_item['dead'], type_item['dead'], type_item['violent']+type_item['affected'], type_item['violent']+type_item['affected'], type_item['injured'], type_item['injured'] ])
	# response['main_type_chart'] = gchart.BarChart(
	#     SimpleDataSource(data=data_main_type),
	#     html_id="pie_chart2",
	#     options={
	#         'title': 'Incident type overview and casualties',
	#         'width': 450,
	#         'height': 450,
	#         'isStacked':'true',
	#         'bars': 'horizontal',
	#         'axes': {
	#             'x': {
	#               '0': { 'side': 'top', 'label': '# of Casualties and Incident'}
	#             },

	#         },
	#         'annotations': {
	#             'textStyle': {
	#                 'fontSize':7
	#             }
	#         },
	#         'bar': { 'groupWidth': '90%' },
	#         'chartArea': {'width': '60%', 'height': '90%'},
	#         'titleX':'# of incident and casualties',
	# })

	# data_main_type.append(['TYPE', 'incident', 'dead', 'violent', 'injured' ])
	# for type_item in main_type_raw_data:
	# 	data_main_type.append([type_item['main_type'],type_item['count'], type_item['dead'], (type_item['violent'] or 0)+(type_item['affected'] or 0), type_item['injured'] ])

	# data_main_type = ['TYPE', 'incident', 'dead', 'violent', 'injured' ]+[[
	# 	item['main_type'],
	# 	item['count'],
	# 	item['dead'],
	# 	(item['violent'] or 0)+(item['affected'] or 0),
	# 	item['injured'],
	# ]
	# for item in main_type_raw_data]

	# response['main_type_chart'] = RadarChart(SimpleDataSource(data=data_main_type),
	#         html_id="pie_chart2",
	#         options={
	#             'title': _('Number of Incident by Incident Type'),
	#             'col-included' : [
	#                 {'col-no':1,'name':_('Incidents'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['dead_casualties_type_chart'] = RadarChart(SimpleDataSource(data=data_main_type),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of dead casualties by Incident Type'),
	#             'col-included' : [
	#                 {'col-no':2,'name':_('Dead'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['injured_casualties_type_chart'] = RadarChart(SimpleDataSource(data=data_main_type),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of injured casualties by Incident Type'),
	#             'col-included' : [
	#                 {'col-no':4,'name':_('Violent'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['violent_casualties_type_chart'] = RadarChart(SimpleDataSource(data=data_main_type),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of affected person by Incident Type'),
	#             'col-included' : [
	#                 {'col-no':3,'name':_('Injured'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	if include_section('incident_target', includes, excludes):
		response['main_target_child'] = getSAMParams(request, daterange, filterLock, flag, code, 'main_target')
		response['incident_target'] = datafilter.get('incident_target') or [i['main_target'] for i in response['main_target_child']]

		main_target_raw_data = getSAMParams(request, daterange, filterLock, flag, code, 'main_target', datafilter=datafilter)
		response['incident_target_group'] = [{
			'count':i['count'],
			'injured':i['injured'],
			'violent':i['violent']+i['affected'],
			'dead':i['dead'],
			'main_target':i['main_target'],
			'child':list(getSAMIncident(request, daterange, filterLock, flag, code, 'target', datafilter={'incident_target':[i['main_target']]}))
		} for i in main_target_raw_data]

	# data_main_target = []
	# data_main_target.append(['', 'incident',{ 'role': 'annotation' }, 'dead',{ 'role': 'annotation' }, 'violent',{ 'role': 'annotation' }, 'injured',{ 'role': 'annotation' } ])
	# for type_item in main_target_raw_data:
	#      data_main_target.append([type_item['main_target'],type_item['count'],type_item['count'], type_item['dead'], type_item['dead'], type_item['violent']+type_item['affected'], type_item['violent']+type_item['affected'], type_item['injured'], type_item['injured'] ])

	# response['main_target_chart'] = gchart.BarChart(
	#     SimpleDataSource(data=data_main_target),
	#     html_id="pie_chart3",
	#     options={
	#         'title': 'Incident target overview and casualties',
	#         'width': 450,
	#         'height': 450,
	#         # 'legend': { 'position': 'none' },
	#         'isStacked':'true',
	#         'bars': 'horizontal',
	#         'axes': {
	#             'x': {
	#               '0': { 'side': 'top', 'label': '# of Casualties and Incident'}
	#             },

	#         },
	#         'annotations': {
	#             'textStyle': {
	#                 'fontSize':7
	#             }
	#         },
	#         'bar': { 'groupWidth': '90%' },
	#         'chartArea': {'width': '60%', 'height': '90%'},
	#         'titleX':'# of incident and casualties',
	# })
	# data_main_target.append(['Target', 'incident', 'dead', 'violent', 'injured' ])
	# for type_item in main_target_raw_data:
	#      data_main_target.append([type_item['main_target'],type_item['count'], type_item['dead'], (type_item['violent'] or 0)+(type_item['affected'] or 0), type_item['injured'] ])
	# response['main_target_chart'] = RadarChart(SimpleDataSource(data=data_main_target),
	#         html_id="pie_chart3",
	#         options={
	#             'title': _('Number of Incident by Incident Target'),
	#             'col-included' : [
	#                 {'col-no':1,'name':_('Incidents'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['dead_casualties_target_chart'] = RadarChart(SimpleDataSource(data=data_main_target),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of dead casualties by Incident Target'),
	#             'col-included' : [
	#                 {'col-no':2,'name':_('Dead'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['injured_casualties_target_chart'] = RadarChart(SimpleDataSource(data=data_main_target),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of injured casualties by Incident Target'),
	#             'col-included' : [
	#                 {'col-no':4,'name':_('Injured'),'fill':True}
	#             ]
	#         }
	#     ).get_image()

	# response['violent_casualties_target_chart'] = RadarChart(SimpleDataSource(data=data_main_target),
	#         html_id="pie_chart4",
	#         options={
	#             'title': _('Number of affected person by Incident Target'),
	#             'col-included' : [
	#                 {'col-no':3,'name':_('Injured'),'fill':True}
	#             ]
	#         }
	#     ).get_image()


	# for i in response['main_type_child']:
	# 	response['incident_type'].append(i['main_type'])

	# for i in response['main_target_child']:
	# 	response['incident_target'].append(i['main_target'])

	# if 'incident_type' in request.GET:
	# 	response['incident_type'] = request.GET['incident_type'].split(',')
	# 	# print response['incident_type']

	# if 'incident_target' in request.GET:
	# 	response['incident_target'] = request.GET['incident_target'].split(',')
	# 	# print response['incident_target']

	# data = getListIncidentCasualties(request, daterange, filterLock, flag, code)
	if include_section('lc_child', includes, excludes):
		response['lc_child'] = data = getListIncidentCasualties(request, daterange, filterLock, flag, code)

	if include_section('incident_list_100', includes, excludes):
		response['incident_list_100'] = getListIncidents(request, daterange, filterLock, flag, code)

	if include_section('GeoJson', includes, excludes):
		response['GeoJson'] = getGeoJson(request, flag, code)

	return response
示例#9
0
def dashboard_security(request, filterLock, flag, code, includes=[], excludes=[], datafilter={}, response=dict_ext()):

	datafilter = datafilter or get_datafilter(request.GET)

	# incident_type = request.GET.get('incident_type','').split(',')
	# incident_target = request.GET.get('incident_target','').split(',')

	# response = dict_ext()

	if include_section('getCommonUse', includes, excludes):
		response.update(getCommonUse(request, flag, code))

	response['source'] = source = response.pathget('cache','getSecurity') or dict_ext(getSecurity(request, filterLock, flag, code, includes=includes, excludes=excludes, datafilter=datafilter))
	panels = response.path('panels')
	barcharts = response.path('panels','charts','bar')
	spidercharts = response.path('panels','charts','spider')
	tables = response.path('panels','tables')

	# titles = {
	# 	'casualties':{
	# 		'number_of_casualties_by_incident_type':'Number of Casualties by Incident Type',
	# 		'number_of_casualties_by_target_type':'Number of Casualties by Target Type', 
	# 	},
	# 	'incidents':{
	# 		'number_of_incidents_by_incident_type':'Number of Incidents by Incident Type',
	# 		'number_of_incidents_by_target_type':'Number of Incidents by Target Type',
	# }
	# labels = {
	# 	'type':source['incident_type'],
	# 	'target':source['incident_target'],
	# }
	# numbersource = {
	# 	'type':source['incident_type_group'],
	# 	'target':source['incident_target_group'],
	# }
	# for k,t in titles.items():
	# 	barcharts.path(k)['key'] = k
	# 	barcharts.path(k)['title'] = t
	# 	barcharts.path(k)['labels'] = source['incident_type']
	# 	barcharts.path(k)['child'] = [{
	# 		'name':CASUALTY_TYPES[t],
	# 		'data':[i[t] for i in source['incident_type_group']]
	# 	} for t in CASUALTY_TYPES_ORDER]

	if source.containall('incident_type','incident_type_group'):

		k = 'number_of_casualties_by_incident_type'
		barcharts[k] = {
			'key':k,
			'title':'Number of Casualties by Incident Type',
			'labels':source['incident_type'],
			'child':[{
				'name':CASUALTY_TYPES[t],
				'data':[i[t] for i in source['incident_type_group']]
			} for t in ['dead','injured']],
		}

		k = 'number_of_incidents_by_incident_type'
		barcharts[k] = {
			'key':k,
			'title':'Number of Incidents by Incident Type',
			'labels':source['incident_type'],
			'child':[{
				'name':CASUALTY_TYPES[t],
				'data':[i[t] for i in source['incident_type_group']]
			} for t in ['count','violent']],
		}

		chart = spidercharts.path('graph_of_incident_and_casualties_trend_by_incident_type')
		chart['key'] = 'graph_of_incident_and_casualties_trend_by_incident_type'
		chart['title'] = 'Graph of Incident and Casualties Trend by Incident Type'
		chart['labels'] = source['incident_type']
		chart['labels_all'] = [{
			'name':t['main_type'],
			'count':t['count'],
			'selected':t['main_type'] in source['incident_type'],
		} for t in source['main_type_child']]
		chart['child'] = [{
			'type':CASUALTY_TYPES[t],
			'data':[i[t] for i in source['incident_type_group']]
		} for t in CASUALTY_TYPES_ORDER]

	if source.containall('incident_target','incident_target_group'):

		k = 'number_of_casualties_by_target_type'
		barcharts[k] = {
			'key':k,
			'title':'Number of Casualties by Target Type',
			'labels':source['incident_target'],
			'child':[{
				'name':CASUALTY_TYPES[t],
				'data':[i[t] for i in source['incident_target_group']]
			} for t in ['dead','injured']],
		}

		k = 'number_of_incidents_by_target_type'
		barcharts[k] = {
			'key':k,
			'title':'Number of Incidents by Target Type',
			'labels':source['incident_target'],
			'child':[{
				'name':CASUALTY_TYPES[t],
				'data':[i[t] for i in source['incident_target_group']]
			} for t in ['count','violent']],
		}

		chart = spidercharts.path('graph_of_incident_and_casualties_trend_by_target_type')
		chart['key'] = 'graph_of_incident_and_casualties_trend_by_target_type'
		chart['title'] = 'Graph of Incident and Casualties Trend by Target Type'
		chart['labels'] = source['incident_target']
		chart['labels_all'] = [{
			'name':t['main_target'],
			'count':t['count'],
			'selected':t['main_target'] in source['incident_target'],
		} for t in source['main_target_child']]
		chart['child'] = [{
			'type':CASUALTY_TYPES[t],
			'data':[i[t] for i in source['incident_target_group']]
		} for t in CASUALTY_TYPES_ORDER]

	# titles = {
	# 	'number_of_casualties_by_target_type':'Number of Casualties by Target Type', 
	# 	'number_of_incidents_by_target_type':'Number of Incidents by Target Type'
	# }
	# for k,t in titles.items():
	# 	barcharts.path(k)['key'] = k
	# 	barcharts.path(k)['title'] = t
	# 	barcharts.path(k)['labels'] = source['incident_target']
	# 	barcharts.path(k)['child'] = [{
	# 		'name':CASUALTY_TYPES[t],
	# 		'data':[i[t] for i in source['incident_target_group']]
	# 	} for t in CASUALTY_TYPES_ORDER]

	# titles = {
	# 	'graph_of_incident_and_casualties_trend_by_incident_type':'Graph of Incident and Casualties Trend by Incident Type', 
	# 	'graph_of_incident_and_casualties_trend_by_target_type':'Graph of Incident and Casualties Trend by Target Type'
	# }
	# for k,t in titles.items():
	# 	spidercharts.path(k)['key'] = k
	# 	spidercharts.path(k)['title'] = t
	# 	spidercharts.path(k)['labels'] = source['incident_type']
	# 	spidercharts.path(k)['child'] = [{
	# 		'type':CASUALTY_TYPES[t],
	# 		'data':[i[t] for i in source['incident_type_group']]
	# 	} for t in CASUALTY_TYPES_ORDER]

	if source.containall('incident_target_group'):
		table = tables['incidents_and_casualties_by_incident_type'] = dict_ext()
		table['key'] = 'incidents_and_casualties_by_incident_type'
		table['title'] = _('Incidents and Casualties by Incident Type')
		table['child'] = []
		for i in source['incident_type_group']:
			table['child'] += [{
				'isgroup':True,
				'value':[i['main_type'],i['count'],i['violent'],i['injured'],i['dead']],
			}] + [{
				'value':[j['type'],j['count'],j['violent'],j['injured'],j['dead']],
			} for j in i['child']]

	if source.containall('incident_target_group'):
		table = tables['incident_and_casualties_trend_by_target_type'] = dict_ext()
		table['key'] = 'incident_and_casualties_trend_by_target_type'
		table['title'] = _('Incidents and Casualties by Target Type')
		table['child'] = []
		for i in source['incident_target_group']:
			table['child'] += [{
				'isgroup':True,
				'value':[i['main_target'],i['count'],i['violent'],i['injured'],i['dead']],
			}] + [{
				'value':[j['target'],j['count'],j['violent'],j['injured'],j['dead']],
			} for j in i['child']]

	if source.containall('parent_label') and source.containall('lc_child','total_incident','total_violent','total_injured','total_dead'):
		tables['number_of_incident_and_casualties_overview'] = {
			'title':_('Number of Incident and Casualties Overview'),
			'key':'number_of_incident_and_casualties_overview',
			'parentdata':[response['parent_label'],source['total_incident'],source['total_violent'],source['total_injured'],source['total_dead']],
			'child':[{
				'code':i['code'],
				'value':[i['na_en'],i['total_incident'],i['total_violent'],i['total_injured'],i['total_dead']],
			}
			for i in source['lc_child']],
		}

	if source.containall('incident_target','incident_list_100'):
		tables['list_of_latest_incidents'] = {
			'title':_('List of Latest Incidents'),
			'key':'list_of_latest_incidents',
			'child':[[i['incident_date'],i['description'],] for i in source['incident_list_100']],
		}

	if include_section('GeoJson', includes, excludes):
		response['GeoJson'] = geojsonadd_security(response)

	return response