-
Notifications
You must be signed in to change notification settings - Fork 5
/
devtracker.rb
1573 lines (1456 loc) · 64.8 KB
/
devtracker.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#dotenv is used to load the sensitive environment variables for devtracker.
require 'dotenv'
Dotenv.load('/etc/platform.conf')
require 'sinatra'
require 'json'
require 'rest-client'
require 'active_support/all'
require 'kramdown'
require 'pony'
require 'money'
require 'benchmark'
require 'eventmachine'
require 'em-synchrony'
require "em-synchrony/em-http"
require 'oj'
require 'rss'
require "sinatra/json"
require "action_view"
require 'csv'
require "sinatra/cookies"
require "cgi"
#helpers path
require_relative 'helpers/formatters.rb'
require_relative 'helpers/oipa_helpers.rb'
require_relative 'helpers/codelists.rb'
require_relative 'helpers/lookups.rb'
require_relative 'helpers/common_helpers.rb'
require_relative 'helpers/project_helpers.rb'
require_relative 'helpers/sector_helpers.rb'
require_relative 'helpers/country_helpers.rb'
require_relative 'helpers/document_helpers.rb'
require_relative 'helpers/common_helpers.rb'
require_relative 'helpers/results_helper.rb'
require_relative 'helpers/JSON_helpers.rb'
require_relative 'helpers/filters_helper.rb'
require_relative 'helpers/search_helper.rb'
require_relative 'helpers/input_sanitizer.rb'
require_relative 'helpers/region_helpers.rb'
require_relative 'helpers/recaptcha_helper.rb'
require_relative 'helpers/solr_helper.rb'
#Helper Modules
include CountryHelpers
include Formatters
include SectorHelpers
include ProjectHelpers
include CommonHelpers
include ResultsHelper
include FiltersHelper
include SearchHelper
include InputSanitizer
include RegionHelpers
include RecaptchaHelper
include SolrHelper
# Developer Machine: set global settings
#set :oipa_api_url, 'https://fcdo-direct-indexing.iati.cloud/search/'#'https://fcdo.iati.cloud/search/'#'https://fcdo-direct-indexing.iati.cloud/search/'#'https://devtracker.fcdo.gov.uk/api/'
# set :oipa_api_url, 'https://devtracker-entry.oipa.nl/api/'
# set :oipa_api_url, 'https://fcdo.iati.cloud/search/'
# set :oipa_api_url, 'https://fcdo-direct-indexing.iati.cloud/search/'
#set :bind, '0.0.0.0' # Allows for vagrant pass-through whilst debugging
# Server Machine: set global settings to use varnish cache
set :oipa_api_url, 'http://127.0.0.1:6081/search/'
set :prod_api_url, 'https://fcdo.iati.cloud'
set :dev_api_url, 'https://fcdo-staging.iati.cloud'
#ensures that we can use the extension html.erb rather than just .erb
Tilt.register Tilt::ERBTemplate, 'html.erb'
Money.locale_backend = :i18n
Money.default_currency = "GBP"
#####################################################################
# Common Variable Assingment
#####################################################################
set :current_first_day_of_financial_year, first_day_of_financial_year(DateTime.now)
set :current_last_day_of_financial_year, last_day_of_financial_year(DateTime.now)
set :goverment_department_ids, 'GB-GOV-25,GB-GOV-26,GB-GOV-15,GB-GOV-9,GB-GOV-6,GB-GOV-2,GB-GOV-1,GB-1,GB-GOV-3,GB-GOV-13,GB-GOV-7,GB-6,GB-10,GB-GOV-10,GB-9,GB-GOV-8,GB-GOV-5,GB-GOV-12,GB-COH-RC000346,GB-COH-03877777,GB-GOV-24'
#set :goverment_department_ids, 'GB-GOV-1,GB-1'
set :google_recaptcha_publicKey, ENV["GOOGLE_PUBLIC_KEY"]
set :google_recaptcha_privateKey, ENV["GOOGLE_PRIVATE_KEY"]
set :raise_errors, false
set :show_exceptions, false
set :log_api_calls, false
set :devtracker_page_title, ''
#####################################################################
# HOME PAGE
#####################################################################
get '/' do #homepage
#read static data from JSON files for the front page
top5results = JSON.parse(File.read('data/top5results.json'))
top5countries = ''
Benchmark.bm(7) do |x|
x.report("Loading Time: ") {
if (!canLoadFromCache('top5Countries'))
storeCacheData(get_top_5_countriesv2(), 'top5Countries')
top5countries = getCacheData('top5Countries')
else
top5countries = getCacheData('top5Countries')
end
#oipa v3.1
}
end
## cache storing ends here
odas = Oj.load(File.read('data/odas.json'))
odas = odas.first(10)
settings.devtracker_page_title = ''
# Example of setting up a cookie from server end
# response.set_cookie('my_cookie', 'value_of_cookie')
what_we_do = ''
if (!canLoadFromCache('what_we_do'))
## logic
## get budget data, then check if they fall within date range
## do a summation of the budget amount within date range
## pick dac5 sector code and then get the underlying high level sector code
## if the sector is present, add the new budget info to this sector
## Else create a new ref to the high level sector code and add
## budget value starting from 0
## pick budget percentage for each dac5 sector code2
## calculate the budget amount against that perentage and add it to
## the high level related sector code
newApiCall = settings.oipa_api_url + "activity?q=participating_org_ref:GB-GOV-* AND reporting_org_ref:(#{settings.goverment_department_ids.gsub(","," OR ")}) AND budget_period_start_iso_date:[#{settings.current_first_day_of_financial_year}T00:00:00Z TO *] AND budget_period_end_iso_date:[* TO #{settings.current_last_day_of_financial_year}T00:00:00Z]&fl=iati_identifier,budget_value,recipient_country_code,recipient_region_code,budget_period_start_iso_date,budget_period_end_iso_date,sector_code,sector_percentage,&rows=50000"
pulledData = RestClient.get newApiCall
storeCacheData(high_level_sector_listv2(pulledData, 'top_five_sectors'), 'what_we_do')
what_we_do = getCacheData('what_we_do')
else
what_we_do = getCacheData('what_we_do')
end
whatWeDoTotal = what_we_do.first['budget']
top5countries = top5countries.select{|i| i.has_key?('budget')}
top5countries = top5countries.sort_by{|val| -val['budget'].to_f}
top5CountryTotal = top5countries.first['budget']
activiteProjectCount = JSON.parse(RestClient.get settings.oipa_api_url + "activity/?q=reporting_org_ref:(#{settings.goverment_department_ids.gsub(","," OR ")}) AND hierarchy:1 AND activity_status_code:2&rows=1&fl=iati_identifier")['response']['numFound'].to_i
erb :'index',
:layout => :'layouts/landing',
:locals => {
top_5_countries: top5countries.first(10),
what_we_do: what_we_do,
what_we_achieve: top5results,
odas: odas,
oipa_api_url: settings.oipa_api_url,
whatWeDoTotal: whatWeDoTotal,
top5CountryTotal: top5CountryTotal,
activiteProjectCount: activiteProjectCount
}
end
get '/total_spend/?' do
if (!canLoadFromCache('totalGlobalSpend'))
storeCacheData(get_total_spend(), 'totalGlobalSpend')
totalSpend = getCacheData('totalGlobalSpend')
else
totalSpend = getCacheData('totalGlobalSpend')
end
totalSpend = format_billion_stg(totalSpend.to_f)
json :output => totalSpend
end
############## RUBY APP LEVEL CACHING OF DATA######################
def canLoadFromCache(fileName)
if File.exists?('data/cache/'+fileName+'.json')
data = JSON.parse(File.read('data/cache/'+fileName+'.json'))
updatedDate = data['updatedDate'].to_date
updatedDate = updatedDate.next_day(7)
if (DateTime.now.to_date <= updatedDate)
puts 'date time check passed and sending true'
return true
else
puts 'date time check failed and sending false'
return false
end
else
puts 'file does not exist, sending false'
return false
end
end
def storeCacheData(data, fileName)
tempData = {}
tempData['updatedDate'] = DateTime.now.to_date
tempData['data'] = data
File.open('data/cache/'+fileName+'.json', "w") { |f| f.puts tempData.to_json }
end
def getCacheData(fileName)
data = JSON.parse(File.read('data/cache/'+fileName+'.json'))
data['data']
end
####################################################################
#####################################################################
# COUNTRY PAGES
#####################################################################
# Country summary page
get '/countries/:country_code/?' do |n|
n = sanitize_input(n,"p").upcase
country = ''
results = ''
if (!canLoadFromCache('country_'+n))
storeCacheData(get_country_detailsv2(n), 'country_'+n)
country = getCacheData('country_'+n)
else
country = getCacheData('country_'+n)
end
countryYearWiseBudgets = ''
countrySectorGraphData = ''
newtempActivityCount = 'activity?q=activity_status_code:2 AND hierarchy:1 AND participating_org_ref:GB-GOV-* AND reporting_org_ref:('+settings.goverment_department_ids.gsub(","," OR ")+') AND recipient_country_code:('+n+')&fl=sector_code,sector_percentage,sector_narrative,sector,recipient_country_code,recipient_country_name,recipient_country_percentage,recipient_country,recipient_region_code,recipient_region_name,recipient_region_percentage,recipient_region&rows=1'
tempActivityCount = Oj.load(RestClient.get api_simple_log(settings.oipa_api_url + newtempActivityCount))['response']['numFound']
if n == 'UA2'
tempActivityCount = 0
end
results = get_country_results(n)
#----- Following project count code needs to be deprecated before merging with main solr branch work ----------------------
country['totalProjects'] = Oj.load(RestClient.get api_simple_log(settings.oipa_api_url + 'activity?q=participating_org_ref:GB-GOV-* AND reporting_org_ref:('+settings.goverment_department_ids.gsub(","," OR ")+') AND recipient_country_code:('+n+') AND hierarchy:1 AND activity_status_code:2&fl=iati_identifier&rows=1'))['response']['numFound']
ogds = Oj.load(File.read('data/OGDs.json'))
topSixResults = pick_top_six_results(n)
#Geo Location data of country
geoJsonData = getCountryBounds(n)
# Get a list of map markers
mapMarkers = getCountryMapMarkers(n)
settings.devtracker_page_title = 'Country ' + country['name'] + ' Summary Page'
json_link = ''
if request.url.start_with?('https://devtracker.')
json_link = json_link + settings.prod_api_url
else
json_link = json_link + settings.dev_api_url
end
json_link = json_link + '/search/activity/?q=recipient_country_code:'+n+' AND reporting_org_ref:GB-GOV-* AND hierarchy:1&format='
erb :'countries/country',
:layout => :'layouts/layout',
:locals => {
country: country,
results: results,
topSixResults: topSixResults,
oipa_api_url: settings.oipa_api_url,
activityCount: tempActivityCount,
countryGeoJsonData: geoJsonData,
mapMarkers: mapMarkers,
active_link: 'aidByLoc',
active_sub_link: 'countrySummary',
json_url_link: json_link
}
end
## country summary page related api calls
get '/country-implementing-org-list/:country_code/:activity_count/?' do
n = sanitize_input(params[:country_code],"p").upcase
count = sanitize_input(params[:activity_count],"p")
json :output => getCountryLevelImplOrgs(n,count)
end
get '/country-sector-graph-data/:country_code/?' do |n|
n = sanitize_input(n,"p").upcase
country = ''
json :output => get_country_sector_graph_data_jsCompatibleV2(n)
end
get '/region-sector-graph-data/:country_code/?' do |n|
n = sanitize_input(n,"p").upcase
country = ''
json :output => get_region_sector_graph_data_jsCompatibleV2(n)
end
get '/country-budget-bar-graph-data/:country_code/?' do |n|
n = sanitize_input(n,"p").upcase
json :output => budgetBarGraphDataDv3(n)
end
##
# solr route
get '/countries/:country_code/projects/?' do |n|
n = sanitize_input(n, "p")
query = '('+n+')'
filters = prepareFilters(query.to_s, 'C')
response = solrResponse(query, 'AND activity_status_code:(2)', 'C', 0, '', '')
if(response['numFound'].to_i > 0)
response = addTotalBudgetWithCurrency(response)
end
settings.devtracker_page_title = 'Search Results For : ' + query
projectData = ''
country = get_country_code_name(n)
settings.devtracker_page_title = 'Country ' + country['name'] + ' Programmes Page'
erb :'countries/projects',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
country: country,
total_projects: response['numFound'],
query: query,
filters: filters,
response: response,
solrConfig: Oj.load(File.read('data/solr-config.json')),
activityStatus: Oj.load(File.read('data/activity_status.json')),
searchType: 'C',
breadcrumbURL: '/location/country',
breadcrumbText: 'Aid by Location'
}
end
#####################################################################
# GLOBAL PAGES
#####################################################################
#Global Project List Page
get '/global/:global_code/projects/?' do |n|
n = sanitize_input(n,"p")
countryAllProjectFilters = get_static_filter_list()
region = {}
if n == 'ZZ'
region[:code] = "ZZ"
region[:name] = "Multilateral Organisation"
elsif n == 'NS'
region[:code] = "NS"
region[:name] = "Non Specific Country"
else
region[:code] = ""
region[:name] = "ALL"
end
#getRegionProjects = get_region_projects(region[:code])
getRegionProjects = generate_project_page_data(generate_api_list('R',region[:code],"2"))
settings.devtracker_page_title = 'Global '+region[:name]+' Programme Page'
erb :'regions/projects',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
region: region,
total_projects: getRegionProjects['projects']['count'],
projects: getRegionProjects['projects']['results'],
countryAllProjectFilters: countryAllProjectFilters,
highLevelSectorList: getRegionProjects['highLevelSectorList'],
budgetHigherBound: getRegionProjects['project_budget_higher_bound'],
actualStartDate: getRegionProjects['actualStartDate'],
plannedEndDate: getRegionProjects['plannedEndDate'],
documentTypes: getRegionProjects['document_types'],
implementingOrgTypes: getRegionProjects['implementingOrg_types'],
reportingOrgTypes: getRegionProjects['reportingOrg_types']
}
end
#####################################################################
# REGION PAGES
#####################################################################
# Region summary page
get '/regions/:region_code/?' do |n|
n = sanitize_input(n,"p")
region = get_region_detailsv2(n)
settings.devtracker_page_title = 'Region '+region[:name]+' Summary Page'
erb :'regions/region',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
region: region,
regionYearWiseBudgets: get_country_region_yearwise_budget_graph_datav2(RestClient.get api_simple_log(settings.oipa_api_url + 'activity/?q=recipient_region_code:'+n+' AND reporting_org_ref:('+settings.goverment_department_ids.gsub(","," OR ")+') &fl=budget_value,default-currency,budget_period_start_iso_date,budget_period_end_iso_date,budget.period-start.quarter,budget.period-end.quarter')),
mapMarkers: getRegionMapMarkersv2(region[:code]),
}
end
#Region Project List Page
get '/regions/:region_code/projects/?' do |n|
n = sanitize_input(n, "p")
query = '('+n+')'
filters = prepareFilters(query.to_s, 'R')
response = solrResponse(query, 'AND activity_status_code:(2)', 'R', 0, '', '')
if(response['numFound'].to_i > 0)
response = addTotalBudgetWithCurrency(response)
end
countryAllProjectFilters = get_static_filter_list()
region = get_region_code_name(n)
settings.devtracker_page_title = 'Region '+region[:name]+' Programmes Page'
if n.to_i == 998
breadcrumbURL = '/location/global'
else
breadcrumbURL = '/location/regional'
end
erb :'regions/projects',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
region: region,
total_projects: response['numFound'],
query: query,
filters: filters,
response: response,
solrConfig: Oj.load(File.read('data/solr-config.json')),
activityStatus: Oj.load(File.read('data/activity_status.json')),
searchType: 'R',
breadcrumbURL: breadcrumbURL,
breadcrumbText: 'Aid by Location'
}
end
#####################################################################
# PROJECTS PAGES
#####################################################################
get '/projects/*' do
wildCardData = params['splat'][0]
if request.url.end_with? ('/summary')
getProgID = wildCardData.gsub('/summary', '')
redirect '/programme/'+getProgID+'/summary'
elsif request.url.end_with? ('/documents')
getProgID = wildCardData.gsub('/documents', '')
redirect '/programme/'+getProgID+'/documents'
elsif request.url.end_with? ('/transactions')
getProgID = wildCardData.gsub('/transactions', '')
redirect '/programme/'+getProgID+'/transactions'
elsif request.url.end_with? ('/components')
getProgID = wildCardData.gsub('/components', '')
redirect '/programme/'+getProgID+'/projects'
elsif request.url.end_with? ('/partners')
getProgID = wildCardData.gsub('/partners', '')
redirect '/programme/'+getProgID+'/partners'
else
getProgID = wildCardData.gsub('/components', '')
redirect '/programme/'+getProgID+'/summary'
end
#redirect '/search_p'
end
# Project summary page
get '/programme/*/summary' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
#n = sanitize_input(n,"p")
check_if_project_exists(n)
# get the project data from the API
project = get_h1_project_detailsv2(n)
participatingOrgList = get_participating_organisationsv2(project)
#get the country/region data from the API
countryOrRegion = get_country_or_regionv2(n)
spendToDate = spendToDatev2(n)
programmeBudget = 0
if(project.has_key?('activity_plus_child_aggregation_budget_value_gbp'))
programmeBudget = programmeBudget + project['activity_plus_child_aggregation_budget_value_gbp'].to_f
elsif(project.has_key?('related_budget_value'))
project['related_budget_value'].each do |b|
programmeBudget = programmeBudget + b.to_f
end
elsif(project.has_key?('activity_aggregation_budget_value_gbp'))
programmeBudget = programmeBudget + project['activity_aggregation_budget_value_gbp'].to_f
else
if project.has_key?('budget_value')
project['budget_value'].each do |budget|
programmeBudget = programmeBudget + budget
end
end
end
if(!project['reporting_org_ref'].to_s == 'GB-GOV-1')
if(project.has_key?('activity_aggregation_incoming_funds_value_gbp'))
programmeBudget = programmeBudget + project['activity_aggregation_incoming_funds_value_gbp'].to_f
end
if(project.has_key?('activity_aggregation_commitment_value_gbp'))
programmeBudget = programmeBudget + project['activity_aggregation_commitment_value_gbp'].to_f
end
end
#get project sectorwise graph data
projectSectorGraphData = get_project_sector_graph_datav2(n)
settings.devtracker_page_title = 'Programme '+project['iati_identifier']
erb :'projects/summary',
:layout => :'layouts/layout',
:locals => {
projectId: n,
oipa_api_url: settings.oipa_api_url,
project: project,
countryOrRegion: countryOrRegion,
projectSectorGraphData: projectSectorGraphData,
participatingOrgList: participatingOrgList,
policyMarkers: get_policy_markersv2(project),
mapMarkers: getProjectMapMarkersv2(project),
spendToDate: spendToDate,
programmeBudget: programmeBudget
}
end
# Project documents page
get '/programme/*/documents/?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
check_if_project_exists(n)
# get the project data from the API
project = get_h1_project_documents(n)
doc_categories = Oj.load(File.read('data/doc_category_list.json'))
settings.devtracker_page_title = 'Programme '+project['iati_identifier']+' Documents'
erb :'projects/documents',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
project: project,
cateogies: doc_categories,
}
end
#Project transactions page
get '/programme/*/transactions/?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
check_if_project_exists(n)
# get the project data from the API
project = get_h1_project_detailsv2(n)
settings.devtracker_page_title = 'Programme '+project['iati_identifier']+' Transactions'
erb :'projects/transactions',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
project: project,
}
end
#Project transactions page
get '/programme/*/projects/?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
check_if_project_exists(n)
# get the project data from the API
project = get_h1_project_detailsv2(n)
settings.devtracker_page_title = 'Programme '+project['iati_identifier']+' Transactions'
erb :'projects/components',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
project: project
}
end
######################################################################
################## PROJECT PAGE RELATED API CALLS ###################
######################################################################
post 'get-participating-orgs' do
project = sanitize_input(params['data']['project'].to_s,"newId")
json :output => get_participating_organisations(project)
end
post '/transaction-details' do
project = sanitize_input(params['data']['projectID'].to_s,"newId")
transactionType = sanitize_input(params['data']['transactionType'].to_s, "a")
json :output => get_transaction_details(project,transactionType)
end
get '/transaction-count/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
json :output => get_transaction_countv2(n)
end
post '/transaction-details-pagev2' do
project = sanitize_input(params['data']['projectID'].to_s,"newId")
transactionType = sanitize_input(params['data']['transactionType'].to_s, "a")
resultCount = 20
nextPage = sanitize_input(params['data']['nextPage'].to_s, "a")
json :output => get_transaction_details_pagev2(project,transactionType, nextPage, resultCount)
end
post '/transaction-total' do
project = sanitize_input(params['data']['project'].to_s,"newId")
transactionType = sanitize_input(params['data']['transactionType'].to_s, "a")
currency = sanitize_input(params['data']['currency'].to_s, "newId")
#json :output => get_transaction_total(project,transactionType, currency)
json :output => get_transaction_totalv2(project,transactionType)
end
get '/component-list/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
oipa = RestClient.get api_simple_log(settings.oipa_api_url + "activity/?q=iati_identifier:#{n}&fl=related_activity_ref&rows=1")
project = JSON.parse(oipa)['response']['docs'].first
json :output => project['related_activity_ref']
end
# Get yearly budget for H1 Activity from the API
get '/project-yearwise-budget/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
projectYearWiseBudgets= get_project_yearwise_budgetv2(n)
json :output=> projectYearWiseBudgets
end
# Convert number to proper currency data
post '/number-to-currency' do
number = sanitize_input(params['data']['number'].to_s,"a")
currency = sanitize_input(params['data']['currency'].to_s, "newId")
begin
data = Money.new(number.to_f.round(0)*100, currency).format(:no_cents_if_whole => true,:sign_before_symbol => false)
rescue
data = "£#{number}"
end
json :output=> data
end
# Get total project budget
get '/total-project-budget/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
project = get_h1_project_detailsv2(n)
projectYearWiseBudgets= get_project_yearwise_budget(n)
totalProjectBudget=get_sum_budget(projectYearWiseBudgets).to_f
begin
data = Money.new(totalProjectBudget.round(0)*100, if project['activity_plus_child_aggregation']['activity_children']['budget_currency'].nil? then project['default_currency']['code'] else project['activity_plus_child_aggregation']['activity_children']['budget_currency'] end).format(:no_cents_if_whole => true,:sign_before_symbol => false)
rescue
data = "£#{totalProjectBudget}"
end
json :output=> data
end
get '/total-project-budgetv2/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
programmeBudgets = RestClient.get api_simple_log(settings.oipa_api_url + "activity/?q=iati_identifier:#{n}*&fl=budget_value,default-currency&rows=200")
programmeBudgets = JSON.parse(programmeBudgets)['response']['docs']
totalBudget = 0
programmeBudgets.each do |project|
if project.has_key?('budget_value')
project['budget_value'].each do |budget|
totalBudget = totalBudget + budget
end
end
end
begin
data = Money.new(totalBudget.round(0)*100, if programmeBudgets.first.has_key?('default-currency') then programmeBudgets.first['default-currency'] else 'GBP' end).format(:no_cents_if_whole => true,:sign_before_symbol => false)
rescue
data = "£#{totalBudget}"
end
json :output=> data
end
get '/project-details/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
#oipa = RestClient.get api_simple_log(settings.oipa_api_url + "activities/#{n}/?format=json&fields=iati_identifier,title,description,activity_date")
oipa = RestClient.get api_simple_log(settings.oipa_api_url + "activity/?q=iati_identifier:#{n}&fl=iati_identifier,title_narrative,description_narrative,activity_date_type,activity_date_iso_date&rows=1")
oipa = JSON.parse(oipa)['response']['docs'].first
tempData = {}
tempData['iati_identifier'] = oipa['iati_identifier']
tempData['title'] = oipa['title_narrative'].first
tempData['description'] = oipa['description_narrative'].first
tempData['activity_date'] = {}
tempData['activity_dates'] = bestActivityDatev2(oipa)
json :output=> tempData
end
get '/country-or-region/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
json :output=> get_country_or_regionv2(n)
end
# Get the funding projects Count from the API
get '/get-funding-projects/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
json :output=> get_funding_project_countv2(n)
end
# Get funded project counts
get '/get-funded-projects/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
json :output=> get_funded_project_countv2(n)
end
# projects that are funded by this target project
get '/get-funded-projects-page/:page/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
page = ERB::Util.url_encode params[:page].to_s
json :output=> get_funded_project_details_pagev2(n, page, 20)
end
# projects that are funding this target project
get '/get-funding-projects-details/*?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
json :output=> get_funding_project_detailsv2(n)
end
######################################################################
######################################################################
#Project partners page
get '/programme/*/partners/?' do
n = ERB::Util.url_encode (params['splat'][0]).to_s
check_if_project_exists(n)
# get the project data from the API
project = get_h1_project_detailsv2(n)
settings.devtracker_page_title = 'Programme '+project['iati_identifier']+' Partners'
erb :'projects/partners',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
project: project
}
end
#####################################################################
# SECTOR PAGES
#####################################################################
# examples:
# http://devtracker.fcdo.gov.uk/sector/
# High Level Sector summary page
get '/sector/?' do
# Get the high level sector data from the API
high_level_sector_list = ''
if (!canLoadFromCache('high_level_sector_list'))
newApiCall = settings.oipa_api_url + "activity?q=participating_org_ref:GB-GOV-* AND reporting_org_ref:(#{settings.goverment_department_ids.gsub(","," OR ")}) AND budget_period_start_iso_date:[#{settings.current_first_day_of_financial_year}T00:00:00Z TO *] AND budget_period_end_iso_date:[* TO #{settings.current_last_day_of_financial_year}T00:00:00Z]&fl=iati_identifier,budget_value,recipient_country_code,recipient_region_code,budget_period_start_iso_date,budget_period_end_iso_date,sector_code,sector_percentage,&rows=50000"
pulledData = RestClient.get newApiCall
storeCacheData(high_level_sector_listv2(pulledData, 'all_sectors'), 'high_level_sector_list')
high_level_sector_list = getCacheData('high_level_sector_list')
else
high_level_sector_list = getCacheData('high_level_sector_list')
end
settings.devtracker_page_title = 'Sector Page'
erb :'sector/index',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
high_level_sector_list: high_level_sector_list,#high_level_sector_list( get_5_dac_sector_data(), "all_sectors", "High Level Code (L1)", "High Level Sector Description")
active_link: 'sector'
}
end
# Category Page (e.g. Three Digit DAC Sector)
get '/sector/:high_level_sector_code/?' do
# Get the three digit DAC sector data from the API
dac2Code = sanitize_input(params[:high_level_sector_code],"p")
high_level_sector_list = ''
fileName = 'sector_dac2_'+dac2Code
if (!canLoadFromCache(fileName))
prepSectorCodeFilter = ''
sectorHierarchy = JSON.parse(File.read('data/sectorHierarchies.json')).select{|s| s['High Level Code (L1)'].to_i == dac2Code.to_i}
sectorHierarchy.each_with_index do |elem, index|
if index == sectorHierarchy.length-1
prepSectorCodeFilter = prepSectorCodeFilter + elem['Code (L3)'].to_s
else
prepSectorCodeFilter = prepSectorCodeFilter + elem['Code (L3)'].to_s + ' OR '
end
end
newApiCall = settings.oipa_api_url + "activity?q=participating_org_ref:GB-GOV-* AND reporting_org_ref:(#{settings.goverment_department_ids.gsub(","," OR ")}) AND sector_code:("+prepSectorCodeFilter+") AND budget_period_start_iso_date:[#{settings.current_first_day_of_financial_year}T00:00:00Z TO *] AND budget_period_end_iso_date:[* TO #{settings.current_last_day_of_financial_year}T00:00:00Z]&fl=iati_identifier,budget_value,recipient_country_code,recipient_region_code,budget_period_start_iso_date,budget_period_end_iso_date,sector_code,sector_percentage,&rows=50000"
pulledData = RestClient.get newApiCall
#storeCacheData(sector_parent_data_list( settings.oipa_api_url, "category", "Category (L2)", "Category Name", "High Level Code (L1)", "High Level Sector Description", dac2Code, "category"), fileName)
storeCacheData(sector_parent_data_listv2(pulledData, sectorHierarchy), fileName)
high_level_sector_list = getCacheData(fileName)
else
high_level_sector_list = getCacheData(fileName)
end
settings.devtracker_page_title = 'Sector '+dac2Code+' Page'
erb :'sector/categories',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
category_list: high_level_sector_list,#sector_parent_data_list( settings.oipa_api_url, "category", "Category (L2)", "Category Name", "High Level Code (L1)", "High Level Sector Description", sanitize_input(params[:high_level_sector_code],"p"), "category")
active_link: 'sector'
}
end
# List of all the High level sector projects (e.g. Three Digit DAC Sector)
# Sector Page (e.g. Five Digit DAC Sector)
get '/sector/:high_level_sector_code/categories/:category_code/?' do
# Get the three digit DAC sector data from the API
dac2Code = sanitize_input(params[:high_level_sector_code],"p")
catCode = sanitize_input(params[:category_code],"p")
high_level_sector_list = ''
fileName = 'sector_dac2_'+dac2Code+'_'+catCode
if (!canLoadFromCache(fileName))
prepSectorCodeFilter = ''
sectorHierarchy = JSON.parse(File.read('data/sectorHierarchies.json')).select{|s| s['Category (L2)'].to_i == catCode.to_i}
sectorHierarchy.each_with_index do |elem, index|
if index == sectorHierarchy.length-1
prepSectorCodeFilter = prepSectorCodeFilter + elem['Code (L3)'].to_s
else
prepSectorCodeFilter = prepSectorCodeFilter + elem['Code (L3)'].to_s + ' OR '
end
end
newApiCall = settings.oipa_api_url + "activity?q=participating_org_ref:GB-GOV-* AND reporting_org_ref:(#{settings.goverment_department_ids.gsub(","," OR ")}) AND sector_code:("+prepSectorCodeFilter+") AND budget_period_start_iso_date:[#{settings.current_first_day_of_financial_year}T00:00:00Z TO *] AND budget_period_end_iso_date:[* TO #{settings.current_last_day_of_financial_year}T00:00:00Z]&fl=iati_identifier,budget_value,recipient_country_code,recipient_region_code,budget_period_start_iso_date,budget_period_end_iso_date,sector_code,sector_percentage,&rows=50000"
pulledData = RestClient.get newApiCall
#storeCacheData(sector_parent_data_list( settings.oipa_api_url, "category", "Category (L2)", "Category Name", "High Level Code (L1)", "High Level Sector Description", dac2Code, "category"), fileName)
storeCacheData(sector_parent_data_dac5(pulledData, sectorHierarchy), fileName)
#storeCacheData(sector_parent_data_list(settings.oipa_api_url, "sector", "Code (L3)", "Name", "Category (L2)", "Category Name", sanitize_input(params[:high_level_sector_code],"p"), sanitize_input(params[:category_code],"p")), fileName)
high_level_sector_list = getCacheData(fileName)
else
high_level_sector_list = getCacheData(fileName)
end
settings.devtracker_page_title = 'Sector Category '+catCode+' Page'
erb :'sector/sectors',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
sector_list: high_level_sector_list,#sector_parent_data_list(settings.oipa_api_url, "sector", "Code (L3)", "Name", "Category (L2)", "Category Name", sanitize_input(params[:high_level_sector_code],"p"), sanitize_input(params[:category_code],"p"))
active_link: 'sector'
}
end
#####################################################################
# COUNTRY REGION & GLOBAL PROJECT MAP PAGES
#####################################################################
#Aid By Location Page
get '/location/country/?' do
settings.devtracker_page_title = 'Aid by Location Page'
fileName = 'map_data'
map_data = ''
dfid_complete_country_list = ''
total_coun_bud_loc = ''
country_sector_data = ''
getMaxBudget = ''
if (!canLoadFromCache('country_sector_data'))
storeCacheData(generateCountryDatav5(), 'country_sector_data')
getMainData = getCacheData('country_sector_data')
map_data = getMainData['map_data']
storeCacheData(map_data[1].sort_by{|k,val| val['budget']}.reverse!.first[1]['budget'], 'getMaxBudgetCountryLocation')
country_sector_data = getMainData['countryHash']
getMaxBudget = getCacheData('getMaxBudgetCountryLocation')
else
getMainData = getCacheData('country_sector_data')
map_data = getMainData['map_data']
country_sector_data = getMainData['countryHash']
getMaxBudget = getCacheData('getMaxBudgetCountryLocation')
end
erb :'location/country/index',
:layout => :'layouts/layout',
:locals => {
oipa_api_url: settings.oipa_api_url,
:dfid_country_map_data => map_data[0],
:dfid_country_stats_data => map_data[1],
:sectorData => country_sector_data,
:countryMapData => getCountryBoundsForLocation(map_data[1]),
:maxBudget => getMaxBudget,
active_link: 'aidByLoc',
active_sub_link: 'country',
}
end
# Aid by Region Page
get '/location/regional/?' do
settings.devtracker_page_title = 'Aid by Region Page'
dfid_regional_projects_data = ''
generateRegionData = ''
if (!canLoadFromCache('dfid_regional_projects_data_regions'))
storeCacheData(dfid_regional_projects_datav2("all"), 'dfid_regional_projects_data_regions')
dfid_regional_projects_data = getCacheData('dfid_regional_projects_data_regions')
else
dfid_regional_projects_data = getCacheData('dfid_regional_projects_data_regions')
end
erb :'location/regional/index',
:layout => :'layouts/layout',
:locals => {
:oipa_api_url => settings.oipa_api_url,
:dfid_regional_projects_data => dfid_regional_projects_data,
#:generateRegionData => generateRegionData
active_link: 'aidByLoc',
active_sub_link: 'region',
}
end
# Aid by Global Page
get '/location/global/?' do
dfid_regional_projects_data = ''
if (!canLoadFromCache('dfid_regional_projects_data_global'))
storeCacheData(dfid_regional_projects_datav2("global"), 'dfid_regional_projects_data_global')
dfid_regional_projects_data = getCacheData('dfid_regional_projects_data_global')
else
dfid_regional_projects_data = getCacheData('dfid_regional_projects_data_global')
end
settings.devtracker_page_title = 'Aid by Global Page'
erb :'location/global/index',
:layout => :'layouts/layout',
:locals => {
:oipa_api_url => settings.oipa_api_url,
:dfid_global_projects_data => dfid_regional_projects_data,
active_link: 'aidByLoc',
active_sub_link: 'global',
}
end
#####################################################################
# SOLR BASED PAGES
#####################################################################
get '/search_p/?' do
if (!params['query'])
query= ''
filters = []
response = {}
response['response'] =
{
'numFound' => -1,
'docs' => []
}
settings.devtracker_page_title = 'Search Page'
didYouMeanData = {}
didYouMeanData['dfidCountryBudgets'] = 0
didYouMeanData['dfidRegionBudgets'] = 0
else
query = params['query']
activityStatuses = 'AND activity_status_code:(2)'
filters = prepareFilters(query.to_s, 'F')
response = solrResponse(query, activityStatuses, 'F', 0, '', '')
if(response['response']['numFound'].to_i > 0)
response['response'] = addTotalBudgetWithCurrency(response['response'])
response = addHighlightingToFTSTerms(response)
end
settings.devtracker_page_title = 'Search Results For : ' + query
didYouMeanQuery = sanitize_input(params['query'],"a")
didYouMeanData = generate_did_you_mean_data(didYouMeanQuery,'2')
end
erb :'search/solrTemplate',
:layout => :'layouts/layout',
:locals =>
{
oipa_api_url: settings.oipa_api_url,
query: query,
filters: filters,
response: response['response'],
solrConfig: Oj.load(File.read('data/solr-config.json')),
activityStatus: Oj.load(File.read('data/activity_status.json')),
searchType: 'F',
breadcrumbURL: '',
breadcrumbText: '',
fcdoCountryBudgets: didYouMeanData['dfidCountryBudgets'],
fcdoRegionBudgets: didYouMeanData['dfidRegionBudgets'],
isIncludeClosedProjects: 0
}
end
get '/search/?' do
redirect '/search_p'
end
post '/search_p/?' do
#query = params['query']
query = sanitize_input(params['query'],"newId")
isIncludeClosedProjects = sanitize_input(params['includeClosedProject'],"newId")
if(isIncludeClosedProjects.to_i != 1)
activityStatuses = 'AND activity_status_code:(2)'
else
activityStatuses = 'AND activity_status_code:(2 OR 3 OR 4 OR 5)'
end
filters = prepareFilters(query.to_s, 'F')
response = solrResponse(query, activityStatuses, 'F', 0, '', '')
if(response['response']['numFound'].to_i > 0)
response['response'] = addTotalBudgetWithCurrency(response['response'])
response = addHighlightingToFTSTerms(response)
end
settings.devtracker_page_title = 'Search Results For : ' + query
didYouMeanQuery = sanitize_input(params['query'],"a")
#didYouMeanData = generate_did_you_mean_data(didYouMeanQuery,'2')
#erb :'search/solrSearch',
erb :'search/solrTemplate',
:layout => :'layouts/layout',
:locals =>
{
oipa_api_url: settings.oipa_api_url,
query: query,
filters: filters,
response: response['response'],
solrConfig: Oj.load(File.read('data/solr-config.json')),
activityStatus: Oj.load(File.read('data/activity_status.json')),
searchType: 'F',
breadcrumbURL: '',
breadcrumbText: '',
fcdoCountryBudgets: nil,#didYouMeanData['dfidCountryBudgets'],
fcdoRegionBudgets: nil,#didYouMeanData['dfidRegionBudgets'],
isIncludeClosedProjects: isIncludeClosedProjects
}
end
post '/solr-response' do
query = sanitize_input(params['data']['query'],"newId")
if params['data']['filters'].strip.length > 1
filters = 'AND ' + sanitize_input(params['data']['filters'],"newId")
else
filters = ''
end
searchType = sanitize_input(params['data']['queryType'],"newId")
startPage = sanitize_input(params['data']['page'],"newId")
response = solrResponse(query, filters, searchType, startPage, sanitize_input(params['data']['dateRange'],"newId"), sanitize_input(params['data']['sortType'],"newId"))
if searchType == 'F'
if(response['response']['numFound'].to_i > 0)
response['response'] = addTotalBudgetWithCurrency(response['response'])
response = addHighlightingToFTSTerms(response)
response = response['response']
end
else
if(response['numFound'].to_i > 0)
response = addTotalBudgetWithCurrency(response)
end
end
json :output => response
end
get '/regions/?' do
query = '(298 OR 798 OR 89 OR 589 OR 389 OR 189 OR 679 OR 289 OR 380)'
filters = prepareFilters(query.to_s, 'R')
response = solrResponse(query, 'AND activity_status_code:(2)', 'R', 0, '', '')
if(response['numFound'].to_i > 0)
response = addTotalBudgetWithCurrency(response)
end
settings.devtracker_page_title = 'Search Results For : ' + query
region = {}
region[:code] = "298,798,89,589,389,189,679,289,380"