-
Notifications
You must be signed in to change notification settings - Fork 21
/
index.js
executable file
·1726 lines (1574 loc) · 63.1 KB
/
index.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
/* eslint-disable no-use-before-define */
/* eslint-disable no-await-in-loop */
/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
let v4;
try {
// eslint-disable-next-line global-require
const crypto = require('crypto');
v4 = crypto.randomUUID;
if (!v4) {
// node v12 doesnt have randomUUID
throw new Error();
}
} catch (err) {
console.log('Node lacks crypto support!');
// eslint-disable-next-line global-require
({ v4 } = require('uuid'));
}
const moment = require('moment');
const knex = require('./connection');
const { TABLES } = require('./constants');
const emailConstants = require('../lib/email/constants');
const { fundingActivityCategoriesByCode } = require('../lib/fieldConfigs/fundingActivityCategories');
const helpers = require('./helpers');
async function getUsers(tenantId) {
const users = await knex('users')
.select(
'users.*',
'roles.name as role_name',
'roles.rules as role_rules',
'agencies.name as agency_name',
'agencies.abbreviation as agency_abbreviation',
'agencies.parent as agency_parent_id_id',
)
.leftJoin('roles', 'roles.id', 'users.role_id')
.leftJoin('agencies', 'agencies.id', 'users.agency_id')
.where('users.tenant_id', tenantId);
return users.map((user) => {
const u = { ...user };
if (user.role_id) {
u.role = {
id: user.role_id,
name: user.role_name,
rules: user.role_rules,
};
}
if (user.agency_id !== null) {
u.agency = {
id: user.agency_id,
name: user.agency_name,
abbreviation: user.agency_abbreviation,
agency_parent_id: user.agency_parent_id,
};
}
return u;
});
}
async function deleteUser(id) {
await knex('email_subscriptions').where('user_id', id).del();
return knex('users')
.where('id', id)
.del();
}
async function createUser(user) {
const response = await knex
.insert(user)
.into('users')
.returning(['id', 'created_at']);
const emailUnsubscribePreference = Object.assign(
...Object.values(emailConstants.notificationType).map(
(k) => ({ [k]: emailConstants.emailSubscriptionStatus.subscribed }),
),
);
await setUserEmailSubscriptionPreference(response[0].id, user.agency_id, emailUnsubscribePreference);
return {
...user,
id: response[0].id,
created_at: response[0].created_at,
};
}
async function updateUser(user) {
const { id, name, avatar_color } = user;
await knex('users')
.where('id', id)
.update({ name, avatar_color });
return getUser(id);
}
async function getUsersByAgency(agencyId) {
const users = await knex('users').where('users.agency_id', agencyId);
return users;
}
async function getSubscribersForNotification(agencyId, notificationType) {
const subscribers = await knex('users')
.select(
'users.id',
'users.email',
'email_subscriptions.status',
)
.leftJoin('email_subscriptions', function () {
this
.on('users.id', '=', 'email_subscriptions.user_id')
.andOn('users.agency_id', '=', 'email_subscriptions.agency_id')
.andOn('email_subscriptions.notification_type', '=', knex.raw('?', [notificationType]));
})
.where('users.agency_id', agencyId);
return subscribers.filter((s) => s.status !== emailConstants.emailSubscriptionStatus.unsubscribed);
}
async function getUsersEmailAndName(ids) {
return knex.select('id', 'name', 'email').from('users').whereIn('id', ids);
}
async function getUser(id) {
const [user] = await knex('users')
.select(
'users.id',
'users.email',
'users.name',
'users.role_id',
'users.avatar_color',
'roles.name as role_name',
'roles.rules as role_rules',
'users.agency_id',
'agencies.name as agency_name',
'agencies.abbreviation as agency_abbreviation',
'agencies.parent as agency_parent_id_id',
'agencies.warning_threshold as agency_warning_threshold',
'agencies.danger_threshold as agency_danger_threshold',
'tenants.id as tenant_id',
'tenants.display_name as tenant_display_name',
'tenants.main_agency_id as tenant_main_agency_id',
'users.tags',
'users.tenant_id',
)
.leftJoin('roles', 'roles.id', 'users.role_id')
.leftJoin('agencies', 'agencies.id', 'users.agency_id')
.leftJoin('tenants', 'tenants.id', 'users.tenant_id')
.where('users.id', id);
if (!user) return null;
if (user.role_id != null) {
user.role = {
id: user.role_id,
name: user.role_name,
rules: user.role_rules,
};
}
if (user.agency_id != null) {
user.agency = {
id: user.agency_id,
name: user.agency_name,
abbreviation: user.agency_abbreviation,
agency_parent_id: user.agency_parent_id,
warning_threshold: user.agency_warning_threshold,
danger_threshold: user.agency_danger_threshold,
main_agency_id: user.agency_main_agency_id,
};
user.tenant = {
id: user.tenant_id,
display_name: user.tenant_display_name,
main_agency_id: user.tenant_main_agency_id,
};
let subagencies = [];
if (user.role.name === 'admin') {
subagencies = await getAgencyTree(user.agency_id);
} else {
subagencies.push({ ...user.agency });
}
user.agency.subagencies = subagencies;
}
user.emailPreferences = await getUserEmailSubscriptionPreference(user.id, user.agency_id);
return user;
}
async function getUserIdForEmail(email) {
const [user] = await knex('users')
.select('users.id')
.where('email', email);
return user ? user.id : null;
}
async function getAgencyCriteriaForAgency(agencyId) {
const eligibilityCodes = await getAgencyEligibilityCodes(agencyId);
const enabledECodes = eligibilityCodes.filter((e) => e.enabled);
const keywords = await getAgencyKeywords(agencyId);
return {
eligibilityCodes: enabledECodes.map((c) => c.code),
includeKeywords: keywords.reduce((filtered, c) => {
if (!c.type || c.type === 'include') {
filtered.push(c.search_term);
}
return filtered;
}, []),
excludeKeywords: keywords.reduce((filtered, c) => {
if (c.type === 'exclude') {
filtered.push(c.search_term);
}
return filtered;
}, []),
};
}
/* isSubOrganization(parent, candidateChild) returns true if
candidateChild is a child of parent.
Normally parent will be the agency_id of the logged in user, and
candidateChild will be the agency_id in the request header.
*/
async function isSubOrganization(parent, candidateChild) {
const query = `
with recursive hierarchy as (
select id, parent from agencies
where id = ?
union all
select agencies.id, agencies.parent from agencies
inner join hierarchy
on agencies.id = hierarchy.parent
)
select id from hierarchy;
`;
const result = await knex.raw(query, candidateChild);
// console.dir(result.rows.map((rec) => rec.id));
return result.rows.map((rec) => rec.id).indexOf(parent) !== -1;
}
function getRoles() {
return knex('roles')
.select('*')
.orderBy('name');
}
async function getAccessToken(passcode) {
const result = await knex('access_tokens')
.select('*')
.where('passcode', passcode);
return result[0];
}
async function incrementAccessTokenUses(passcode) {
const result = await knex('access_tokens')
.update({ uses: knex.raw('uses + 1') })
.where('passcode', passcode)
.then(() => knex('access_tokens')
.select('uses')
.where('passcode', passcode));
return result[0].uses;
}
function markAccessTokenUsed(passcode) {
return knex('access_tokens')
.where('passcode', passcode)
.update({ used: true });
}
async function generatePasscode(email) {
console.log('generatePasscode for :', email);
const users = await knex('users')
.select('*')
.where('email', email);
if (users.length === 0) {
throw new Error(`User '${email}' not found`);
}
const passcode = v4();
const used = false;
const expiryMinutes = 30;
const expires = new Date();
expires.setMinutes(expires.getMinutes() + expiryMinutes);
await knex('access_tokens').insert({
user_id: users[0].id,
passcode,
expires,
used,
});
return passcode;
}
function createAccessToken(email) {
return generatePasscode(email);
}
function getEligibilityCodes() {
return knex(TABLES.eligibility_codes)
.select('*');
}
function setAgencyEligibilityCodeEnabled(code, agencyId, enabled) {
return knex(TABLES.agency_eligibility_codes)
.insert({
agency_id: agencyId,
code,
enabled,
updated_at: new Date(),
})
.onConflict(['agency_id', 'code'])
.merge();
}
async function getKeyword(keywordId) {
const response = await knex(TABLES.keywords)
.select('*')
.where('id', keywordId);
return response[0];
}
function getKeywords() {
return knex(TABLES.keywords)
.select('*');
}
async function createKeyword(keyword) {
const response = await knex
.insert(keyword)
.into(TABLES.keywords)
.returning(['id', 'created_at']);
return {
...keyword,
id: response[0].id,
created_at: response[0].created_at,
};
}
function deleteKeyword(id) {
return knex(TABLES.keywords)
.where('id', id)
.del();
}
async function getNewGrantsForAgency(agency) {
const agencyCriteria = await getAgencyCriteriaForAgency(agency.id);
const rows = await knex(TABLES.grants)
.select(knex.raw(`${TABLES.grants}.*, count(*) OVER() AS total_grants`))
.modify(helpers.whereAgencyCriteriaMatch, agencyCriteria)
.modify((qb) => {
qb.where({ open_date: moment().subtract(1, 'day').format('YYYY-MM-DD') });
})
.limit(3);
return rows;
}
async function buildOrderingParams(args) {
// default order by the most recently opened grant
const orderingParams = { orderBy: 'open_date', orderDesc: 'true' };
if (args) {
if (args.orderBy) {
const orderArgs = args.orderBy.split('|');
if (orderArgs.length !== 1) {
throw new Error('The number of orderBy arguments must be 1');
} else if (!/^(rank|award_ceiling|open_date|close_date)$/.test(orderArgs[0])) {
console.error('Wat', orderArgs[0]);
throw new Error('orderBy must be one of rank|award_ceiling|open_date|close_date');
}
}
// we treat undefined order direction as descending === true
const orderDesc = args.orderDesc || 'true';
if (!/^(true|false)$/.test(orderDesc)) {
throw new Error('orderDesc must be true or false');
}
orderingParams.orderBy = args.orderBy;
orderingParams.orderDesc = args.orderDesc;
}
return orderingParams;
}
async function buildPaginationParams(args) {
const { currentPage, perPage } = args;
let { isLengthAware } = args;
if (!currentPage || currentPage < 1) {
throw Error('Invalid page');
}
if (!perPage || perPage < 1) {
throw Error('Invalid per page');
}
if (isLengthAware === undefined || isLengthAware === null) {
isLengthAware = true;
}
return { currentPage, perPage, isLengthAware };
}
function isValidArray(value) {
return Array.isArray(value) && value.length > 0;
}
function buildTsqExpression(includeKeywords, excludeKeywords) {
if (!isValidArray(includeKeywords) && !isValidArray(excludeKeywords)) {
return null;
}
const signedKeywords = { include: [], exclude: [] };
// wrap phrases in double quotes and ensure keywords have the correct operator
if (isValidArray(includeKeywords)) {
includeKeywords.forEach((ik) => { if (ik.indexOf(' ') > 0) { signedKeywords.include.push(`"${ik}"`); } else { signedKeywords.include.push(ik); } });
}
if (isValidArray(excludeKeywords)) {
excludeKeywords.forEach((ek) => { if (ek.indexOf(' ') > 0) { signedKeywords.exclude.push(`-"${ek}"`); } else { signedKeywords.exclude.push(`-${ek}`); } });
}
const includeExpression = signedKeywords.include.join(' or ');
const excludeExpression = signedKeywords.exclude.join(' ');
return { includeExpression, excludeExpression };
}
function buildKeywordQuery(queryBuilder, includeKeywords, excludeKeywords, orderingParams) {
const expression = buildTsqExpression(includeKeywords, excludeKeywords);
const includeExpression = expression?.includeExpression;
const excludeExpression = expression?.excludeExpression;
if (!includeExpression && !excludeExpression) {
return false;
}
if (includeExpression) {
queryBuilder.joinRaw(`cross join websearch_to_tsquery('english', ?) as tsqp`, includeExpression);
}
if (excludeExpression) {
queryBuilder.joinRaw(`cross join websearch_to_tsquery('english', ?) as ntsqp`, excludeExpression);
}
if (includeExpression) {
queryBuilder.andWhere((q) => {
q.where('tsqp', '@@', knex.raw('title_ts'))
.orWhere('tsqp', '@@', knex.raw('description_ts'));
return q;
});
}
if (excludeExpression) {
queryBuilder.andWhere((q) => {
q.where('ntsqp', '@@', knex.raw('title_ts'))
.andWhere('ntsqp', '@@', knex.raw('description_ts'));
});
}
if (includeExpression && orderingParams.orderBy !== undefined) {
queryBuilder.select(
knex.raw(`ts_rank(title_ts, tsqp) as rank_title`),
knex.raw(`ts_rank(grants.description_ts, tsqp) as rank_description`),
);
queryBuilder.groupBy('rank_title', 'rank_description');
}
return Boolean(includeExpression);
}
function matchAsWordRegex(word) {
return `\\m${word}\\M`;
}
function buildFiltersQuery(queryBuilder, filters, agencyId) {
const statusMap = {
Applied: 'Result',
'Not Applying': 'Rejected',
Interested: 'Interested',
};
queryBuilder.andWhere(
(qb) => {
if (filters.eligibilityCodes?.length) {
qb.where('eligibility_codes', '~', filters.eligibilityCodes.join('|'));
}
if (filters.opportunityNumber) {
qb.where(`${TABLES.grants}.grant_number`, '=', filters.opportunityNumber);
}
if (filters.fundingTypes?.length) {
qb.where('funding_instrument_codes', '~', filters.fundingTypes.join('|'));
}
if (filters.reviewStatuses?.length) {
const statuses = filters.reviewStatuses.map((status) => statusMap[status]);
qb.whereIn(`${TABLES.interested_codes}.status_code`, statuses);
qb.where(`${TABLES.grants_interested}.agency_id`, '=', agencyId);
}
if (parseInt(filters.assignedToAgencyId, 10) >= 0) {
qb.where(`${TABLES.assigned_grants_agency}.agency_id`, '=', filters.assignedToAgencyId);
}
if (parseInt(filters.followedByAgencyId, 10) >= 0) {
qb.where(`${TABLES.agencies}.id`, '=', filters.followedByAgencyId);
}
if (filters.opportunityCategories?.length) {
qb.whereIn(`${TABLES.grants}.opportunity_category`, filters.opportunityCategories);
}
if (filters.costSharing) {
qb.where(`${TABLES.grants}.cost_sharing`, '=', filters.costSharing);
}
if (filters.agencyCode) {
qb.where(`${TABLES.grants}.agency_code`, '~*', filters.agencyCode);
}
if (filters.bill) {
qb.where(`${TABLES.grants}.bill`, '~*', filters.bill);
}
if (filters.openDate) {
qb.where(`${TABLES.grants}.open_date`, '=', filters.openDate);
} else if (filters.postedWithinDays > 0) {
const date = moment().subtract(filters.postedWithinDays, 'days').startOf('day').format('YYYY-MM-DD');
qb.where(`${TABLES.grants}.open_date`, '>=', date);
}
if (filters.fundingActivityCategories?.length) {
qb.where('funding_activity_category_codes', '~*',
filters.fundingActivityCategories.map(matchAsWordRegex).join('|'));
}
},
);
}
function grantsQuery(queryBuilder, filters, agencyId, orderingParams, paginationParams) {
let hasRankColumns = false;
if (filters) {
if (filters.reviewStatuses?.length) {
queryBuilder.join(TABLES.grants_interested, `${TABLES.grants}.grant_id`, `${TABLES.grants_interested}.grant_id`)
.join(TABLES.interested_codes, `${TABLES.interested_codes}.id`, `${TABLES.grants_interested}.interested_code_id`);
}
if (parseInt(filters.assignedToAgencyId, 10) >= 0) {
queryBuilder.join(TABLES.assigned_grants_agency, `${TABLES.grants}.grant_id`, `${TABLES.assigned_grants_agency}.grant_id`);
}
if (parseInt(filters.followedByAgencyId, 10) >= 0) {
queryBuilder.join(TABLES.grant_followers, `${TABLES.grants}.grant_id`, `${TABLES.grant_followers}.grant_id`)
.join(TABLES.users, `${TABLES.grant_followers}.user_id`, `${TABLES.users}.id`)
.join(TABLES.agencies, `${TABLES.users}.agency_id`, `${TABLES.agencies}.id`);
}
hasRankColumns = buildKeywordQuery(queryBuilder, filters.includeKeywords, filters.excludeKeywords, orderingParams);
buildFiltersQuery(queryBuilder, filters, agencyId);
}
if (orderingParams.orderBy && orderingParams.orderBy !== 'undefined') {
// we assume orderingParams is a valid construction of buildOrderingParams
if (orderingParams.orderBy.includes('rank')) {
if (hasRankColumns) {
queryBuilder.orderBy([
{ column: 'rank_title', order: 'desc' },
{ column: 'rank_description', order: 'desc' },
]);
}
} else {
const orderDirection = ((orderingParams.orderDesc === 'true') ? 'desc' : 'asc');
queryBuilder.orderBy(orderingParams.orderBy, knex.raw(`${orderDirection} NULLS LAST`));
}
}
if (filters.opportunityStatuses?.length) {
queryBuilder.havingRaw(`
CASE
WHEN grants.archive_date <= now() THEN 'archived'
WHEN grants.close_date <= now() THEN 'closed'
ELSE 'posted'
END IN (${Array(filters.opportunityStatuses.length).fill('?').join(',')})`, filters.opportunityStatuses);
}
if (paginationParams) {
queryBuilder.limit(paginationParams.perPage);
queryBuilder.offset((paginationParams.currentPage - 1) * paginationParams.perPage);
}
}
// Convert saved search criteria to db query filters
function formatSearchCriteriaToQueryFilters(criteria) {
const parsedCriteria = JSON.parse(criteria);
const postedWithinOptions = {
'All Time': 0, 'One Week': 7, '30 Days': 30, '60 Days': 60,
};
let filters = {};
if (parsedCriteria.includeKeywords) {
filters.includeKeywords = parsedCriteria.includeKeywords.split(',').map((s) => s.trim());
delete parsedCriteria.includeKeywords;
}
if (parsedCriteria.excludeKeywords) {
filters.excludeKeywords = parsedCriteria.excludeKeywords.split(',').map((s) => s.trim());
delete parsedCriteria.excludeKeywords;
}
if (parsedCriteria.fundingTypes) {
filters.fundingTypes = parsedCriteria.fundingTypes.map((ft) => ft.code);
delete parsedCriteria.fundingTypes;
}
if (parsedCriteria.agency) {
filters.agencyCode = filters.agency;
delete parsedCriteria.agency;
}
if (parsedCriteria.postedWithin) {
filters.postedWithinDays = postedWithinOptions[parsedCriteria.postedWithin] || 0;
delete parsedCriteria.postedWithin;
}
if (parsedCriteria.eligibility) {
filters.eligibilityCodes = parsedCriteria.eligibility.map((e) => e.code);
delete parsedCriteria.eligibility;
}
if (parsedCriteria.fundingActivityCategories) {
filters.fundingActivityCategories = parsedCriteria.fundingActivityCategories.map((c) => c.code);
delete parsedCriteria.fundingActivityCategories;
}
filters = { ...filters, ...parsedCriteria };
return filters;
}
function validateSearchFilters(filters) {
const filterOptionsByType = {
reviewStatuses: { type: 'List', valueType: 'Enum', values: ['Applied', 'Not Applying', 'Interested'] },
eligibilityCodes: { type: 'List', valueType: 'String' },
fundingActivityCategories: { type: 'List', valueType: 'String' },
includeKeywords: { type: 'List', valueType: 'String' },
excludeKeywords: { type: 'List', valueType: 'String' },
opportunityNumber: { type: 'String', valueType: 'Any' },
fundingTypes: { type: 'List', valueType: 'Enum', values: ['CA', 'G', 'PC', 'O'] },
opportunityStatuses: { type: 'List', valueType: 'Enum', values: ['posted', 'forecasted', 'closed', 'archived'] },
opportunityCategories: { type: 'List', valueType: 'Enum', values: ['Other', 'Discretionary', 'Mandatory', 'Continuation', 'Earmark'] },
costSharing: { type: 'String', valueType: 'Enum', values: ['Yes', 'No'] },
agencyCode: { type: 'String', valueType: 'Any' },
postedWithinDays: { type: 'number', valueType: 'Any' },
assignedToAgencyId: { type: 'number', valueType: 'Any' },
followedByAgencyId: { type: 'number', valueType: 'Any' },
bill: { type: 'String', valueType: 'Any' },
openDate: { type: 'Date', valueType: 'YYYY-MM-DD' },
};
const errors = [];
for (const [option, value] of Object.entries(filters)) {
if (!value || value.length === 0) {
// eslint-disable-next-line no-continue
continue;
}
if (!filterOptionsByType[option]) {
errors.push(`Received invalid filter ${option}, does not exist`);
} else if (filterOptionsByType[option].type === 'List') {
if (!Array.isArray(value)) {
errors.push(`Received invalid filter ${option}, expected List`);
} else if (filterOptionsByType[option].valueType && value.length > 0) {
if (filterOptionsByType[option].valueType === 'Enum') {
for (const v of value) {
if (!filterOptionsByType[option].values.includes(v)) {
errors.push(`Received invalid filter ${option}, expected List of Enum, found value ${v} that is not in ${filterOptionsByType[option].values}`);
}
}
} else if (filterOptionsByType[option].valueType === 'String') {
for (const v of value) {
if (typeof v !== 'string') {
errors.push(`Received invalid filter ${option}, expected List of String`);
}
}
}
}
} else if (filterOptionsByType[option].type === 'String') {
if (filterOptionsByType[option].valueType === 'Enum') {
if (!filterOptionsByType[option].values.includes(value)) {
errors.push(`Received invalid filter ${option}, expected Enum, found value ${value} that is not in ${filterOptionsByType[option].values}`);
}
} else if (filterOptionsByType[option].valueType === 'Any') {
if (typeof value !== 'string') {
errors.push(`Received invalid filter ${option}, expected String, received ${value}`);
}
}
} else if (filterOptionsByType[option].type === 'number') {
if (filterOptionsByType[option].valueType === 'Any') {
if (typeof value !== 'number') {
errors.push(`Received invalid filter ${option}, expected number, received ${value}`);
}
} else {
errors.push(`Numbers with specific value types is not implemented`);
}
} else if (filterOptionsByType[option].type === 'Date') {
if (filterOptionsByType[option].valueType === 'YYYY-MM-DD') {
if (!moment(value, 'YYYY-MM-DD', true).isValid()) {
errors.push(`Received invalid filter ${option}, expected YYYY-MM-DD, received ${value}`);
}
} else {
errors.push(`Dates without specific value-types/date-format is not implemented`);
}
}
}
return errors;
}
function addCsvData(qb) {
qb
.select(knex.raw(`
CASE
WHEN grants.funding_instrument_codes = 'G' THEN 'Grant'
WHEN grants.funding_instrument_codes = 'CA' THEN 'Cooperative Agreement'
WHEN grants.funding_instrument_codes = 'PC' THEN 'Procurement Contract'
ELSE 'Other'
END as funding_type
`))
.select(knex.raw(`array_to_string(array_agg(${TABLES.eligibility_codes}.label), '|') AS eligibility`))
.leftJoin(
`${TABLES.eligibility_codes}`,
`${TABLES.eligibility_codes}.code`, '=', knex.raw(`ANY(string_to_array(${TABLES.grants}.eligibility_codes, ' '))`),
);
}
/*
filters: {
reviewStatuses: List[Enum['Applied', 'Not Applying', 'Interested']],
eligibilityCodes: List[String],
includeKeywords: List[String],
excludeKeywords: List[String],
opportunityNumber: String,
fundingTypes: List[Enum['CA, 'G', 'PC' ,'O']]
opportunityStatuses: List[Enum['posted', 'forecasted', 'closed']],
opportunityCategories: List[Enum['Other', 'Discretionary', 'Mandatory', 'Continuation']],
costSharing: Enum['Yes', 'No'],
agencyCode: String,
postedWithinDays: number,
assignedToAgencyId: Optional[number],
followedByAgencyId: Optional[number]
bill: String,
},
paginationParams: { currentPage: number, perPage: number, isLengthAware: boolean },
orderingParams: { orderBy: List[string], orderDesc: boolean},
tenantId: number
agencyId: number
*/
async function getGrantsNew(filters, paginationParams, orderingParams, tenantId, agencyId, toCsv) {
const errors = validateSearchFilters(filters);
if (errors.length > 0) {
throw new Error(`Invalid filters: ${errors.join(', ')}`);
}
const query = knex(TABLES.grants)
.select([
'grants.grant_id',
'grants.grant_number',
'grants.title',
'grants.status',
'grants.agency_code',
'grants.cost_sharing',
'grants.cfda_list',
'grants.open_date',
'grants.close_date',
'grants.archive_date',
'grants.reviewer_name',
'grants.opportunity_category',
'grants.search_terms',
'grants.notes',
'grants.created_at',
'grants.updated_at',
'grants.description',
'grants.eligibility_codes',
'grants.award_floor',
'grants.revision_id',
'grants.title_ts',
'grants.description_ts',
'grants.funding_instrument_codes',
'grants.bill',
'grants.funding_activity_category_codes',
])
.select(knex.raw(`
CASE
WHEN grants.archive_date <= now() THEN 'archived'
WHEN grants.close_date <= now() THEN 'closed'
ELSE 'posted'
END as opportunity_status
`))
.select(knex.raw(`
NULLIF(grants.award_ceiling, 0) as award_ceiling
`))
.modify((qb) => grantsQuery(qb, filters, agencyId, orderingParams, paginationParams))
.select(knex.raw(`
count(*) OVER() AS full_count
`))
.groupBy(
'grants.grant_id',
'grants.grant_number',
'grants.title',
'grants.status',
'grants.agency_code',
'award_ceiling',
'grants.cost_sharing',
'grants.cfda_list',
'grants.open_date',
'grants.close_date',
'grants.archive_date',
'grants.reviewer_name',
'grants.opportunity_category',
'grants.search_terms',
'grants.notes',
'grants.created_at',
'grants.updated_at',
'grants.description',
'grants.eligibility_codes',
'grants.award_floor',
'grants.revision_id',
'grants.title_ts',
'grants.description_ts',
'grants.funding_instrument_codes',
'grants.bill',
'grants.funding_activity_category_codes',
);
if (toCsv) {
query.modify(addCsvData);
}
const data = await query;
const fullCount = data.length > 0 ? data[0].full_count : 0;
const pagination = {
total: parseInt(fullCount, 10),
lastPage: Math.ceil(parseInt(fullCount, 10) / parseInt(paginationParams.perPage, 10)),
};
const enhancedData = await enhanceGrantData(tenantId, data);
return { data: enhancedData, pagination };
}
async function enhanceGrantData(tenantId, data) {
if (!data.length) return [];
const viewedByQuery = knex(TABLES.agencies)
.join(TABLES.grants_viewed, `${TABLES.agencies}.id`, '=', `${TABLES.grants_viewed}.agency_id`)
.whereIn('grant_id', data.map((grant) => grant.grant_id))
.andWhere('agencies.tenant_id', tenantId);
const viewedBy = await viewedByQuery.distinct(
`${TABLES.grants_viewed}.grant_id`,
`${TABLES.grants_viewed}.agency_id`,
`${TABLES.agencies}.name as agency_name`,
`${TABLES.agencies}.abbreviation as agency_abbreviation`,
);
const interestedBy = await getInterestedAgencies({ grantIds: data.map((grant) => grant.grant_id), tenantId });
const followNotesEnabled = process.env.ENABLE_FOLLOW_NOTES === 'true';
let followedBy = null;
if (followNotesEnabled) {
const followedByQuery = knex(TABLES.agencies)
.join(TABLES.users, `${TABLES.agencies}.id`, '=', `${TABLES.users}.agency_id`)
.join(TABLES.grant_followers, `${TABLES.users}.id`, '=', `${TABLES.grant_followers}.user_id`)
.whereIn('grant_id', data.map((grant) => grant.grant_id))
.andWhere(`${TABLES.agencies}.tenant_id`, tenantId);
followedBy = await followedByQuery.distinct(
`${TABLES.grant_followers}.grant_id`,
`${TABLES.grant_followers}.user_id`,
`${TABLES.agencies}.name as agency_name`,
`${TABLES.agencies}.abbreviation as agency_abbreviation`,
);
}
const enhancedData = data.map((grant) => {
const viewedByAgencies = viewedBy.filter((viewed) => viewed.grant_id === grant.grant_id);
const agenciesInterested = interestedBy.filter((interested) => interested.grant_id === grant.grant_id);
const followedByAgencies = followNotesEnabled ? followedBy.filter((followed) => followed.grant_id === grant.grant_id) : [];
return {
...grant,
etitle: decodeURIComponent(escape(grant.title)),
viewed_by_agencies: followNotesEnabled ? alphaSortAgencies(viewedByAgencies) : viewedByAgencies,
interested_agencies: agenciesInterested,
...(followNotesEnabled && { followed_by_agencies: alphaSortAgencies(followedByAgencies) }),
funding_activity_categories: (grant.funding_activity_category_codes || '')
.split(' ')
.map((code) => fundingActivityCategoriesByCode[code]?.name)
.filter(Boolean),
};
});
return enhancedData;
}
function alphaSortAgencies(grants) {
return grants.sort((a, b) => {
if (a.agency_name.toLowerCase() < b.agency_name.toLowerCase()) {
return -1;
}
if (a.agency_name.toLowerCase() > b.agency_name.toLowerCase()) {
return 1;
}
return 0;
});
}
async function getGrants({
currentPage, perPage, tenantId, filters, orderBy, searchTerm, orderDesc,
} = {}) {
const data = await knex(TABLES.grants)
.modify((queryBuilder) => {
if (searchTerm && searchTerm !== 'null') {
queryBuilder.andWhere(
(qb) => qb.where(`${TABLES.grants}.grant_id`, '~*', searchTerm)
.orWhere(`${TABLES.grants}.grant_number`, '~*', searchTerm)
.orWhere(`${TABLES.grants}.title`, '~*', searchTerm),
);
}
if (filters) {
if (filters.interestedByUser || filters.positiveInterest || filters.result || filters.rejected || filters.interestedByAgency) {
queryBuilder.join(TABLES.grants_interested, `${TABLES.grants}.grant_id`, `${TABLES.grants_interested}.grant_id`)
.join(TABLES.interested_codes, `${TABLES.interested_codes}.id`, `${TABLES.grants_interested}.interested_code_id`);
}
if (filters.assignedToAgency) {
queryBuilder.join(TABLES.assigned_grants_agency, `${TABLES.grants}.grant_id`, `${TABLES.assigned_grants_agency}.grant_id`);
}
queryBuilder.andWhere(
(qb) => {
const isMyGrantsQuery = filters.interestedByAgency !== null
|| filters.assignedToAgency !== null
|| filters.rejected !== null
|| filters.result !== null;
if (!isMyGrantsQuery) {
helpers.whereAgencyCriteriaMatch(qb, filters.agencyCriteria);
}
if (filters.interestedByAgency != null) {
qb.where('grants_interested.agency_id', filters.interestedByAgency);
}
if (filters.interestedByUser) {
qb.where(`${TABLES.grants_interested}.user_id`, '=', filters.interestedByUser);
}
if (filters.assignedToAgency) {
qb.where(`${TABLES.assigned_grants_agency}.agency_id`, '=', filters.assignedToAgency);
}
if (!(filters.positiveInterest && filters.result && filters.rejected)) {
if (filters.positiveInterest) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Interested');
}
if (filters.result) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Result');
}
if (filters.rejected) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Rejected');
}
}
if (filters.opportunityStatuses?.length) {
qb.whereIn(`${TABLES.grants}.opportunity_status`, filters.opportunityStatuses);
}
if (filters.opportunityCategories?.length) {
qb.whereIn(`${TABLES.grants}.opportunity_category`, filters.opportunityCategories);
}
if (filters.costSharing) {
qb.where(`${TABLES.grants}.cost_sharing`, '=', filters.costSharing);
}
},
);
}
if (orderBy && orderBy !== 'undefined') {
// we assume orderBy is a valid construction of buildOrderingParams
const orderDirection = ((orderDesc === 'true') ? 'desc' : 'asc');
queryBuilder.orderBy(orderBy, knex.raw(`${orderDirection} NULLS LAST`));
}
queryBuilder.limit(perPage);
queryBuilder.offset((currentPage - 1) * perPage);
});
const counts = await knex(TABLES.grants)
.modify((queryBuilder) => {
if (searchTerm && searchTerm !== 'null') {
queryBuilder.andWhere(
(qb) => qb.where(`${TABLES.grants}.grant_id`, '~*', searchTerm)
.orWhere(`${TABLES.grants}.grant_number`, '~*', searchTerm)
.orWhere(`${TABLES.grants}.title`, '~*', searchTerm),
);
}
if (filters) {
if (filters.interestedByUser || filters.positiveInterest || filters.result || filters.rejected || filters.interestedByAgency) {
queryBuilder.join(TABLES.grants_interested, `${TABLES.grants}.grant_id`, `${TABLES.grants_interested}.grant_id`)
.join(TABLES.interested_codes, `${TABLES.interested_codes}.id`, `${TABLES.grants_interested}.interested_code_id`);
}
if (filters.assignedToAgency) {
queryBuilder.join(TABLES.assigned_grants_agency, `${TABLES.grants}.grant_id`, `${TABLES.assigned_grants_agency}.grant_id`);
}
queryBuilder.andWhere(
(qb) => {
const isMyGrantsQuery = filters.interestedByAgency !== null
|| filters.assignedToAgency !== null
|| filters.rejected !== null
|| filters.result !== null;
if (!isMyGrantsQuery) {
helpers.whereAgencyCriteriaMatch(qb, filters.agencyCriteria);
}
if (filters.interestedByAgency != null) {
qb.where('grants_interested.agency_id', filters.interestedByAgency);
}
if (filters.interestedByUser) {
qb.where(`${TABLES.grants_interested}.user_id`, '=', filters.interestedByUser);
}
if (filters.assignedToAgency) {
qb.where(`${TABLES.assigned_grants_agency}.agency_id`, '=', filters.assignedToAgency);
}
if (!(filters.positiveInterest && filters.result && filters.rejected)) {
if (filters.positiveInterest) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Interested');
}
if (filters.result) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Result');
}
if (filters.rejected) {
qb.where(`${TABLES.interested_codes}.status_code`, '=', 'Rejected');
}