-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
1143 lines (1028 loc) · 43.2 KB
/
app.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
const http = require('http'),
process = require('process'),
fs = require('fs'),
path = require('path'),
contentTypes = require('./utils/content-types'),
sysInfo = require('./utils/sys-info'),
env = process.env,
mongo = require('mongodb').MongoClient,
mongoose = require('mongoose'),
passport = require('passport'),
LocalStrategy= require('passport-local').Strategy,
express = require('express'),
session = require('express-session'),
mongoStore = require('connect-mongodb-session')(session),
bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
crypto = require('crypto'),
emailer = require('nodemailer'),
//load schemas
userschema = require('./schema/user'),
voluschema = require('./schema/volunteer'),
animalschema = require('./schema/animal'),
schSchema = require('./schema/schedule');
var dbUrl = 'mongodb://localhost:27017/volunteers';
//look for process variables (ie, we're deployed on open shift) to rewrite the url
if (process.env.MONGODB_PASSWORD) {
dbUrl = 'mongodb://' + process.env.MONGODB_USER + ":" +
process.env.MONGODB_PASSWORD + "@" +
process.env.MONGODB_IP + ":" +
process.env.MONGODB_PORT + "/" +
process.env.MONGODB_DATABASE;
}
var defaultUser = 'admin';
if (process.env.LUNAS_DEFAULT_USER) {
defaultUser = process.env.LUNAS_DEFAULT_USER;
}
var defaultPass = 'admin';
if (process.env.LUNAS_DEFAULT_PASS) {
defaultPass = process.env.LUNAS_DEFAULT_PASS;
}
var defaultEmail = '';
if (process.env.LUNAS_DEFAULT_EMAIL) {
defaultEmail = process.env.LUNAS_DEFAULT_EMAIL;
}
//Data Access Obj.
var User;
var Volunteer;
var Schedule;
var Animal;
//TODO : create a new gmail account for volunteering . sources suggest that we can dispatch 99 emails a day this way.
// we may have to do some configurating on the account to make this happen.
//var emailTransport = emailer.createTransport('smtps:tbd%40gmail.com:[email protected]');
var emailTransport = {}; //emailer.createTransport('smtps:tbd%40gmail.com:[email protected]');
//use global (ES6) promises
mongoose.Promise = global.Promise;
mongoose.connect(dbUrl, { useMongoClient : true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error to db'));
//create collection roots
db.once('open', function() {
User = mongoose.model('User', userschema.UserSchema);
//do we have at least one user?
User.count({}, function(err, count) {
if (count == 0) {
createUser(defaultUser, defaultPass, defaultEmail, 0);
}
});
Volunteer = mongoose.model('Volunteer', voluschema.VolunteerSchema);
Schedule = mongoose.model('Schedule', schSchema.ScheduleSchema);
Animal = mongoose.model('Animal', animalschema.AnimalSchema);
});
var app = express();
var store = new mongoStore(
{
uri : dbUrl,
collection: 'sessionStore'
}
);
store.on('error', function(error) {
assert.ifError(error);
assert.ok(false);
});
var sessionSecret = "localhost";
if (process.env.LUNAS_SESSION_SECRET) {
sessionSecret = process.env.LUNAS_SESSION_SECRET;
}
app.use(express.static('static'));
app.use('/bower', express.static(path.join(__dirname, 'bower_components')));
app.use(express.static('views'));
app.use(cookieParser());
app.use(bodyParser.urlencoded( { extended : true }));
app.use(bodyParser.json());
app.use(session( {
secret : sessionSecret,
cookie : {
maxAge : 2*1000*60*60*24*7 //2 weeks
},
store : store,
saveUninitialized : true,
resave : true
})); //must precede passport session
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
done(null, user.username);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
passport.use('local', new LocalStrategy( {
usernameField : 'username',
passwordField : 'password',
passReqToCallback : true
},
//verification method:
function(req, username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
function verifyAuth(req,res,next) {
if ( !req.isAuthenticated() ) {
return res.redirect('/');
}
next();
};
function validateNumber(n, defaultValue) {
if (typeof n === "undefined") {
return defaultValue;
}
if (Number.isFinite(n)) {
return n;
}
if (!Number.isNaN(Number.parseInt(n))) {
return Number.parseInt(n);
}
return defaultValue;
};
function createUser(uname, pword, emailAddress, roleNumber) {
var p = User.hashpw(pword);
var u = new User({username : uname, password : p , email : emailAddress, role : roleNumber});
u.save(function(err) {
if (err) console.log(err);
});
};
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
};
////////////////////////////////////
/// API routes
////////////////////////////////////
//user management - view / edit registered users of the portal
app.get('/api/users',
verifyAuth,
function(req, res) {
User.find(function(err, users) {
if (err) res.send(err);
else
res.json(users);
});
});
app.post('/api/users',
verifyAuth,
function(req, res) {
//update a user
if (req.body.id) {
User.findOne({ _id: req.body.id },
function (err, user) {
if (user) {
user.email = req.body.email;
user.role = req.body.role;
user.save(
function(err) {
if (err) console.log(err);
});
}
});
}
//return current list of users
User.find(function(err, users) {
if (err) res.send(err); else
res.json(users);
});
});
app.delete('/api/users',
verifyAuth,
function(req, res) {
//remove a user
//return current list of users
User.find(function(err, users) {
if (err) res.send(err); else
res.json(users);
});
});
//////////////////////////////////////
//volunteer management - view, search, edit, volunteers stored in the portal
const itemsPerPage = 20;
//look for page# parameter on the query - if not found assume first page
function buildPagination(req) {
var page = req.query.page || 0;
return { skip : page*itemsPerPage, limit : itemsPerPage};
};
function buildCriteria(req) {
var criteria = {}; //we're going to AND together a set of clauses
var critList = [];
if (typeof req.query.email != "undefined") {
critList.push({'email' : new RegExp(req.query.email, 'i')});
}
if (typeof req.query.name != "undefined") {
//if name term contains a space they might be typing a first name part and a last name part or vice versa (search for smith bob vs bob smith)
if (req.query.name.indexOf(' ') > 0) {
//what if we're looking for some name via three pieces? haha
var tokes = req.query.name.split(' ');
var fnReg = new RegExp(tokes[0].trim(), 'i');
var lnReg = new RegExp(tokes[1].trim(), 'i');
critList.push({'$or' : [ {'firstName' : fnReg}, {'lastName' : lnReg}]});
} else {
//use same regex for both
var reg = new RegExp(req.query.name, 'i');
critList.push({'$or' : [ {'firstName' : reg}, {'lastName' : reg}]});
}
}
if (typeof req.query.training != "undefined") {
var training = req.query.training;
//we expect this to be a # 0 .. 8
var fields = ['trainedCats', 'trainedCatsPetsmart', 'trainedDogs', 'trainedRabbit', 'trainedSmalls', 'trainedCatsQuarantine', 'trainedDogsQuarantine', 'trainedRabbitQuarantine', 'trainedSmallsQuarantine'];
var fname = 'volunteerData.status.' + fields[training];
var c = {};
c[fname] = {'$nin' : [null]};
critList.push(c);
}
if (typeof req.query.interests != "undefined") {
var interests = req.query.interests;
//we expect this to be a # 0 .. 10
var fields = ['cats', 'dogs', 'rabbits', 'smalls', 'maintenance', 'fundraising', 'events', 'fosterCare', 'adopterEducation', 'donationTransport', 'humaneEducation'];
var fname = 'volunteerData.interests.' + fields[interests];
var c = {};
c[fname] = {'$gt' : 0};
critList.push(c);
}
if (typeof req.query.availability != "undefined") {
var av = req.query.availability;
//we expect this to be in the form x_y : day and time period ...
var dayNames = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'];
var timeNames = ['morning', 'afternoon', 'evening'];
var tokes = av.split("_");
var dayIndex = parseInt(tokes[0]);
var timeIndex = parseInt(tokes[1]);
var faccess = 'volunteerData.availability.' + dayNames[dayIndex] +'.' +timeNames[timeIndex];
var o = {};
o[faccess] = true;
critList.push(o);
}
if (typeof req.query.activeOnly != "undefined") {
critList.push({'volunteerData.activeVolunteer' : true});
}
if (typeof req.query.age != "undefined") {
//back calculate the birthday
var age = req.query.age;
var bday = new Date();
bday.setFullYear(bday.getFullYear() - age);
critList.push({'volunteerData.birthday' : {$lte : bday}});
}
//we want all of these supplied criteria to be true
if (critList.length > 0) {
criteria['$and'] = critList;
}
return criteria;
};
function volunteerTableQuery(req, res) {
//examine the query parameters for any other filters or criteria
var criteria = buildCriteria(req);
var options = buildPagination(req);
//return current list of volunteers
//plausibly we want to project here since this query drives a summary table
var projection = {
};
//count in this filter set
Volunteer.count(criteria, function(err, c) {
var pageCount = c / itemsPerPage;
Volunteer.find(criteria, projection, options).sort('lastName').exec(function(err, vtrs) {
if (err)
res.send(err);
else {
var paginateData = {pageCount : pageCount, data : vtrs};
res.json(paginateData);
}
});
});
};
app.get('/api/volunteers/' ,
verifyAuth,
function (req, res) {
if (req.query.id) {
Volunteer.findOne({ _id: req.query.id }, function (err, v) {
if (err)
res.send(err);
else
res.json(v);
});
} else {
volunteerTableQuery(req, res);
}
});
//upserts
app.post('/api/volunteers/' ,
verifyAuth,
function (req, res) {
//if the body doesn't supply an ID we are inserting a new one
var oid = req.body._id;
if (!oid) {
oid = new mongoose.mongo.ObjectID();
}
//VALIDATION / defaulting
var hoursValue = validateNumber(req.body.hoursWorked, 0);
var validatedNoShows = validateNumber(req.body.noShows, 0);
var prefContact = validateNumber(req.body.contactPreference, 0);
var iCat = validateNumber(req.body.interestscats, -1);
var iDog = validateNumber(req.body.interestsdogs, -1);
var iRab = validateNumber(req.body.interestsrabbits, -1);
var iSml = validateNumber(req.body.interestssmalls, -1);
var iMnt = validateNumber(req.body.interestsmaintenance, -1);
var iFnd = validateNumber(req.body.interestsfundraising, -1);
var iEvt = validateNumber(req.body.interestsevents, -1);
var iFos = validateNumber(req.body.interestsfostercare, -1);
var iAdo = validateNumber(req.body.interestsadoptereducation, -1);
var iDon = validateNumber(req.body.interestsdonationtransport, -1);
var iHum = validateNumber(req.body.interestshumaneeducation, -1);
Volunteer.findOneAndUpdate(
{ _id : oid },
{
email : req.body.email,
firstName : req.body.firstName,
lastName : req.body.lastName,
address : req.body.address,
city : req.body.city,
state : req.body.state,
zip : req.body.zip,
phoneNumber : req.body.phoneNumber,
alternatePhoneNumber : req.body.altPhoneNumber,
workPhoneNumber : req.body.workPhoneNumber,
canGetSMS : req.body.canGetSMS,
contactPreference : prefContact,
doNotEmail : req.body.doNotEmail,
contactNotes : req.body.contactNotes,
//TODO should we check to see if we have any data to save first?
volunteerData : {
activeVolunteer : req.body.active,
specialNeeds : req.body.specialNeeds,
foster : req.body.foster,
fostering : req.body.fostering,
noShows : validatedNoShows,
birthday : req.body.birthday,
started : req.body.started,
lastSeen : req.body.lastSeen,
hoursWorked : hoursValue,
notes : req.body.notes,
partners : req.body.partners,
dependents : req.body.dependents,
emergencyContactName : req.body.emergencyContactName,
emergencyContactNumber : req.body.emergencyContactNumber,
emergencyContactRelationship : req.body.emergencyContactRelationship,
status : {
waiver : req.body.statuswaiver,
oriented : req.body.statusoriented,
trainedCats : req.body.statustrainedCats,
trainedCatsPetsmart : req.body.statustrainedCatsPetsmart,
trainedDogs : req.body.statustrainedDogs,
trainedRabbit : req.body.statustrainedRabbit,
trainedSmalls : req.body.statustrainedSmalls,
trainedCatsQuarantine : req.body.statustrainedCatsQuarantine,
trainedDogsQuarantine : req.body.statustrainedDogsQuarantine,
trainedRabbitQuarantine : req.body.statustrainedRabbitQuarantine,
trainedSmallsQuarantine : req.body.statustrainedSmallsQuarantine
},
interests : {
cats : iCat,
dogs : iDog,
rabbits : iRab,
smalls : iSml,
maintenance : iMnt,
fundraising : iFnd,
events : iEvt,
fosterCare : iFos,
adopterEducation : iAdo,
donationTransport : iDon,
humaneEducation : iHum
},
availability : {
monday : {
morning : req.body.availabilitymondaymorning,
afternoon : req.body.availabilitymondayafternoon,
evening : req.body.availabilitymondayevening
},
tuesday : {
morning : req.body.availabilitytuesdaymorning,
afternoon : req.body.availabilitytuesdayafternoon,
evening : req.body.availabilitytuesdayevening
},
wednesday : {
morning : req.body.availabilitywednesdaymorning,
afternoon : req.body.availabilitywednesdayafternoon,
evening : req.body.availabilitywednesdayevening
},
thursday : {
morning : req.body.availabilitythursdaymorning,
afternoon : req.body.availabilitythursdayafternoon,
evening : req.body.availabilitythursdayevening
},
friday : {
morning : req.body.availabilityfridaymorning,
afternoon : req.body.availabilityfridayafternoon,
evening : req.body.availabilityfridayevening
},
saturday : {
morning : req.body.availabilitysaturdaymorning,
afternoon : req.body.availabilitysaturdayafternoon,
evening : req.body.availabilitysaturdayevening
},
sunday : {
morning : req.body.availabilitysundaymorning,
afternoon : req.body.availabilitysundayafternoon,
evening : req.body.availabilitysundayevening
},
notes : req.body.availabilitynotes
}
},
donorData : {
gifts : req.body.donorDataGifts
},
adopteeData : {
adoptions : req.body.adopteeDataAdoptions
},
boardingData : {
lastBoarded : req.body.boardingDate,
notes : req.body.boardingNotes
},
disqualifyingData : {
surrenderedAnimal : req.body.dqSurrenderDate,
failedVetCheck : req.body.dqFailedVetDate,
failedHomeInspection : req.body.dqFailedHomeDate,
notes : req.body.dqNotes
}
},
{ upsert : true },
function(err, vol) {
if (err) {
console.log(err);
res.redirect('/vdb');
} else {
volunteerTableQuery(req, res);
}
});
});
//what's the RESTful way to do this I wonder? probably not exactly this.
//I suppose it's an edit of a particular property but I don't want to get and then set it
//but I might want to decrement it too
//maybe api/vol/:vid/noshows/inc or /dec ? in terms of idempotentcy I guess I really would want to read it, update it outside the api, and submit back the
//new correct value
app.post('/api/volunteers/:vid/noshows/inc',
verifyAuth,
function(req, res) {
var criteria = {_id : req.params.vid};
var updateOp = { '$inc' : { 'volunteerData.noShows' : 1}};
Volunteer.findOneAndUpdate(criteria, updateOp, function(err, r) {
if (err) console.log(err);
});
});
app.post('/api/volunteers/:vid/noshows/dec',
verifyAuth,
function(req, res) {
var criteria = {_id : req.params.vid};
var updateOp = { '$inc' : { 'volunteerData.noShows' : -1}};
Volunteer.findOneAndUpdate(criteria, updateOp, function(err, r) {
if (err) console.log(err);
});
});
app.delete('/api/volunteers/' ,
verifyAuth,
function (req, res) {
if (!req.query.id) {
Volunteer.find(function(err, vtrs) {
if (err) res.send(err);
res.json(vtrs);
});
}
//Also / first remove this volunteer from any schedules
Schedule.remove ({volunteerId : req.query.id}).exec();
Volunteer.remove(
{ _id : req.query.id },
function (err, r) {
volunteerTableQuery(req, res);
});
});
//////////////////
/// Animals API
function buildAnimalCriteria(req) {
var criteria = {}; //we're going to AND together a set of clauses
var critList = [];
if (typeof req.query.name != "undefined") {
critList.push({'name' : new RegExp(req.query.name, 'i')});
}
if (typeof req.query.breed != "undefined") {
critList.push({'breed' : new RegExp(req.query.breed, 'i')});
}
if (typeof req.query.status != "undefined") {
//we expect this to be a # 0 .. 4
var fields = ['Quarantined', 'Adoptable', 'Pending Adoption', 'Adopted', 'Deceased'];
var val = fields[req.query.status];
critList.push({'status' : new RegExp(val, 'i')});
}
if (typeof req.query.kind != "undefined") {
//we expect this to be the text
critList.push({'kind' : new RegExp(req.query.kind, 'i')});
}
if (typeof req.query.chip != "undefined") {
//we expect this to be the text
critList.push({'chipId' : new RegExp(req.query.chip, 'i')});
}
if (typeof req.query.person != "undefined") {
var n = new RegExp(req.query.person, 'i');
critList.push({'$or' : [{'transfers.origin': n}, {'transfers.dest': n}] });
}
if (critList.length > 0) {
criteria['$and'] = critList;
}
return criteria;
};
function animalTableQuery(req, res) {
//examine the query parameters for any other filters or criteria
var criteria = buildAnimalCriteria(req);
var options = buildPagination(req);
//return current list of animals
//plausibly we want to project here since this query drives a summary table
var projection = {
};
//count in this filter set
Animal.count(criteria, function(err, c) {
var pageCount = c / itemsPerPage;
Animal.find(criteria, projection, options).sort('name').exec(function(err, vtrs) {
if (err)
res.send(err);
else {
var paginateData = {pageCount : pageCount, data : vtrs};
res.json(paginateData);
}
});
});
};
app.get('/api/animals/',
verifyAuth,
function(req, res) {
if (req.query.id) {
Animal.findOne({ _id: req.query.id }, function (err, a) {
if (err)
res.send(err);
else
res.json(a);
});
} else {
animalTableQuery(req, res);
}
});
app.post('/api/animals/',
verifyAuth,
function(req, res) {
//if the body doesn't supply an ID we are inserting a new one
var oid = req.body._id;
if (!oid) {
oid = new mongoose.mongo.ObjectID();
}
//VALIDATION / defaulting
req.body.approxWeight = validateNumber(req.body.approxWeight, 0);
Animal.findOneAndUpdate(
{ _id : oid },
{
name : req.body.name,
kind : req.body.kind,
breed : req.body.breed,
secondaryBreed : req.body.secondaryBreed,
coloration : req.body.coloration,
size : req.body.size,
coat : req.body.coat,
approxWeight : req.body.approxWeight,
birthday : req.body.birthday,
birthdayApproximated : req.body.birthdayApproximated,
descriptionNotes : req.body.descriptionNotes,
sex : req.body.sex,
altered : req.body.altered,
alteredDate : req.body.alteredDate,
healthNotes : req.body.healthNotes,
microchipped : req.body.microchipped,
chippedDate : req.body.chippedDate,
chipId : req.body.chipId,
chipModel : req.body.chipModel,
housetrained : req.body.housetrained,
status : req.body.status,
fostered : req.body.fostered,
isDeclawed : req.body.isDeclawed,
fivlTested : req.body.fivlTested,
fivPositive : req.body.fivPositive,
flvPositive : req.body.flvPositive,
heartwormTested : req.body.heartwormTested,
heartwormPositive : req.body.heartwormPositive,
rabiesTag : req.body.rabiesTag,
pictures : req.body.pictures,
getsAlongWithCats : req.body.getsAlongWithCats,
getsAlongWithDogs : req.body.getsAlongWithDogs,
getsAlongWithKids : req.body.getsAlongWithKids,
litterNotes : req.body.litterNotes,
bondedWith : req.body.bondedWith,
transfers : req.body.transfers
},
{ upsert : true },
function(err, ani) {
if (err) {
res.send(err);
} else {
animalTableQuery(req, res);
}
});
});
app.delete('/api/animals/',
verifyAuth,
function(req, res) {
if (!req.query.id) {
Animal.find(function(err, animals) {
if (err) res.send(err);
res.json(animals);
});
}
Animal.remove(
{ _id : req.query.id },
function (err, r) {
animalTableQuery(req, res);
});
});
///////////////////////////
///// Schedule API
app.get('/api/schedule/:year/:month',
verifyAuth,
function (req, res) {
var criteria = {};
criteria['year'] = req.params.year;
criteria['month'] = req.params.month;
Schedule.find(criteria, function(err, scheduledItems) {
if (err) res.send(err);
res.json(scheduledItems);
});
});
//assume form data in body is either new event or edit of existing event
//should we also allow posting to api/schedule/2017/11/ ?
app.post('/api/schedule',
verifyAuth,
function (req, res) {
//check for upserts
var oid = req.body._id;
if (!oid) {
oid = new mongoose.mongo.ObjectID();
}
var validatedTeamSize = validateNumber(req.body.teamSize, 1);
var validatedTimeSlot = validateNumber(req.body.timeslot, 0);
var validatedAssignment = validateNumber(req.body.assignment, 0);
//if the form passes a date object, extract these values instead of the year/month/day set
var valYear = req.body.year;
var valMonth = req.body.month;
var valDate = req.body.day;
if (req.body.scheduledDate) {
valYear = req.body.scheduledDate.getFullYear();
valMonth = req.body.scheduledDate.getMonth();
valDate = req.body.scheduledDate.getDate();
}
Schedule.findOneAndUpdate(
{ _id : oid },
{
volunteerId : req.body.volunteerId,
year : valYear,
month : valMonth,
dayOfMonth : valDate,
timeslot : validatedTimeSlot, // 0, 1, 2 : Morning, Afternoon, Evening
assignment : validatedAssignment, //0 cats, 1 catsP, 2 dogs, 3 rab, 4 smalls
teamSize : validatedTeamSize, //how many people in the team (usually 1 but parent child or whatever counts as more)
notes : req.body.notes, //optional text to accompany event - like fixed arrival time if a Tuesday
arrivalTime : req.body.arrivalTime,
noShow : req.body.noShow
},
{ upsert : true },
function(err, sch) {
if (err) {
console.log(err);
res.redirect('/sch');
} else {
res.json(sch);
}
});
});
//delete an event by id
app.delete('/api/schedule',
verifyAuth,
function (req, res) {
if (!req.query.id) {
res.redirect('/sch');
}
Schedule.remove(
{ _id : req.query.id },
function (err, r) {
if (err) {
console.log(err);
}
res.json(r);
});
});
//strange misfit toy API route for doing a delete-all-forward call
app.delete('/api/scheduleBatch',
verifyAuth,
function(req, res) {
if (!req.query.id) {
res.redirect('/sch');
}
var volunteerId = req.query.id;
var deleteForwardFromDate = new Date(req.query.date);
var year = deleteForwardFromDate.getFullYear();
var month = deleteForwardFromDate.getMonth();
var day = deleteForwardFromDate.getDate();
//we want to delete things that happen after this time but we can't do multiplicative criteria
//so that's everything in the next year; or everything that is this year and next month, or everything that is this year and month and the next day
var clauses = [];
clauses.push({'year' : {'$gt' : year}}); //delete everything in following years
clauses.push({'$and' : [{'year' : year, 'month' : {'$gt' : month}}]}); //delete everything this year that happens at a later month
clauses.push({'$and' : [{'year' : year, 'month' : month, 'dayOfMonth' : {'$gte' : day}}]}); //delete everything this month that happens today or later.
Schedule.remove(
{
'volunteerId' : volunteerId,
'$or' : clauses
},
function (err, r) {
if (err) {
console.log(err);
}
res.json(r);
});
});
///////// Mongo Can't Join -- Joey doesn't share food ///////
app.post('/api/vsj',
verifyAuth,
function(req, res) {
var idList = req.body.ids;
if (idList) {
var oidList = idList.map(function(id) { return new mongoose.mongo.ObjectID(id)});
var criteria = {'_id' : { '$in' : oidList}};
//we don't want everything
var projection = { 'firstName' : 1, 'lastName' : 1, 'volunteerData.status' : 1 };
Volunteer.find(criteria, projection, function (err, results) {
if (err) {
console.log(err);
}
res.json(results);
});
}
});
//////////////////
//// Report API
app.get('/api/report/email',
verifyAuth,
function(req, res) {
var excludeMinors = req.query.excludeMinors;
var respectOptOut = req.query.respectOptOut;
var skipInactive = req.query.skipInactive;
var skipDisqualified = req.query.skipDisqualified;
var filterTraining = req.query.filterTraining;
var criteriaTraining = req.query.criteriaTraining;
var minorsBornAfter = new Date();
minorsBornAfter.setFullYear(minorsBornAfter.getFullYear() - 18);
var deDuplicate = req.query.deDuplicate;
var projection = {'email' : 1};
var criteria = {
'email' : {'$ne' : null},
};
if (excludeMinors != 'false') {
criteria['volunteerData.birthday'] = {'$lte' : minorsBornAfter};
}
if (respectOptOut != 'false') {
criteria['doNotEmail'] = {'$in' : [null, false]};
}
if (skipInactive != 'false') {
criteria['volunteerData.activeVolunteer'] = true;
}
if (skipDisqualified != 'false') {
criteria['disqualifyingData.surrenderedAnimal'] = null;
criteria['disqualifyingData.failedVetCheck'] = null;
criteria['disqualifyingData.failedHomeInspection'] = null;
criteria['disqualifyingData.notes'] = null;
}
if (filterTraining != 'false' && criteriaTraining) {
var fields = ['trainedCats', 'trainedCatsPetsmart', 'trainedDogs', 'trainedRabbit', 'trainedSmalls'];
var fname = 'volunteerData.status.' + fields[criteriaTraining-1];
criteria[fname] = {'$nin' : [null]};
}
Volunteer.find(criteria, projection, function (err, results) {
if (err) {
console.log(err);
}
//manual distinct since mongoose doesn't like to do projection + distincting
if (deDuplicate != 'false') {
results = Array.from(new Set(results.map(
function (s) {
return s.email;
}
)));
} else {
results = results.map(function(s) {return s.email;});
}
res.json(results);
});
});
app.get('/api/report/address',
verifyAuth,
function(req, res) {
var respectOptOut = req.query.respectOptOut;
var skipInactive = req.query.skipInactive;
var skipDisqualified = req.query.skipDisqualified;
var minorsBornAfter = new Date();
minorsBornAfter.setFullYear(minorsBornAfter.getFullYear() - 18);
var projection = {'firstName' : 1, 'lastName' : 1, 'address' : 1, 'city' : 1, 'state' : 1, 'zip' : 1};
var criteria = {
'firstName' : {'$ne' : null},
'lastName' : {'$ne' : null},
'address' : {'$ne' : null},
'city' : {'$ne' : null},
'state' : {'$ne' : null},
'zip' : {'$ne' : null},
'volunteerData.birthday' : {'$lte' : minorsBornAfter}
};
if (respectOptOut != 'false') {
criteria['doNotEmail'] = {'$in' : [null, false]};
}
if (skipInactive != 'false') {
criteria['volunteerData.activeVolunteer'] = true;
}
if (skipDisqualified != 'false') {
criteria['disqualifyingData.surrenderedAnimal'] = null;
criteria['disqualifyingData.failedVetCheck'] = null;
criteria['disqualifyingData.failedHomeInspection'] = null;
criteria['disqualifyingData.notes'] = null;
}
Volunteer.find(criteria, projection, function (err, results) {
if (err) {
console.log(err);
}
//manual distinct since mongoose doesn't like to do projection + distincting
//we can't do Set since we want a more complex duplicating check
var uniqueResults = [];
for (var i = 0; i < results.length; i++) {
var r = results[i];
var contained = false;
for (var j = 0; j < uniqueResults.length; j++) {
var u = uniqueResults[j];
if (u.address.trim() === r.address.trim()) {
if (u.zip.trim() === r.zip.trim()) {
contained = true;
break;
}
}
}
if (!contained) {
uniqueResults.push(r);
}
}
res.json(uniqueResults);
});
});
app.get('/api/report/emergencyContact',
verifyAuth,
function(req, res) {
var skipInactive = req.query.skipInactive;
var projection = {
'email' : 1,
'firstName' : 1,
'lastName' : 1,
'volunteerData.emergencyContactName' : 1,
'volunteerData.emergencyContactNumber' : 1
};
var criteria = {
'$or' : [{'volunteerData.emergencyContactName' : null}, {'volunteerData.emergencyContactNumber' : null}]
};
if (skipInactive != 'false') {
criteria['volunteerData.activeVolunteer'] = true;
}
Volunteer.find(criteria, projection, function (err, results) {
if (err) {
console.log(err);
}
res.json(results);
});
});
//////////////////////////////////////////
////// Views / pages