-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathInstrumentDataSource.ts
More file actions
909 lines (824 loc) · 26.4 KB
/
Copy pathInstrumentDataSource.ts
File metadata and controls
909 lines (824 loc) · 26.4 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
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
import { logger } from '@user-office-software/duo-logger';
import { GraphQLError } from 'graphql';
import { Knex } from 'knex';
import { inject, injectable } from 'tsyringe';
import database from './database';
import {
InstrumentRecord,
UserRecord,
createBasicUserObject,
InstrumentWithAvailabilityTimeRecord,
InstrumentHasProposalRecord,
InstrumentWithManagementTimeRecord,
InstitutionRecord,
FapProposalRecord,
CountryRecord,
createTagObject,
} from './records';
import { Tokens } from '../../config/Tokens';
import {
Instrument,
InstrumentsHasProposals,
InstrumentWithAvailabilityTime,
InstrumentWithManagementTime,
} from '../../models/Instrument';
import { Tag } from '../../models/Tag';
import { BasicUserDetails } from '../../models/User';
import { ManagementTimeAllocationsInput } from '../../resolvers/mutations/AdministrationProposalMutation';
import { CreateInstrumentArgs } from '../../resolvers/mutations/CreateInstrumentMutation';
import { FapDataSource } from '../FapDataSource';
import { InstrumentDataSource } from '../InstrumentDataSource';
@injectable()
export default class PostgresInstrumentDataSource
implements InstrumentDataSource
{
constructor(
@inject(Tokens.FapDataSource) private fapDataSource: FapDataSource
) {}
private createInstrumentObject(instrument: InstrumentRecord) {
return new Instrument(
instrument.instrument_id,
instrument.name,
instrument.short_code,
instrument.description,
instrument.manager_user_id,
instrument.selectable,
instrument.multiple_tech_reviews_enabled
);
}
private createInstrumentWithAvailabilityTimeObject(
instrument: InstrumentWithAvailabilityTimeRecord
) {
return new InstrumentWithAvailabilityTime(
instrument.instrument_id,
instrument.name,
instrument.short_code,
instrument.description,
instrument.manager_user_id,
instrument.availability_time,
instrument.submitted,
instrument.fap_id
);
}
private createInstrumentWithManagementTimeObject(
instrument: InstrumentWithManagementTimeRecord
) {
return new InstrumentWithManagementTime(
instrument.instrument_id,
instrument.name,
instrument.short_code,
instrument.description,
instrument.manager_user_id,
instrument.management_time_allocation,
instrument.multiple_tech_reviews_enabled
);
}
async create(args: CreateInstrumentArgs): Promise<Instrument> {
const [instrumentRecord]: InstrumentRecord[] = await database
.insert({
name: args.name,
short_code: args.shortCode,
description: args.description,
manager_user_id: args.managerUserId,
selectable: !!args.selectable,
multiple_tech_reviews_enabled: !!args.multipleTechReviewsEnabled,
})
.into('instruments')
.returning('*');
if (!instrumentRecord) {
throw new GraphQLError('Could not create instrument');
}
return this.createInstrumentObject(instrumentRecord);
}
async getInstrument(instrumentId: number): Promise<Instrument | null> {
return database
.select()
.from('instruments')
.where('instrument_id', instrumentId)
.first()
.then((instrument: InstrumentRecord | null) =>
instrument ? this.createInstrumentObject(instrument) : null
);
}
async getInstrumentsByNames(
instrumentNames: string[]
): Promise<Instrument[]> {
return database
.select()
.from('instruments')
.whereIn('name', instrumentNames)
.then((results: InstrumentRecord[]) =>
results.map(this.createInstrumentObject)
);
}
async getInstrumentsByIds(instrumentIds: number[]): Promise<Instrument[]> {
return database
.select()
.from('instruments')
.whereIn('instrument_id', instrumentIds)
.then((results: InstrumentRecord[]) =>
results.map(this.createInstrumentObject)
);
}
async getInstruments(
first?: number,
offset?: number,
agentRoleId?: number
): Promise<{ totalCount: number; instruments: Instrument[] }> {
let instruments: InstrumentRecord[];
const tags = agentRoleId
? (await this.getTagsByRoleId(agentRoleId)) ?? []
: [];
if (tags.length > 0) {
const tagIds = tags.map((tag) => tag.id);
instruments = await database
.select(['i.*', database.raw('count(*) OVER() AS full_count')])
.from('instruments as i')
.join('tag_instrument as ti', 'i.instrument_id', 'ti.instrument_id')
.whereIn('ti.tag_id', tagIds)
.orderBy('i.instrument_id', 'desc')
.modify((query) => {
if (first) {
query.limit(first);
}
if (offset) {
query.offset(offset);
}
});
} else {
instruments = await database
.select(['*', database.raw('count(*) OVER() AS full_count')])
.from('instruments')
.orderBy('instrument_id', 'desc')
.modify((query) => {
if (first) {
query.limit(first);
}
if (offset) {
query.offset(offset);
}
});
}
const result = instruments.map((instrument) =>
this.createInstrumentObject(instrument)
);
return {
totalCount: instruments[0] ? instruments[0].full_count : 0,
instruments: result,
};
}
async getTagsByRoleId(roleId: number): Promise<Tag[]> {
try {
const rows = await database
.select('t.tag_id', 't.name')
.from('roles_has_tags as rht')
.join('tag as t', 't.tag_id', 'rht.tag_id')
.where('rht.role_id', roleId);
return rows.map(createTagObject);
} catch (error) {
logger.logError('Failed to get tags by role id', {
roleId,
});
throw error;
}
}
async getInstrumentsByCallId(
callIds: number[],
selectableOnly?: boolean
): Promise<InstrumentWithAvailabilityTime[]> {
return database
.select([
'i.instrument_id',
'name',
'short_code',
'description',
'manager_user_id',
'chi.availability_time',
'chi.fap_id',
])
.from('instruments as i')
.join('call_has_instruments as chi', {
'i.instrument_id': 'chi.instrument_id',
})
.whereIn('chi.call_id', callIds)
.modify((query) => {
if (selectableOnly) {
query.andWhere('i.selectable', true);
}
})
.distinct('i.instrument_id')
.then((instruments: InstrumentWithAvailabilityTimeRecord[]) => {
const result = instruments.map((instrument) =>
this.createInstrumentWithAvailabilityTimeObject(instrument)
);
return result;
});
}
async getCallsByInstrumentId(
instrumentId: number,
callIds: number[]
): Promise<{ callId: number; instrumentId: number }[]> {
return database
.select(['call_id', 'instrument_id'])
.from('call_has_instruments')
.whereIn('call_id', callIds)
.andWhere('instrument_id', instrumentId)
.then((calls: { call_id: number; instrument_id: number }[]) => {
const result = calls.map((call) => ({
callId: call.call_id,
instrumentId: call.instrument_id,
}));
return result;
});
}
async getInstrumentHasProposals(
instrumentId: number,
proposalPks: number[]
): Promise<InstrumentsHasProposals> {
return database
.select<InstrumentHasProposalRecord[]>('*')
.from('instrument_has_proposals')
.whereIn('proposal_pk', proposalPks)
.andWhere('instrument_id', instrumentId)
.then((ihp) => {
if (!ihp || ihp.length !== proposalPks.length) {
throw new GraphQLError(
`Could not get instrument proposals records with ${proposalPks} and instrument id: ${instrumentId}`
);
}
return new InstrumentsHasProposals(
ihp.map((i) => i.instrument_has_proposals_id),
[instrumentId],
proposalPks,
ihp.every((i) => i.submitted)
);
});
}
async getInstrumentsHasProposal(
instrumentIds: number[],
proposalPk: number,
callId: number
): Promise<InstrumentsHasProposals> {
return database
.select<InstrumentHasProposalRecord[]>('*')
.from('instrument_has_proposals')
.whereIn('instrument_id', instrumentIds)
.andWhere('proposal_pk', proposalPk)
.then(async (ihp) => {
const instrumentsWithSubmittedFlag =
await this.checkIfAllProposalsOnInstrumentSubmitted(
ihp.map((i) => ({
instrument_id: i.instrument_id,
})) as InstrumentWithAvailabilityTimeRecord[],
callId,
{ proposalPk }
);
return new InstrumentsHasProposals(
ihp.map((i) => i.instrument_has_proposals_id),
instrumentIds,
[proposalPk],
instrumentsWithSubmittedFlag.every((i) => i.submitted)
);
});
}
async getUserInstruments(
userId: number,
agentId?: number
): Promise<Instrument[]> {
const tags = agentId ? (await this.getTagsByRoleId(agentId)) ?? [] : [];
if (tags.length != 0) {
const tagIds = tags.map((tag) => tag.id);
if (tagIds.length != 0) {
const instruments = await database<InstrumentRecord>(
'tag_instrument as ti'
)
.join('instruments as i', 'ti.instrument_id', 'i.instrument_id')
.whereIn('tag_id', tagIds)
.select('i.*');
const managerInstruments = await database<InstrumentRecord>(
'instruments as i'
)
.where('i.manager_user_id', userId)
.select('i.*');
const allInstruments = [...instruments, ...managerInstruments];
const uniqueInstruments = allInstruments.filter(
(inst, index, self) =>
self.findIndex((i) => i.instrument_id === inst.instrument_id) ===
index
);
return uniqueInstruments.map(
this.createInstrumentWithAvailabilityTimeObject
);
} else {
const instruments =
await database<InstrumentRecord>('instruments as i').select('i.*');
return instruments.map(this.createInstrumentWithAvailabilityTimeObject);
}
}
return database
.select([
'i.instrument_id',
'name',
'short_code',
'description',
'manager_user_id',
])
.from('instruments as i')
.leftJoin('instrument_has_scientists as ihs', {
'i.instrument_id': 'ihs.instrument_id',
})
.where(function () {
this.where('ihs.user_id', userId).orWhere('i.manager_user_id', userId);
})
.distinct('i.instrument_id')
.then((instruments: InstrumentRecord[]) => {
const result = instruments.map((instrument) =>
this.createInstrumentObject(instrument)
);
return result;
});
}
async update(instrument: Instrument): Promise<Instrument> {
const [instrumentRecord]: InstrumentRecord[] = await database
.update(
{
name: instrument.name,
short_code: instrument.shortCode,
description: instrument.description,
manager_user_id: instrument.managerUserId,
selectable: instrument.selectable,
multiple_tech_reviews_enabled: instrument.multipleTechReviewsEnabled,
},
['*']
)
.from('instruments')
.where('instrument_id', instrument.id);
if (!instrumentRecord) {
throw new GraphQLError(`Instrument not found ${instrument.id}`);
}
return this.createInstrumentObject(instrumentRecord);
}
async delete(instrumentId: number): Promise<Instrument> {
const [instrumentRecord]: InstrumentRecord[] = await database('instruments')
.where('instrument_id', instrumentId)
.del()
.returning('*');
if (!instrumentRecord) {
throw new GraphQLError(
`Could not delete instrument with id: ${instrumentId} `
);
}
return this.createInstrumentObject(instrumentRecord);
}
async assignProposalToInstrument(
proposalPk: number,
instrumentId: number
): Promise<InstrumentsHasProposals> {
const dataToInsert = {
instrument_id: instrumentId,
proposal_pk: proposalPk,
};
return database('instrument_has_proposals')
.insert(dataToInsert)
.returning(['*'])
.then(([result]: InstrumentHasProposalRecord[]) => {
if (result) {
return new InstrumentsHasProposals(
[result.instrument_has_proposals_id],
[instrumentId],
[result.proposal_pk],
false
);
}
throw new GraphQLError(
`Could not assign proposal ${proposalPk} to instrument with id: ${instrumentId}`
);
});
}
async removeProposalsFromInstrument(
proposalPks: number[],
instrumentId?: number
): Promise<boolean> {
const result = await database('instrument_has_proposals')
.del()
.whereIn('proposal_pk', proposalPks)
.modify((query) => {
if (instrumentId) {
query.andWhere('instrument_id', instrumentId);
}
})
.returning<InstrumentHasProposalRecord[]>('*');
if (result?.length) {
return true;
} else {
return false;
}
}
async getInstrumentsByProposalPk(
proposalPk: number
): Promise<InstrumentWithManagementTime[]> {
return database
.select([
'i.instrument_id',
'name',
'short_code',
'description',
'manager_user_id',
'management_time_allocation',
'multiple_tech_reviews_enabled',
])
.from('instruments as i')
.join('instrument_has_proposals as ihp', {
'i.instrument_id': 'ihp.instrument_id',
})
.orderBy('ihp.instrument_has_proposals_id')
.where('ihp.proposal_pk', proposalPk)
.then((instruments: InstrumentWithManagementTimeRecord[]) => {
const result = instruments.map((instrument) =>
this.createInstrumentWithManagementTimeObject(instrument)
);
return result;
});
}
async updateProposalInstrumentTimeAllocation(
proposalPk: number,
managementTimeAllocations: ManagementTimeAllocationsInput[]
): Promise<boolean> {
const result = await database.transaction(async (trx) => {
const queries = managementTimeAllocations.map(
(managementTimeAllocation) =>
database('instrument_has_proposals')
.where('instrument_id', managementTimeAllocation.instrumentId)
.andWhere('proposal_pk', proposalPk)
.update({
management_time_allocation: managementTimeAllocation.value,
})
.transacting(trx)
);
try {
const value = await Promise.all(queries);
return trx.commit(value);
} catch (error) {
return trx.rollback(error);
}
});
if (!result) {
throw new GraphQLError(
`Cannot update proposal instrument time allocations: ${JSON.stringify(
managementTimeAllocations
)}`
);
}
return true;
}
async checkIfAllProposalsOnInstrumentSubmitted(
instruments: InstrumentWithAvailabilityTimeRecord[],
callId: number,
{ fapId, proposalPk }: { fapId?: number; proposalPk?: number }
): Promise<InstrumentWithAvailabilityTimeRecord[]> {
const instrumentsWithSubmittedFlag: InstrumentWithAvailabilityTimeRecord[] =
[];
for (const instrument of instruments) {
const allProposalsOnInstrument =
await this.fapDataSource.getFapProposalsByInstrument(
instrument.instrument_id,
callId,
{ fapId, proposalPk }
);
const allProposalsOnInstrumentSubmitted = allProposalsOnInstrument.every(
(item) => item.fapInstrumentMeetingSubmitted
);
instrumentsWithSubmittedFlag.push({
...instrument,
submitted: allProposalsOnInstrumentSubmitted,
});
}
return instrumentsWithSubmittedFlag;
}
async getInstrumentsByFapId(
fapId: number,
callId: number
): Promise<InstrumentWithAvailabilityTime[]> {
const fullInstrumentQuery = (query: Knex.QueryBuilder) =>
query
.select([
'i.*',
'chi.availability_time as availability_time',
// NOTE: This is call specific sum of all instrument technical reviews time allocation for proposals that are attached to a FAP
database.raw(
'sum(tr.time_allocation)::integer as all_faps_instrument_time_allocation'
),
])
.from('instruments as i')
.join('technical_review as tr', {
'tr.instrument_id': 'i.instrument_id',
})
.join('fap_proposals as fp', {
'fp.instrument_id': 'i.instrument_id',
'fp.proposal_pk': 'tr.proposal_pk',
})
.join('call_has_instruments as chi', {
'chi.instrument_id': 'i.instrument_id',
'chi.call_id': callId,
})
.groupBy(['i.instrument_id', 'chi.availability_time']);
const fapInstrumentQuery = (query: Knex.QueryBuilder) =>
query
.select([
'i.*',
// NOTE: This is the sum of instrument technical reviews time allocation for specific call and FAP
database.raw(
'sum(tr.time_allocation)::integer as fap_instrument_time_allocation'
),
])
.from('instruments as i')
.join('technical_review as tr', {
'tr.instrument_id': 'i.instrument_id',
})
.join('fap_proposals as fp', {
'fp.instrument_id': 'i.instrument_id',
'fp.proposal_pk': 'tr.proposal_pk',
'fp.fap_id': fapId,
})
.join('call_has_instruments as chi', {
'chi.instrument_id': 'i.instrument_id',
'chi.call_id': callId,
})
.groupBy(['i.instrument_id']);
return database
.with('full_instrument', fullInstrumentQuery)
.with('fap_instrument', fapInstrumentQuery)
.select([
'fap_instrument.*',
'all_faps_instrument_time_allocation',
'availability_time',
])
.from('fap_instrument')
.join('full_instrument', {
'full_instrument.instrument_id': 'fap_instrument.instrument_id',
})
.then(async (instruments: InstrumentWithAvailabilityTimeRecord[]) => {
const instrumentsWithSubmittedFlag =
await this.checkIfAllProposalsOnInstrumentSubmitted(
instruments,
callId,
{ fapId }
);
const result = instrumentsWithSubmittedFlag.map((instrument) => {
let calculatedInstrumentAvailabilityTimePerFap = null;
if (
instrument.availability_time !== null &&
instrument.all_faps_instrument_time_allocation > 0 &&
instrument.fap_instrument_time_allocation !== null
) {
// NOTE: Using "-" sign to round down in .5 cases (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round)
calculatedInstrumentAvailabilityTimePerFap = -Math.round(
-(
instrument.availability_time /
instrument.all_faps_instrument_time_allocation
) * instrument.fap_instrument_time_allocation
);
}
return this.createInstrumentWithAvailabilityTimeObject({
...instrument,
availability_time: calculatedInstrumentAvailabilityTimePerFap,
});
});
return result;
});
}
async assignScientistsToInstrument(
scientistIds: number[],
instrumentId: number
): Promise<boolean> {
const dataToInsert = scientistIds.map((scientistId) => ({
instrument_id: instrumentId,
user_id: scientistId,
}));
const result = await database('instrument_has_scientists').insert(
dataToInsert
);
if (result) {
return true;
} else {
return false;
}
}
async removeScientistFromInstrument(
scientistId: number,
instrumentId: number
): Promise<boolean> {
const result = await database('instrument_has_scientists')
.where('instrument_id', instrumentId)
.andWhere('user_id', scientistId)
.del();
if (result) {
return true;
} else {
return false;
}
}
async assignScientistToInstruments(
scientistId: number,
instrumentIds: number[]
): Promise<boolean> {
const dataToInsert = instrumentIds.map((instrumentId) => ({
instrument_id: instrumentId,
user_id: scientistId,
}));
return database('instrument_has_scientists')
.insert(dataToInsert)
.then((result) => result.length === instrumentIds.length);
}
async removeScientistFromInstruments(
scientistId: number,
instrumentIds: number[]
): Promise<boolean> {
return database('instrument_has_scientists')
.whereIn('instrument_id', instrumentIds)
.andWhere('user_id', scientistId)
.del()
.then((result) => result === instrumentIds.length);
}
async getInstrumentScientists(
instrumentId: number
): Promise<BasicUserDetails[]> {
return database
.select('*')
.from('users as u')
.join('instrument_has_scientists as ihs', {
'u.user_id': 'ihs.user_id',
})
.join('institutions as i', { 'u.institution_id': 'i.institution_id' })
.where('ihs.instrument_id', instrumentId)
.then(
(
usersRecord: Array<UserRecord & InstitutionRecord & CountryRecord>
) => {
const users = usersRecord.map((user) => createBasicUserObject(user));
return users;
}
);
}
async setAvailabilityTimeOnInstrument(
callId: number,
instrumentId: number,
availabilityTime: number
): Promise<boolean> {
const result = await database.raw(
`${database('call_has_instruments').insert({
instrument_id: instrumentId,
call_id: callId,
availability_time: availabilityTime,
})} ON CONFLICT (instrument_id, call_id) DO UPDATE SET availability_time=${availabilityTime}`
);
if (result) {
return true;
} else {
return false;
}
}
async submitInstrumentInFap(
proposalPks: number[],
instrumentId: number
): Promise<InstrumentsHasProposals> {
const records: FapProposalRecord[] = await database('fap_proposals')
.update(
{
fap_meeting_instrument_submitted: true,
},
['*']
)
.whereIn('proposal_pk', proposalPks)
.andWhere('instrument_id', instrumentId);
if (!records?.length) {
throw new GraphQLError(
`No fap_proposals found with proposalPks: ${proposalPks} and instrumentId: ${instrumentId}`
);
}
const instrumentHasProposls = await this.getInstrumentHasProposals(
instrumentId,
proposalPks
);
if (
instrumentHasProposls.instrumentHasProposalIds.length !==
proposalPks.length
) {
logger.logWarn(
`Some record from instrument proposals were not found with proposalPks: ${proposalPks} and instrumentId: ${instrumentId}`,
{}
);
}
return new InstrumentsHasProposals(
instrumentHasProposls.instrumentHasProposalIds,
[instrumentId],
proposalPks,
true
);
}
async unsubmitInstrumentInFap(
proposalPks: number[],
instrumentId: number
): Promise<InstrumentsHasProposals> {
const records: FapProposalRecord[] = await database('fap_proposals')
.update(
{
fap_meeting_instrument_submitted: false,
},
['*']
)
.whereIn('proposal_pk', proposalPks)
.andWhere('instrument_id', instrumentId);
if (!records?.length) {
throw new GraphQLError(
`No fap_proposals found with proposalPks: ${proposalPks} and instrumentId: ${instrumentId}`
);
}
const instrumentHasProposals = await this.getInstrumentHasProposals(
instrumentId,
proposalPks
);
if (
instrumentHasProposals.instrumentHasProposalIds.length !==
proposalPks.length
) {
logger.logWarn(
`Some record from instrument proposals was not found with proposalPks: ${proposalPks} and instrumentId: ${instrumentId}`,
{}
);
}
return new InstrumentsHasProposals(
instrumentHasProposals.instrumentHasProposalIds,
[instrumentId],
proposalPks,
true
);
}
async hasInstrumentScientistInstrument(
userId: number,
instrumentId: number
): Promise<boolean> {
const result: { count?: string | number | undefined } | undefined =
await database
.count({ count: '*' })
.from('instruments as i')
.leftJoin('instrument_has_scientists as ihs', function () {
this.on('i.instrument_id', '=', 'ihs.instrument_id').andOnVal(
'ihs.user_id',
'=',
userId
);
})
.where('i.instrument_id', instrumentId)
.andWhere(function () {
this.whereNotNull('ihs.user_id').orWhere('i.manager_user_id', userId);
})
.first();
return Number(result?.count) >= 1;
}
async hasInstrumentScientistAccess(
scientistId: number,
instrumentId: number,
proposalPk: number
): Promise<boolean> {
return database
.select([database.raw('count(*) OVER() AS count')])
.from('proposals')
.join('instrument_has_proposals', {
'instrument_has_proposals.proposal_pk': 'proposals.proposal_pk',
})
.join('instruments', {
'instruments.instrument_id': 'instrument_has_proposals.instrument_id',
})
.leftJoin('instrument_has_scientists', {
'instrument_has_scientists.instrument_id': 'instruments.instrument_id',
'instrument_has_scientists.user_id': scientistId,
})
.where('proposals.proposal_pk', '=', proposalPk)
.where('instrument_has_proposals.instrument_id', '=', instrumentId)
.andWhere(function () {
this.where('instrument_has_scientists.user_id', scientistId).orWhere(
'instruments.manager_user_id',
scientistId
);
})
.first()
.then((result) => {
return Number(result?.count) >= 1;
});
}
async getInstrumentsByFapIds(fapId: number[]): Promise<Instrument[]> {
return database
.select('i.*')
.from('fap_proposals as fp')
.join('instruments as i', { 'fp.instrument_id': 'i.instrument_id' })
.where('fp.fap_id', 'in', fapId)
.distinct()
.then((instruments: InstrumentRecord[]) => {
const result = instruments.map((instrument) =>
this.createInstrumentObject(instrument)
);
return result;
});
}
}