-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmake-api.js
More file actions
554 lines (475 loc) · 21 KB
/
make-api.js
File metadata and controls
554 lines (475 loc) · 21 KB
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
/* jshint node: true */
/* jshint esversion:6 */
/*
This file generates a JSON structure that can be served
with https://github.com/typicode/json-server to serve up a fake API
for the CSSP prototype.
Make sure you have json-server installed (npm install -g json server)
and that you also have installed further dependencies (by running 'npm install' in the project root)
*/
// Run `npm install in the project root to install these dependencies`
const faker = require('faker');
const moment = require('moment');
const fs = require('fs');
const _ = require('lodash');
const api = {};
api.employees = [];
api.spouses = [];
api.children = [];
api.applications = [];
api.documents = [];
api.awards = [];
api.tccTuition = {
'default': {
'infant': {
'twoDay': 1381,
'threeDay': 1934,
'fiveDay': 2760
},
'toddler': {
'twoDay': 1160,
'threeDay': 1617,
'fiveDay': 2313
},
'preschool': {
'twoDay': 979,
'threeDay': 1368,
'fiveDay': 1958
}
},
'westgate': {
'preschool': {
'fiveDayMornings': 798,
'fiveDay': 1595
}
},
'linc': {
'infant': {
'twoDay': 1221,
'threeDay': 1765,
'fiveDay': 2524
},
'toddler': {
'twoDay': 1092,
'threeDay': 1584,
'fiveDay': 2262
},
'preschool': {
'twoDay': 921,
'threeDay': 1353,
'fiveDay': 1929
}
}
};
const mitId = function() {
return faker.random.number({ min: 1000000000, max: 9999999999 });
};
const schools = ['College of the Holy Cross','University of California\, Davis','United States Coast Guard Academy','California Institute of Technology','Washington University in Saint Louis','Wheaton College','University of Texas\, Austin','Boston University','University of Pennsylvania','Trinity College','Northwestern University','Williams College','Santa Clara University','University of Southern California','University of California\, Berkeley','Case Western Reserve University','University of Maryland\, College Park','Harvard University','Southern Methodist University','University of Rochester','Davidson College','University of North Carolina\, Chapel Hill','Vassar College','Boston College','Sewanee—University of the South','Stanford University','Union College','University of California\, Los Angeles','Columbia University','Carleton College','Reed College','Kenyon College','University of Illinois\, Urbana-Champaign','Brandeis University','Tufts University','Rice University','Colgate University','Pepperdine University','University of California\, Santa Barbara','United States Air Force Academy','University of Washington','Villanova University','United States Naval Academy','Pennsylvania State University\, University Park','Washington and Lee University','Dartmouth College','Wellesley College','Oberlin College','George Washington University','Hamilton College','University of Michigan\, Ann Arbor','Grinnell College','Lehigh University','Duke University','United States Military Academy','Mount Holyoke College','University of Chicago','Princeton University','Wesleyan University','Georgetown University','University of Richmond','Bryn Mawr College','Lafayette College','Brown University','Vanderbilt University','Scripps College','DePauw University','Whitman College','Georgia Institute of Technology','Smith College','University of Notre Dame','Middlebury College','Harvey Mudd College','Amherst College','Barnard College','Virginia Military Institute','Yale University','New York University','Wake Forest University','Bowdoin College','University of Virginia','Johns Hopkins University','Haverford College','College of William and Mary','Swarthmore College','Cooper Union','University of Wisconsin\, Madison','Colby College','Cornell University','Brigham Young University','Carnegie Mellon University','Pomona College','Colorado College','University of Florida','Indiana University\, Bloomington','Centre College','Franklin and Marshall College','Macalester College','University of Georgia','Massachusetts Institute of Technology'];
// Employee Constructor
const Employee = (index) => {
for (let id = 0; id < 50; id++) {
const employee = {};
employee.id = index; // for API route use - employees/:id
employee.firstName = faker.name.firstName();
employee.middleInitial = faker.random.boolean() ?
faker.name.firstName().substr(0,1) :
null;
employee.lastName = faker.name.lastName();
employee.maritalStatus = faker.random.arrayElement(['married','partnership','divorced','singleOrWidowed']);
if (employee.maritalStatus === 'married') {
employee.spouseMaritalTitle = 'spouse';
} else if (employee.maritalStatus === 'partnership') {
employee.spouseMaritalTitle = 'partner';
} else if (employee.maritalStatus === 'divorced') {
employee.spouseMaritalTitle = 'ex-spouse';
}
employee.email = employee.firstName.substr(0,1).toLowerCase() +
'.' +
employee.lastName.toLowerCase() +
'@' +
faker.internet.domainName();
employee.appointmentStartDate = faker.date.between(
moment().subtract(8,'weeks'),
moment().subtract(15,'years')
);
employee.appointmentEndDate = faker.date.between(
moment().add(8, 'weeks'),
moment().add(3, 'years')
);
employee.phone = faker.phone.phoneNumberFormat();
employee.isPrimaryContact = true; //spouse might override
employee.salary = faker.random.number({min: 30000, max: 120000});
employee.salaryHistory = [];
employee.additionalIncome = faker.random.boolean() ? faker.random.number({min: 0, max: 20000}) : null;
employee.affiliation = faker.random.arrayElement(['faculty','staff','student','postdoc associate','postdoc fellow']);
employee.mitId = mitId();
employee.childIds = [];
// funding source: employee, fellow, combined
employee.fundingSource = faker.random.arrayElement(['Employee', 'Fellow', 'Combined']); // Determines which funds get used and which admin applications get sent to
if (employee.fundingSource === 'Combined') {
employee.fundingSourceEmployeePercentage = faker.random.arrayElement([60,70,80]);
employee.fundingSourceFellowPercentage = 100 - employee.fundingSourceEmployeePercentage;
}
employee.applicationIds = [];
return employee;
}
};
// Spouse Constructor
const Spouse = (employee) => {
const spouse = {};
spouse.id = api.spouses.length;
spouse.firstName = faker.name.firstName();
spouse.middleInitial = faker.random.boolean() ?
faker.name.firstName().substr(0,1) :
null;
spouse.lastName = faker.name.lastName();
spouse.email = spouse.firstName.substr(0,1).toLowerCase() +
'.' +
spouse.lastName.toLowerCase() +
'@' +
faker.internet.domainName();
spouse.phone = faker.phone.phoneNumberFormat();
// Lets say 80% of spouses are employed
spouse.occupation = (Math.random() < 0.2) ?
'employed' :
faker.random.arrayElement([
'student',
'self-employed',
'disabled',
'other'
]);
switch(spouse.occupation) {
// EMPLOYED
case 'employed':
spouse.employer = faker.company.companyName();
spouse.appointmentStartDate = faker.date.between(
moment().subtract(8,'weeks'),
moment().subtract(15,'years')
);
if ( Math.random() < 0.2 ) {
spouse.appointmentEndDate = faker.date.between(
moment().add(8, 'weeks'),
moment().add(3, 'years')
);
}
spouse.isEmployedOverMinimum = (Math.random() < 0.2) ? false : true;
spouse.spousePaymentSchedule = faker.random.arrayElement(['monthly','semi-monthly','bi-weekly','weekly','per diem','irregularly']);
break;
// STUDENT
case 'student':
spouse.school = faker.random.arrayElement(schools);
function generateSchoolAdmissionDate() {
const year = faker.random.arrayElement(2015,2016,2017,2018);
return moment().set({'year': year,'month':8,'date':1}).valueOf();
}
spouse.schoolAdmissionDate = generateSchoolAdmissionDate();
spouse.schoolExpectedGraduationDate =
moment(spouse.schoolAdmissionDate).add(4,'years').valueOf();
spouse.schoolFundingType = faker.random.arrayElement(['teaching assistant','research assistant','stipend','N/A']);
break;
// SELF EMPLOYED
case 'self-employed':
spouse.selfEmploymentCompanyName = faker.company.companyName();
spouse.selfEmploymentStartDate = faker.date.between(
moment().subtract(8,'weeks'),
moment().subtract(15,'years')
);
spouse.selfEmploymentPaymentSchedule = faker.random.arrayElement(['monthly','semi-monthly','bi-weekly','weekly','per diem','irregularly']);
if (spouse.selfEmploymentPaymentSchedule === 'per diem' || spouse.selfEmploymentPaymentSchedule === 'irregularly') {
spouse.selfEmploymentPaymentScheduleReason = 'I have my reasons';
}
break;
case 'disabled':
spouse.disabledCertification = "certification.pdf";
break;
case 'other':
spouse.otherEmployeeNote = 'My partner has been seeking employment, but is currently unemployed.';
spouse.otherAttachedFile = faker.random.boolean() ? 'attachedfile.pdf' : null;
break;
}
spouse.salary = faker.random.number({min: 15000, max: 45000});
spouse.additionalIncome = faker.random.boolean() ? faker.random.number({min: 0, max: 10000}) : null;
// return an MIT ID ~20% of times when employed
spouse.mitId = (Math.random() < 0.2 && spouse.occupation === 'employed') ?
mitId() :
null;
spouse.employeeId = employee.id;
return spouse;
};
function Child(employee, tccCenter) {
var child = {};
child.id = api.children.length;
child.firstName = faker.name.firstName();
child.lastName = employee.lastName;
child.tccCenter = tccCenter;
child.classRoom = faker.random.arrayElement(['Infant', 'Toddler', 'Preschool']);
child.daysPerWeek = faker.random.arrayElement([2,3,5]);
child.employeeId = employee.id;
if (tccCenter.toLowerCase() === 'westgate') {
child.schedule = faker.random.arrayElement(['full-time', 'half-time']);
child.classRoom = 'Preschool';
child.daysPerWeek = 5;
}
switch(child.classRoom.toLowerCase()) {
case 'infant':
child.dateOfBirth = faker.date.between(
moment().subtract(8,'weeks'),
moment().subtract(14,'months')
);
break;
case 'toddler':
child.dateOfBirth = faker.date.between(
moment().subtract(14,'months').subtract(1, 'day'),
moment().subtract(2.8,'years')
);
break;
case 'preschool':
child.dateOfBirth = faker.date.between(
moment().subtract(2.8,'years').subtract(1, 'day'),
moment().subtract(6,'years')
);
break;
default:
console.log('No valid classroom has been selected. The value must match \'infant\',\'toddler\', or \'preschool\'');
}
if (child.tccCenter.toLowerCase() === 'westgate') {
if (child.schedule.toLowerCase() === 'half-time') {
child.monthlyTuition = api.tccTuition.westgate.preschool.fiveDayMornings;
} else {
child.monthlyTuition = api.tccTuition.westgate.preschool.fiveDay;
}
} else if (child.tccCenter.toLowerCase() === 'linc') {
if (child.classRoom.toLowerCase() === 'infant') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.linc.infant.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.linc.infant.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.linc.infant.fiveDay;
}
}
if (child.classRoom.toLowerCase() === 'toddler') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.linc.toddler.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.linc.toddler.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.linc.toddler.fiveDay;
}
}
if (child.classRoom.toLowerCase() === 'preschool') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.linc.preschool.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.linc.preschool.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.linc.preschool.fiveDay;
}
}
} else {
// default: stata, eastgate, koch
if (child.classRoom.toLowerCase() === 'infant') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.default.infant.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.default.infant.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.default.infant.fiveDay;
}
}
if (child.classRoom.toLowerCase() === 'toddler') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.default.toddler.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.default.toddler.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.default.toddler.fiveDay;
}
}
if (child.classRoom.toLowerCase() === 'preschool') {
if (child.daysPerWeek === 2) {
child.monthlyTuition = api.tccTuition.default.preschool.twoDay;
}
if (child.daysPerWeek === 3) {
child.monthlyTuition = api.tccTuition.default.preschool.threeDay;
}
if (child.daysPerWeek === 5) {
child.monthlyTuition = api.tccTuition.default.preschool.fiveDay;
}
}
}
return child;
}
// @TODO remove
var generateSecondAwardTest = true;
/* APPLICATION CONSTRUCTOR */
const Application = (employee, spouse) => {
const application = {};
application.id = api.applications.length;
// @TODO Since the application can be returned and resubmitted, does it make sense to store this in an array on this property? Should research best practices
application.lastSubmissionDate = faker.date.between('2018-08-01','2018-09-15');
application.submissionDates = [].concat([application.lastSubmissionDate]);
application.academicYear = (Math.random() > 0.2) ?
'2018-19' :
'2017-18'; //How would you store AY in an API? academicYearStart and academicYearEnd with two udate objects maybe?
application.statusCode = faker.random.number({ min: 0, max: 5 });
application.statusMessage = ['Pending Approval','Approved','Returned','Denied','Confirmed','Declined'][application.statusCode]; // Corresponds to statusCode
application.employeeId = employee.id;
application.comments = [
{
message : 'Employee has provided corrected documents. Proceeding to approve.',
author : 'Kate Goldstein',
timestamp: '2018-08-17T09:55:00.553Z',
type: 'internal'
},{
message : 'Apologies, I accidentally uploaded the wrong files, everything should be okay now.',
author : employee.lastName + ' ' + employee.firstName + (employee.middleInitial ? ', ' : '') + (employee.middleInitial || ''),
timestamp: '2018-08-16T14:20:00.553Z',
type: 'external'
},{
message : 'Hi, in order to for us to proceed with your application, please supply versions of your financial documentation translated into English.',
author : 'Kate Goldstein',
timestamp: '2018-08-14T10:11:15.553Z',
type: 'external'
}
];
if (typeof spouse === 'undefined') {
var spouse = {};
spouse.salary = 0;
spouse.additionalIncome = 0;
}
application.totalIncome = employee.salary + employee.additionalIncome + spouse.salary + spouse.additionalIncome;
application.hasSalaryChanged = application.statusCode === 4 && Math.random() < 0.3 ? true : false;
if (application.hasSalaryChanged) {
employee.salaryHistory.push(
{
amount: employee.salary + 3386,
startDate: moment().add(1, 'month').add(2, 'days')
},{
amount: employee.salary,
endDate: moment().add(1, 'month').subtract(1, 'day'),
startDate: moment().subtract(4, 'years').subtract(1 , 'months').subtract(9, 'days')
}
);
}
application.awards = [];
// Generate award if application.statusCode demands it
// if (application.statusCode === 1 || application.statusCode === 4) {
api.awards.push(Award(employee, application, false));
// Add award ID to the application.awards array
application.awards.push(api.awards.length - 1);
// @TODO remove
if (generateSecondAwardTest && application.statusCode === 4) {
api.awards.push(Award(employee, application, true));
// Add award ID to the application.awards array
application.awards.push(api.awards.length - 1);
generateSecondAwardTest = false;
}
// }
// application.financialDocumentation = [];
//
// if (employee.spouseId) {
// application.financialDocumentation.spouseTaxForm
// }
return application;
};
/* AWARD CONSTRUCTOR */
const Award = (employee, application, isSecondAward) => {
const award = {};
award.id = api.awards.length;
award.applicationId = application.id;
award.startDate = faker.date.between(application.lastSubmissionDate, moment(application.lastSubmissionDate).add(1,'months'));
award.endDate = '2019-08-31T23:59:59.244Z';
award.amount = faker.random.number({'min': 500, 'max': 2500});
award.status = isSecondAward ? 'archived' : 'active';
return award;
};
const removeKeysWithEmptyProperties = (obj) => {
Object.keys(obj).forEach(key => {
// Add recursion for nested objects
if (obj[key] && typeof obj[key] === 'object') removeKeysWithEmptyProperties(obj[key]);
else if (obj[key] == null) delete obj[key];
});
};
const writeObjectToJsonFile = (obj, jsonFileName) => {
var objJson = JSON.stringify(obj);
fs.writeFile(jsonFileName + '.json', objJson, 'utf-8', function(err) {
if (err) {
console.log('An error occured while writing JSON object to file. 🤬 💩 ');
return console.log(err);
}
console.log(jsonFileName + '.json has been saved... 👍');
});
};
/*** MAIN ROUTINE ***/
(() => {
// Generate n employees
_.times(200, function(index){
api.employees.push(Employee(index));
});
// Now that we have the api.employees, populate api.spouses and api.children with realistic variability (possibility, not probability) so prototype will reveal the possible scenarios.
api.employees.forEach(function(employee, index) {
// SPOUSE
if (employee.maritalStatus !== 'singleOrWidowed') {
api.spouses.push(Spouse(employee));
// Create an ID reference on the employee to the spouse
employee.spouseId = api.spouses.length - 1;
// Determine who is primary contact
employee.isPrimaryContact = faker.random.boolean();
}
// CHILDREN
// One to four little paycheck annihilators...
// Fewer children much more likely
const randomNumber = Math.random();
let numberOfChildren;
if (randomNumber < 0.5) {
numberOfChildren = 1;
} else if (randomNumber < 0.85) {
numberOfChildren = 2;
} else if (randomNumber < 0.95) {
numberOfChildren = 3;
} else {
numberOfChildren = 4;
}
// ...going to the same TCC. (Technically possible it's different, realistically it's unlikely. Also not important for the prototype?)
const tccCenter = faker.random.arrayElement(['Eastgate','Westgate','Koch','Stata','Linc']);
_.times(numberOfChildren, () => {
api.children.push(Child(employee,tccCenter));
//Create array of ChildId references on the employee
employee.childIds.push(api.children.length - 1);
});
});
// Add n applications to random employees
_.times(100, (index) => {
const randomEmployeesArrayIndex = faker.random.number({ min: 0, max: api.employees.length - 1});
const employee = api.employees[randomEmployeesArrayIndex];
const spouse = api.spouses[employee.spouseId];
api.applications.push(Application(employee, spouse));
// Create an ID array element on the employee referencing the application
employee.applicationIds.push(index);
});
// Order applications
// api.applications = _.sortBy(api.applications, function(application) {
// return new Date(application.lastSubmissionDate);
// });
// add ordinal orderIndex property for pending Approval applications
(function(){
let index = 0;
api.applications.forEach(function(application){
if (application.statusCode === 0)
application.orderIndex = index++;
});
}());
removeKeysWithEmptyProperties(api);
writeObjectToJsonFile(api,'api');
})();