-
Notifications
You must be signed in to change notification settings - Fork 1
/
process.js
2771 lines (2411 loc) · 71.3 KB
/
process.js
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
// old stuff to move into a new data processing app
watermapApp.tallyDiversions = function(feature){
if(feature !== undefined){
if(feature.properties !== undefined){
var string = "";
var faceAmount = 0;
var faceAmountActive = 0;
var totalFaceAmount = 0;
var totalFaceAmountActive = 0;
var currentDiversionAmount = 0;
// Set the current diversion amount
if((feature.properties.face_value_amount !== undefined) && (feature.properties.face_value_amount > 0)) {
faceAmount = feature.properties.face_value_amount;
}
if((feature.properties.diversion_acre_feet !== undefined) && (feature.properties.diversion_acre_feet > 0)) {
currentDiversionAmount = feature.properties.diversion_acre_feet;
}
if((feature.properties.direct_div_amount !== undefined) && (feature.properties.direct_div_amount > 0)) {
currentDiversionAmount = parseFloat(feature.properties.direct_div_amount);
}
// Increment the diversion tally.
if(faceAmount > 0){
switch(feature.properties.water_right_status){
case 'Permitted':
watermapApp.tally.count_permitted++;
watermapApp.tally.permitted += parseFloat(faceAmount);
watermapApp.tally.total_face_amount += parseFloat(faceAmount);
watermapApp.tally.count++;
break;
case 'Licensed':
watermapApp.tally.count_licensed++;
watermapApp.tally.licensed += parseFloat(faceAmount);
watermapApp.tally.total_face_amount += parseFloat(faceAmount);
watermapApp.tally.count++;
break;
case 'Adjudicated':
watermapApp.tally.count_adjudicated++;
watermapApp.tally.adjudicated += parseFloat(faceAmount);
watermapApp.tally.total_face_amount += parseFloat(faceAmount);
watermapApp.tally.count++;
break;
case 'Cancelled':
case 'Canceled':
watermapApp.tally.count_canceled++;
watermapApp.tally.canceled += parseFloat(faceAmount);
break;
case 'Certified':
watermapApp.tally.count_certified++;
watermapApp.tally.certified += parseFloat(faceAmount);
break;
case 'Claimed':
watermapApp.tally.count_claimed++;
watermapApp.tally.claimed += parseFloat(faceAmount);
break;
case 'Claimed - Local Oversight':
watermapApp.tally.count_claimed_local++;
watermapApp.tally.claimed_local += parseFloat(faceAmount);
break;
case 'Closed':
watermapApp.tally.count_closed++;
watermapApp.tally.closed += parseFloat(faceAmount);
break;
case 'Inactive':
watermapApp.tally.count_inactive++;
watermapApp.tally.inactive += parseFloat(faceAmount);
break;
case 'Non Jurisdictional':
watermapApp.tally.count_non_jurisdictional++;
watermapApp.tally.non_jurisdictional += parseFloat(faceAmount);
break;
case 'Pending':
watermapApp.tally.count_pending++;
watermapApp.tally.pending += parseFloat(faceAmount);
break;
case 'Registered':
watermapApp.tally.count_registered++;
watermapApp.tally.registered += parseFloat(faceAmount);
break;
case 'Rejected':
watermapApp.tally.count_rejected++;
watermapApp.tally.rejected += parseFloat(faceAmount);
break;
case 'Removed':
watermapApp.tally.count_removed++;
watermapApp.tally.removed += parseFloat(faceAmount);
break;
case 'Revoked':
watermapApp.tally.count_revoked++;
watermapApp.tally.revoked += parseFloat(faceAmount);
break;
case 'State Filing':
watermapApp.tally.count_state_filing++;
watermapApp.tally.state_filing += parseFloat(faceAmount);
break;
case 'Temporary':
watermapApp.tally.count_temportary++;
watermapApp.tally.temportary += parseFloat(faceAmount);
break;
case '':
watermapApp.tally.count_unknown++;
watermapApp.tally.unknown += parseFloat(faceAmount);
break;
}
string += '<tr>';
string += '<td><a href="#' + feature.properties.id + '" class="water-right" data="' + feature.properties.id + '">' + feature.properties.name + '</a></td>';
string += '<td>' + watermapApp.addCommas(faceAmount) + '</td>';
string += '<td>' + watermapApp.addCommas(feature.properties.water_right_status) + '</td>';
string += '<td>' + watermapApp.addCommas(feature.properties.water_right_type) + '</td>';
string += '</tr>';
}
if((feature.properties.diversion_storage_amount !== undefined) && (feature.properties.diversion_storage_amount > 0)) {
currentStorageAmount = parseFloat(feature.properties.diversion_storage_amount);
if(currentStorageAmount > 0) {
watermapApp.tally.storage += currentStorageAmount;
}
}
return string;
}
}
};
app.get('/water-rights/summary', function(req, res, options){
/*
watermapApp.tally.diversion = 0;
watermapApp.tally.storage = 0;
watermapApp.tally.count = 0;
watermapApp.tally.total_face_amount = 0;
watermapApp.tally.face_amount_extra = 0;
watermapApp.tally.total_face_amount_active = 0;
watermapApp.tally.adjudicated = 0;
watermapApp.tally.canceled = 0;
watermapApp.tally.certified = 0;
watermapApp.tally.claimed = 0;
watermapApp.tally.claimed_local = 0;
watermapApp.tally.closed = 0;
watermapApp.tally.inactive = 0;
watermapApp.tally.licensed = 0;
watermapApp.tally.non_jurisdictional = 0;
watermapApp.tally.pending = 0;
watermapApp.tally.permitted = 0;
watermapApp.tally.registered = 0;
watermapApp.tally.rejected = 0;
watermapApp.tally.removed = 0;
watermapApp.tally.revoked = 0;
watermapApp.tally.state_filing = 0;
watermapApp.tally.temporary = 0;
watermapApp.tally.unknown = 0;
watermapApp.tally.count_adjudicated = 0;
watermapApp.tally.count_canceled = 0;
watermapApp.tally.count_certified = 0;
watermapApp.tally.count_claimed = 0;
watermapApp.tally.count_claimed_local = 0;
watermapApp.tally.count_closed = 0;
watermapApp.tally.count_inactive = 0;
watermapApp.tally.count_licensed = 0;
watermapApp.tally.count_non_jurisdictional = 0;
watermapApp.tally.count_pending = 0;
watermapApp.tally.count_permitted = 0;
watermapApp.tally.count_registered = 0;
watermapApp.tally.count_rejected = 0;
watermapApp.tally.count_removed = 0;
watermapApp.tally.count_revoked = 0;
watermapApp.tally.count_state_filing = 0;
watermapApp.tally.count_temporary = 0;
watermapApp.tally.count_unknown = 0;
var regex = {$regex: '.*._01$', $options: 'i'};
var lookup = { $and: [{'kind': 'right'},{'id':regex} , {$or: [{'properties.water_right_status': 'Active'},{'properties.water_right_status':'Permitted'},{'properties.water_right_status':'Licensed'},{'properties.water_right_status':'Adjudicated'}]} ]} ;
engine.find_many_by({query: lookup, options: {'limit': 0}},function(error, results) {
if(!results || error) {
console.log("agent query error");
res.send("[]");
return;
}
var obj = [];
var table = "";
var count = 0;
watermapApp.tally.count_active = 0;
for (i in results){
count++;
table += watermapApp.tallyDiversions(results[i]);
}
watermapApp.tally.total_face_amount_active = watermapApp.addCommas(watermapApp.tally.total_face_amount_active);
var overallocation = Math.round((watermapApp.tally.total_face_amount) / 71000000 * 100) + "%";
} ,{}, {'limit': 55000}); */
res.render("tally_cached.ejs",{layout:false});
});
/**
* Search function for typeahead
*/
app.get('/list/watersheds', function(req, res, options){
var query = { $and: [ {'kind': 'right'}, {$or: [{'properties.water_right_status': 'Active'},{'properties.water_right_status':'Permitted'},{'properties.water_right_status':'Licensed'},{'properties.water_right_status':'Adjudicated'}]}, {'coordinates': {$exists: true}}]};
engine.find_many_by({query: query, options: {'limit': 0/* , 'sort': {'properties.watershed':1 } */}},function(error, results) {
if(!results || error) {
res.send("[]");
return;
}
var array = [];
var i;
for (i in results){
if(results[i]['properties']['watershed'] !== null && results[i]['properties']['watershed'] !== "")
array.push(results[i]['properties']['watershed']);
}
console.log(array);
var list = _.uniq(array).sort();
console.log(list);
res.send(list);
},{'properties.watershed': 1});
});
/////////////////////////////////////////////////////////////////////////////////////////////
// Update Water Rights Data
// Load data from eWRIMS database and GIS server.
/////////////////////////////////////////////////////////////////////////////////////////////
// Global helpers & counters.
watermapApp.xlsCounter = 604;
watermapApp.loadFileCounter = 0;
watermapApp.dbIDs = [];
watermapApp.current = 0;
watermapApp.counterXLSParser = 0;
watermapApp.getBatchCounter = 0;
watermapApp.GISGroup = 'S014'; // Used for downloading GIS data from server.
watermapApp.XLSGroup = 'no_dups';
watermapApp.GISCounter = 0;
watermapApp.GISLoadJSONCounter = 0;
watermapApp.EWRIMSReportCurrent = 0;
watermapApp.EWRIMSReportsCounter = 0;
/////////////////////////////////////////////////////////////////////////////////////////////
// Data handling callbacks.
/////////////////////////////////////////////////////////////////////////////////////////////
//http://ciwqs.waterboards.ca.gov/ciwqs/ewrims/EWServlet?Page_From=EWWaterRightPublicSearch.jsp&Redirect_Page=EWWaterRightPublicSearchResults.jsp&Object_Expected=EwrimsSearchResult&Object_Created=EwrimsSearch&Object_Criteria=&Purpose=&appNumber=&permitNumber=&licenseNumber=&watershed=&waterHolderName=&source=
//http://www.waterboards.ca.gov/water_issues/programs/ewrims/statements/docs/
/**
* Get database ID for all records in eWRIMS database.
* Scrape all pages to get the ID to get the download link to get the xls files
* These are stored as flat files, which need to be cleaned up and cat'ed into one file.
* Takes about 1 day to run (947 pages)
* Is not error proof, also had to get the missing values and reload them - then cat into one master file.
*/
// @TODO Refactored, test it.
app.get('/data/water_rights/scrape/pages', function(req, res, options){
watermapApp.getXLSAllPages();
});
// Scrape all pages to get the ID to get the download link to get the xls files
app.get('/data/water_rights/scrape/app_id_array', function(req, res, options){
watermapApp.getXLSByAppIDArray();
});
/** Once we have all of the DB ids in a CSV file on the server (manually created),
* download all xls files for water rights.
*/
app.get('/data/water_rights/download/xls', function(req, res, options){
watermapApp.downloadWaterRightDBDataXLS();
});
/**
* Load view reports pages, and store the results.
* Then parse results for form ids and store them
*/
app.get('/data/water_rights/reports', function(req, res, options){
watermapApp.loadWaterRightsReportsXLS();
});
app.get('/data/water_rights/reports/parse', function(req, res, options){
watermapApp.parseWaterRightsReportsXLS();
});
app.get('/data/water_rights/reports/download', function(req, res, options){
watermapApp.loadWaterRightsReportsDownload();
});
app.get('/data/water_rights/reports/parse_full', function(req, res, options){
watermapApp.parseReportFile();
});
app.get('/data/update/ewrims_db_id', function(req, res, options){
watermapApp.updateEWRIMSID();
});
// Once downloaded, parse all XLS files. Convert to object for mongo. Store in database.
app.get('/data/water_rights/update/db', function(req, res, options){
watermapApp.parseXLSWaterRights();
});
app.get('/consolidate/reports', function(req, res, options){
watermapApp.consolidateReports();
});
// Lookup GIS data for sets of records to get Lat/Lon and other extra values. Update in Mongo.
app.get('/data/water_rights/update/gis', function(req, res, options){
/* var GISinterval = setInterval(function(){ */
watermapApp.GISCounter = 0;
//watermapApp.GISGroup = watermapApp.gisFacets[watermapApp.GISCounter];
console.log(watermapApp.GISGroup);
console.log("getting GIS: " + watermapApp.GISGroup + " " + watermapApp.GISCounter);
watermapApp.getGISRights();
watermapApp.GISCounter++;
if(watermapApp.GISGroup === undefined) {
clearInterval(GISinterval);
}
/* },1000); */
});
/**
* Read and parse each stored XLS file from the eWRIMS database.
*/
watermapApp.parseReportFile = function(db_id){
var q = async.queue(function (task, callback) {
console.log(task.db + " " + task.form);
var parsed = watermapApp.parseReportFromHTML(task.db, task.form);
watermapApp.getBatchCounter++;
callback();
}, 2);
// assign a callback
q.drain = function() {
console.log('all items have been processed');
};
// add some items to the queue
fs.readFileSync('./server_data/allreports2011.csv').toString().split('\n').forEach(function (line) {
var split_line = line.split(',');
q.push({db: split_line[0], form: split_line[4]}, function (err) {
console.log('finished processing foo');
});
});
};
watermapApp.updateEWRIMSID = function(){
var obj = {};
/* console.log(db_id); */
fs.readFileSync('./server_data/all_ewrims_ids.csv').toString().split('\n').forEach(function (line) {
var split_line = line.split(',');
/* console.log(split_line); */
watermapApp.dbIDs.push(new Array(split_line[1],split_line[0]));
});
// Do a query every 4 seconds -- should be about 8 concurrent queries.
// Should do 100 in 6 minutes.
watermapApp.setEWRIMSID = setInterval(function() {
watermapApp.setEWRIMS(watermapApp.dbIDs[watermapApp.loadFileCounter][0],watermapApp.dbIDs[watermapApp.loadFileCounter][1]);
watermapApp.loadFileCounter++;
watermapApp.getBatchCounter++;
//console.log(watermapApp.dbIDs[watermapApp.loadFileCounter]);
if(watermapApp.dbIDs[watermapApp.loadFileCounter] === undefined) {
clearInterval(watermapApp.setEWRIMSID);
}
}, 200);
};
watermapApp.consolidateReports = function(){
// look up each record with reports
// load report details
// resave with year as the key
// save
var lookup = { $and: [{'properties.reports': { $exists: true}} ,{'coordinates': {$exists: true} } ]} ;
engine.find_many_by(lookup,function(error, results) {
if(!results || error) {
console.log("agent query error");
res.send("[]");
return;
}
for (i in results){
var feature = results[i];
var newReports = {};
for(r in feature.properties.reports){
var report = feature.properties.reports[r];
if(report !== null){
if(report.amount_diverted !== undefined){
if(report.amount_diverted["Total"] === undefined) {
var total_diverted = 0;
var total_used = 0;
var i = 0;
for(i in report.amount_diverted){
if(i < 12){
for(month in report.amount_diverted[i]){
total_diverted += parseInt(report.amount_diverted[i][month]);
}
for(month in report.amount_used[i]){
total_used += parseInt(report.amount_used[i][month]);
}
}
}
report.amount_diverted["Total"] = total_diverted;
report.amount_used["Total"] = total_used;
report.total_used = total_used;
report.total_diverted = total_diverted;
}
}
if(report.total_diverted === '') {
}
/*
if(report.year === undefined) {
newReports['unknown-' + r] = report;
}
else {
newReports[report.year] = report;
}
*/
}
}
//console.log( r ) ;
//console.log(newReports);
/* feature.properties.reports = newReports; */
//console.log( feature.properties.reports);
watermapApp.storeWaterRightFromEWRIMSDatabase(feature);
}
},{},{limit: 10});
};
watermapApp.setEWRIMS = function(app_pod, ewrims_db_id){
console.log(app_pod + " " + ewrims_db_id);
var query = [];
query.push({'properties.application_pod' : app_pod});
// @TODO - storing in separate collection for testing purposes.
var lookup = {
$and: [{'kind': 'right'}, {$and: query}]
};
// $and: [{'kind': 'right'}, {$or: [{'properties.application_pod': feature['properties']['application_pod']},{'properties.ewrims_db_id': feature['properties']['ewrims_db_id']}]}]
engine.find_many_by(lookup,function(error, results) {
/* console.log(results); */
if(!results || error) {
console.log("agent query error");
/* results.send("[]"); */
return;
}
// Create if record does not exist.
if(results.length != 0) {
// merge _id from existing record with new stuff.
var original = results[0];
original.properties.ewrims_db_id = ewrims_db_id;
// Save the original version, to which has been added the new items from the feature.
engine.save(original,function(error,agent) {
if(error) { res.send("Server agent storage error #5",404); return; }
if(!agent) { res.send("Server agent storage error #6",404); return; }
});
}
});
};
watermapApp.parseReportFromHTML = function(db_id, form_id){
console.log("parse: " + db_id + " " + form_id);
var filename = 'water_rights_full_reports_all/water_right-' + db_id + '_' + form_id +'.txt';
var body = fs.readFileSync(filename,'utf8');
if(body !== ''){
jsdom.env({
html: body,
scripts: [
'http://code.jquery.com/jquery-1.8.3.min.js'
],
done: function (err, window) {
var $ = window.jQuery;
var output = '';
var obj = {};
obj.properties = {};
obj.properties.reports = [];
var thisReport = {};
thisReport.usage = new Array();
thisReport.usage_quantity = new Array();
if($ !== undefined){
var testEmpty = $('body').html();
}
var quantityCount = 0;
quantity = $('table tr th:contains("Purpose of Use")').parent().parent().find('tr').each(function(){
if(quantityCount !== 0) {
var usage = $(this).find('td:first-child').html();
var quantity = $(this).find('td:last-child').html();
if(usage !== undefined){
usage = usage.replace(/(\r\n|\n|\r)/gm,"");
usage = usage.replace(/\s+/g," ");
thisReport.usage.push(usage);
}
else{
thisReport.usage.push('');
}
if(quantity !== undefined){
quantity = quantity.replace(/(\r\n|\n|\r)/gm,"");
quantity = quantity.replace(/\s+/g," ");
thisReport.usage_quantity.push(quantity);
}
else{
thisReport.usage_quantity.push('');
}
}
quantityCount++;
});
var diversionItemArray = new Array();
var diversionUsedArray = new Array();
$('table tr th:contains("Amount directly diverted")').parent().parent().find('tr').each(function(){
var month = '';
if($(this).find('td:nth-child(1)').html() === 'September '){
month = 'September';
}
else {
month = $(this).find('td:nth-child(1)').html();
}
var diversion_item = {};
diversion_item[month] = $(this).find('td:nth-child(2)').html();
var diversion_used = {}
diversion_used[month] = $(this).find('td:nth-child(3)').html();
if($(this).find('td:nth-child(1)').html() !== undefined){
diversionItemArray.push(diversion_item);
diversionUsedArray.push(diversion_used);
}
if($(this).find('td:nth-child(1)').html() === 'Total'){
thisReport.diversion_total = $(this).find('td:nth-child(2)').html();
thisReport.used_total = $(this).find('td:nth-child(2)').html();
}
var unit = $(this).find('th:contains("Amount directly diverted or")').html();
if(unit !== undefined){
unit = unit.split('<br />\r\n')[2];
unit = watermapApp.trim(unit);
unit = unit.replace("\r\n","");
unit = unit.replace("(","");
unit = unit.replace(")","");
thisReport.diversion_unit = unit;
}
thisReport.total_diverted = $(this).find('td:nth-child(2)').html();
thisReport.total_used = $(this).find('td:nth-child(2)').html();
console.log("TOTAL USED" + thisReport.total_used);
console.log("TOTAL DIVERTED" + thisReport.total_diverted);
});
thisReport.amount_diverted = diversionItemArray;
thisReport.amount_used = diversionUsedArray;
//thisReport.diversion = watermapApp.trim(diversion);
var year = $('h3:contains("[FINAL SUBMITTED VERSION]")').html();
console.log(year);
if(year !== undefined){
thisReport.year = year.split('FOR')[1];
thisReport.year.replace('\r\n','');
thisReport.year = watermapApp.trim(thisReport.year);
}
/*
thisReport.conservation = $('table tr th:contains("Conservation of Water")').parent().parent().find('tr::nth-child(2) td:last-child');
thisReport.conservation = watermapApp.trim(thisReport.conservation);
*/
thisReport.ewrims_db_id = db_id;
thisReport.ewrims_form_id= form_id; //push to array
obj.properties.reports.push(thisReport);
console.log(obj);
// The XLS file has an odd output from eWRIMS, so to extract the data we read each line and map fields to the fields we are storing in Mongo.
// @NOTE Does not have geocoded data, that has to come from the GIS server.
var done = watermapApp.storeWaterRightFromEWRIMSDatabase(obj);
return true;
}
});
}
};
/////////////////////////////////////////////////////////////////////////////////////////////
// Process data.
/////////////////////////////////////////////////////////////////////////////////////////////
/**
* Load view reports pages, and store the results.
* Then parse results for form ids and store them
*/
watermapApp.loadWaterRightsReportsXLS = function(){
fs.readFileSync('./server_data/db_ids_' + watermapApp.XLSGroup + '.csv').toString().split('\n').forEach(function (line) {
var split_line = line.split(',');
watermapApp.dbIDs.push(split_line[3]);
});
// Do a query every 4 seconds -- should be about 8 concurrent queries.
// Should do 100 in 6 minutes.
watermapApp.getFile = setInterval(function() {
watermapApp.downloadReportForm(watermapApp.dbIDs[watermapApp.loadFileCounter]);
watermapApp.loadFileCounter++;
watermapApp.getBatchCounter++;
console.log(watermapApp.dbIDs[watermapApp.loadFileCounter]);
if(watermapApp.dbIDs[watermapApp.loadFileCounter] === undefined) {
clearInterval(watermapApp.getFile);
}
}, 1000);
};
watermapApp.trim = function(str){
if(str !== undefined){
str = str.replace(/^\s+/, '');
for (var i = str.length - 1; i >= 0; i--) {
if (/\S/.test(str.charAt(i))) {
str = str.substring(0, i + 1);
break;
}
}
return str;
}
else {
return '';
}
}
watermapApp.parseWaterRightsReportsXLS = function(){
fs.readFileSync('./server_data/db_ids_' + watermapApp.XLSGroup + '.csv').toString().split('\n').forEach(function (line) {
var split_line = line.split(',');
watermapApp.dbIDs.push(split_line[3]);
});
watermapApp.getFile = setInterval(function() {
watermapApp.parseWaterRightReport(watermapApp.dbIDs[watermapApp.loadFileCounter]);
watermapApp.loadFileCounter++;
watermapApp.getBatchCounter++;
console.log(watermapApp.dbIDs[watermapApp.loadFileCounter]);
if(watermapApp.dbIDs[watermapApp.loadFileCounter] === undefined) {
clearInterval(watermapApp.getFile);
}
}, 100);
};
//15035 stopped at
watermapApp.parseWaterRightReport = function(db_id) {
var filename = 'water_rights_reports_all/water_right-' + db_id +'.txt';
var body = fs.readFileSync(filename,'utf8');
jsdom.env({
html: body,
scripts: [
'http://code.jquery.com/jquery-1.8.3.min.js'
],
done: function (err, window) {
var $ = window.jQuery;
var output = '';
var testEmpty = $('body #content form table tr td').html();
if(testEmpty !== undefined){
if(testEmpty.indexOf('No reports submitted') === -1){
$('body #content form table tr').each(function(){
outputTestEmpty = $(this).html();
if(outputTestEmpty === " <span id=\"none-submitted-message\">\n No reports submitted.\n </span>\n"){
output = '';
return;
}
else {
output += db_id + ",";
output += $(this).find('td:first-child').html() + ",";
output += $(this).find('td:nth-child(2)').html() + ",";
output += $(this).find('td:last-child a').attr('href') + '\n';
}
});
/*
console.log('done ' + db_id);
console.log(output);
*/
fs.writeFile('reports_all/water_right_reports' + db_id + '.txt', output, function (err) {
if (err) return console.log(err);
/* console.log("saved " + db_id); */
});
}
}
}});
};
/* Scrape all pages to get the ID to get the download link to get the xls files*/
watermapApp.getXLSAllPages = function(){
setInterval(function(){
var i = watermapApp.current;
var query = 'http://ciwqs.waterboards.ca.gov/ciwqs/ewrims/EWServlet?Page_From=EWWaterRightPublicSearch.jsp&Redirect_Page=EWWaterRightPublicSearchResults.jsp&Object_Expected=EwrimsSearchResult&Object_Created=EwrimsSearch&Object_Criteria=&Purpose=&appNumber=&watershed=&waterHolderName=&curPage=' + i + '&sortBy=APPLICATION_NUMBER&sortDir=ASC&pagination=true';
/* console.log(query); */
var j = request.jar();
var cookie = request.cookie('JSESSIONID=c6e01ad5ec1922a1cc53d07a5d15e0b109d7383f430830012cd584e52f0e7622');
j.add(cookie);
request.get({ uri:query, jar: j }, function (error, response, body) {
if (error && response.statusCode !== 200) {
console.log('Error when contacting server')
}
var output = '';
jsdom.env({
html: body,
scripts: [
'http://code.jquery.com/jquery-1.8.3.min.js'
],
done: function (err, window) {
var $ = window.jQuery;
$('body table.dataentry tr').each(function(){
var app_id = $(this).find('td:first-child a').html();
if (app_id === undefined) {
var app_id = $(this).find('td:first-child').html();
}
var link = $(this).find('td:last-child a').attr('href') + '\n';
/* if(app_id !== undefined) { */
output = output + app_id + " , " + link;
/* } */
});
console.log('done ' + i);
fs.writeFile('files/water_right_' + i + '.txt', output, function (err) {
if (err) return console.log(err);
console.log("saved " + i);
if(output === '') {
watermapApp.current--;
console.log('empty, restarting ' + i);
}
});
}});
});
watermapApp.current++;
}, 20000);
};
// Scrape all pages to get the ID to get the download link to get the xls files
watermapApp.getXLSByAppIDArray = function(){
/* var max = 976; */
setInterval(function(){
var i = watermapApp.current;
var query = 'http://ciwqs.waterboards.ca.gov/ciwqs/ewrims/EWServlet?Page_From=EWWaterRightPublicSearch.jsp&Redirect_Page=EWWaterRightPublicSearchResults.jsp&Object_Expected=EwrimsSearchResult&Object_Created=EwrimsSearch&Object_Criteria=&Purpose=&appNumber=' + app_id_array[i] + '&permitNumber=&licenseNumber=&watershed=&waterHolderName=&source=';
console.log(query);
var j = request.jar();
var cookie = request.cookie('JSESSIONID=c795728324aa8f2db0d775555a94ed03ea53eea3bd96cfd78c6add9fd178ba78');
j.add(cookie);
request.get({ uri:query, jar: j }, function (error, response, body) {
if (error && response.statusCode !== 200) {
console.log('Error when contacting server')
}
var output = '';
jsdom.env({
html: body,
scripts: [
'http://code.jquery.com/jquery-1.8.3.min.js'
],
done: function (err, window) {
var $ = window.jQuery;
/* console.log(body); */
$('body table.dataentry tr').each(function(){
var app_id = $(this).find('td:first-child a').html();
if (app_id === undefined) {
var app_id = $(this).find('td:first-child').html();
}
var link = $(this).find('td:last-child a').attr('href') + '\n';
/* if(app_id !== undefined) { */
output = output + app_id + " , " + link;
/* } */
});
console.log('done ' + i);
fs.writeFile('files_extra/water_right_' + i + '.txt', output, function (err) {
if (err) return console.log(err);
console.log("saved " + i);
if(output === '') {
watermapApp.current--;
console.log('empty, restarting ' + i);
}
});
}});
});
watermapApp.current++;
}, 10000);
};
watermapApp.loadWaterRightsReportsDownload = function() {
// open csv file
// read first line
// split
// take third value
// @TODO may have limits on how many to do at once.
// @TODO Also, it would take 11 days to download them all individually--- which is probably necessary because the
// XLS file is generated dynamically.
// It's 30-seconds to download the data, and 1 minute to download the data from the DB server and the GIS server.
// Would be nice if we could do it all in one swoop, and then get a list of updated and new records - especially because the records only change once a year it seems.
// The GIS server might be able to tell us which records are new - if the Water Control Board is not able to help.
fs.readFileSync('./server_data/allreports-txt-pre2008.csv').toString().split('\n').forEach(function (line) {
var split_line = line.split(',');
/* console.log(split_line); */
watermapApp.dbIDs.push(new Array(split_line[0],split_line[4],split_line[3]));
});
/* console.log(watermapApp.dbIDs); */
// Do a query every 4 seconds -- should be about 8 concurrent queries.
// Should do 100 in 6 minutes.
watermapApp.getFile = setInterval(function() {
watermapApp.downloadReport(watermapApp.dbIDs[watermapApp.loadFileCounter][0],watermapApp.dbIDs[watermapApp.loadFileCounter][1], watermapApp.dbIDs[watermapApp.loadFileCounter][2]);
watermapApp.loadFileCounter++;
watermapApp.getBatchCounter++;
console.log(watermapApp.dbIDs[watermapApp.loadFileCounter][0] + " " + watermapApp.dbIDs[watermapApp.loadFileCounter][1]);
if(watermapApp.dbIDs[watermapApp.loadFileCounter] === undefined) {
clearInterval(watermapApp.getFile);
}
}, 2000);
};
/**
* Download the XLS files for each EWRIMS database record.
*/
watermapApp.downloadWaterRightDBDataXLS = function() {
// open csv file
// read first line
// split
// take third value