-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCallDataSource.ts
More file actions
654 lines (589 loc) · 20.4 KB
/
Copy pathCallDataSource.ts
File metadata and controls
654 lines (589 loc) · 20.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
import { logger } from '@user-office-software/duo-logger';
import { GraphQLError } from 'graphql';
import { Call } from '../../models/Call';
import { CallHasInstrument } from '../../models/CallHasInstrument';
import { Workflow } from '../../models/Workflow';
import { CreateCallInput } from '../../resolvers/mutations/CreateCallMutation';
import {
AssignInstrumentsToCallInput,
RemoveAssignedInstrumentFromCallInput,
UpdateCallInput,
UpdateFapToCallInstrumentInput,
CallOrderInput,
CallOrderArray,
} from '../../resolvers/mutations/UpdateCallMutation';
import { PaginationSortDirection } from '../../utils/pagination';
import { CallDataSource } from '../CallDataSource';
import { CallsFilter } from './../../resolvers/queries/CallsQuery';
import database from './database';
import { calculateReferenceNumber } from './ProposalDataSource';
import {
CallHasInstrumentRecord,
CallRecord,
createCallHasInstrumentObject,
createCallObject,
ProposalRecord,
WorkflowRecord,
} from './records';
const fieldMap: { [key: string]: string } = {
sort_order: 'sort_order',
call_id: 'call_id',
};
export default class PostgresCallDataSource implements CallDataSource {
async delete(id: number): Promise<Call> {
return database
.where('call.call_id', id)
.del()
.from('call')
.returning('*')
.then((call: CallRecord[]) => createCallObject(call[0]));
}
async getCall(id: number): Promise<Call | null> {
return database
.select()
.from('call')
.where('call_id', id)
.first()
.then((call: CallRecord | null) =>
call ? createCallObject(call) : null
);
}
async getCalls(
filter?: CallsFilter,
sortField?: string,
sortDirection?: PaginationSortDirection
): Promise<Call[]> {
const query = database('call').select([
'*',
'call.description as description',
]);
if (filter?.shortCode) {
query.where('call_short_code', 'like', `%${filter.shortCode}%`);
}
if (filter?.templateIds) {
query.whereIn('template_id', filter.templateIds);
}
if (filter?.proposalPdfTemplateIds) {
query.whereIn('proposal_pdf_template_id', filter.proposalPdfTemplateIds);
}
if (filter?.experimentSafetyPdfTemplateIds) {
query.whereIn(
'experiment_safety_pdf_template_id',
filter.experimentSafetyPdfTemplateIds
);
}
if (filter?.fapReviewTemplateIds) {
query.whereIn('fap_review_template_id', filter.fapReviewTemplateIds);
}
if (filter?.technicalReviewTemplateIds) {
query.whereIn(
'technical_review_template_id',
filter.technicalReviewTemplateIds
);
}
if (filter?.esiTemplateIds) {
query.whereIn('esi_template_id', filter.esiTemplateIds);
}
// if filter is explicitly set to true or false
if (filter?.isActive === true) {
query.where('is_active', true);
} else if (filter?.isActive === false) {
query.where('is_active', false);
}
if (filter?.isEndedInternal === true) {
query.where('call_ended_internal', true);
} else if (filter?.isEndedInternal === false) {
query.where('call_ended_internal', false);
}
/**
* NOTE: We are comparing dates instead of using the call_ended flag,
* because the flag is set once per hour and we could have a gap.
* TODO: Maybe there is a need to use the timezone setting here but not quite sure about it. Discussion is needed here!
*/
const currentDate = new Date().toISOString();
// if filter is explicitly set for internal filter of calls
if (
filter?.isActive === true &&
filter?.isActiveInternal === true &&
filter?.isEnded === false
) {
query
.where('start_call', '<=', currentDate)
.andWhere('end_call_internal', '>=', currentDate);
} else if (filter?.isEnded === true) {
query.where('end_call', '<=', currentDate);
} else if (filter?.isCallUpcoming === true) {
query
.where('end_call', '>=', currentDate)
.orWhere('end_call_internal', '>=', currentDate);
} else if (filter?.isEnded === false) {
query
.where('start_call', '<=', currentDate)
.andWhere('end_call', '>=', currentDate);
} else if (filter?.isActiveInternal === true) {
query
.where('end_call', '<', currentDate)
.andWhere('end_call_internal', '>=', currentDate);
} else if (filter?.isActiveInternal === false) {
query.where('call_ended_internal', '=', true);
}
if (filter?.isReviewEnded === true) {
query.where('call_review_ended', true);
} else if (filter?.isReviewEnded === false) {
query.where('call_review_ended', false);
}
if (filter?.fapIds?.length) {
query
.leftJoin('call_has_faps as chs', 'chs.call_id', 'call.call_id')
.whereIn('chs.fap_id', filter.fapIds)
.distinctOn('call.call_id');
}
if (filter?.instrumentIds?.length) {
query
.leftJoin('call_has_instruments as chi', 'chi.call_id', 'call.call_id')
.whereIn('chi.instrument_id', filter.instrumentIds)
.distinctOn('call.call_id');
}
if (filter?.isFapReviewEnded === true) {
query.where('call_fap_review_ended', true);
} else if (filter?.isFapReviewEnded === false) {
query.where('call_fap_review_ended', false);
}
if (filter?.isCallEndedByEvent === true) {
query.where('call_ended', true);
} else if (filter?.isCallEndedByEvent === false) {
query.where('call_ended', false);
}
if (filter?.proposalStatusShortCode) {
query
.join(
'workflow_connections as w',
'call.proposal_workflow_id',
'w.workflow_id'
)
.leftJoin('statuses as s', 'w.status_id', 's.status_id')
.where('s.short_code', filter.proposalStatusShortCode)
.distinctOn('call.call_id');
}
if (sortField && sortDirection) {
if (!fieldMap.hasOwnProperty(sortField)) {
throw new GraphQLError(`Bad sort field given: ${sortField}`);
}
sortField = fieldMap[sortField];
query.orderBy(sortField, sortDirection);
}
return query.then((callDB: CallRecord[]) => {
return callDB.map((call) => createCallObject(call));
});
}
async getCallHasInstrumentsByInstrumentIds(
instrumentIds: number[]
): Promise<CallHasInstrument[]> {
return database
.select()
.from('call_has_instruments')
.whereIn('instrument_id', instrumentIds)
.then((callHasInstrument: CallHasInstrumentRecord[]) =>
callHasInstrument.map((callHasInstrument) =>
createCallHasInstrumentObject(callHasInstrument)
)
);
}
async create(args: CreateCallInput): Promise<Call> {
if (!args.sort_order) {
args.sort_order = 0;
}
const [call]: CallRecord[] = await database.transaction(async (trx) => {
try {
const createdCall: CallRecord[] = await database
.insert({
call_short_code: args.shortCode,
start_call: args.startCall,
end_call: args.endCall,
end_call_internal: args.endCallInternal || args.endCall,
start_review: args.startReview,
end_review: args.endReview,
start_fap_review: args.startFapReview,
end_fap_review: args.endFapReview,
start_notify: args.startNotify,
end_notify: args.endNotify,
start_cycle: args.startCycle,
end_cycle: args.endCycle,
cycle_comment: args.cycleComment,
submission_message: args.submissionMessage,
survey_comment: args.surveyComment,
reference_number_format: args.referenceNumberFormat,
proposal_sequence: args.proposalSequence,
proposal_workflow_id: args.proposalWorkflowId,
experiment_workflow_id: args.experimentWorkflowId,
template_id: args.templateId,
esi_template_id: args.esiTemplateId,
proposal_pdf_template_id: args.proposalPdfTemplateId,
experiment_safety_pdf_template_id:
args.experimentSafetyPdfTemplateId,
fap_review_template_id: args.fapReviewTemplateId,
technical_review_template_id: args.technicalReviewTemplateId,
allocation_time_unit: args.allocationTimeUnit,
title: args.title,
description: args.description,
sort_order: args.sort_order,
})
.into('call')
.returning('*')
.transacting(trx);
// NOTE: Attach Faps to a call if they are provided.
if (createdCall[0].call_id && args.faps?.length) {
const valuesToInsert = args.faps.map((fapId) => ({
fap_id: fapId,
call_id: createdCall[0].call_id,
}));
await database
.insert(valuesToInsert)
.into('call_has_faps')
.transacting(trx);
}
return await trx.commit(createdCall);
} catch (error) {
logger.logException(
`Could not create call with args: '${JSON.stringify(args)}'`,
error
);
trx.rollback();
throw new GraphQLError('Could not create call');
}
});
return createCallObject(call);
}
async update(args: UpdateCallInput): Promise<Call> {
const call = await database.transaction(async (trx) => {
try {
const currentDate = new Date();
/*
* Check if the reference number format has been changed,
* in which case all proposals in the call need to be updated.
*/
const preUpdateCall: Pick<
CallRecord,
| 'call_id'
| 'reference_number_format'
| 'call_ended_internal'
| 'call_ended'
> = await database
.select(
'c.call_id',
'c.reference_number_format',
'c.call_ended_internal',
'c.call_ended'
)
.from('call as c')
.where('c.call_id', args.id)
.first()
.forUpdate()
.transacting(trx);
const { referenceNumberFormat } = args;
if (
referenceNumberFormat &&
referenceNumberFormat !== preUpdateCall.reference_number_format
) {
const proposals = (await database
.select('p.proposal_pk', 'p.reference_number_sequence')
.from('proposals as p')
.where({ 'p.call_id': preUpdateCall.call_id, 'p.submitted': true })
.forUpdate()
.transacting(trx)) as Pick<
ProposalRecord,
'proposal_pk' | 'reference_number_sequence'
>[];
await Promise.all(
proposals.map(async (proposal) =>
database
.update({
proposal_id: await calculateReferenceNumber(
referenceNumberFormat,
proposal.reference_number_sequence
),
})
.from('proposals')
.where('proposal_pk', proposal.proposal_pk)
.transacting(trx)
)
);
}
// NOTE: Attach Faps to a call if they are provided.
if (args.id && args.faps !== undefined) {
const valuesToInsert = args.faps.map((fapId) => ({
fap_id: fapId,
call_id: args.id,
}));
// NOTE: Remove all assigned Faps from a call and then re-assign
await database('call_has_faps')
.del()
.where('call_id', args.id)
.transacting(trx);
if (valuesToInsert.length) {
await database
.insert(valuesToInsert)
.into('call_has_faps')
.transacting(trx);
}
}
/*
Work out whether the call_ended and call_ended_internal flags need updating.
*/
const determineCallEndedFlag = (
newFlagValue: boolean | undefined,
previousFlagValue: boolean | undefined,
endCall: Date | undefined
) => {
// Use the new value if explicitly passed in.
if (newFlagValue) {
return newFlagValue;
}
/*
If the call end date has been changed to the future, set to false.
*/
if (endCall && endCall.getTime() > currentDate.getTime()) {
return false;
}
/*
Where the date has been changed to the past, leave the flag unchanged from
its previous value. If it's false, the call end event will fire for this
call and update the flags, and if true it indicates an old call being updated).
*/
return previousFlagValue;
};
const callUpdate = await database
.update(
{
call_short_code: args.shortCode,
start_call: args.startCall,
end_call: args.endCall,
end_call_internal: args.endCallInternal,
reference_number_format: args.referenceNumberFormat,
start_review: args.startReview,
end_review: args.endReview,
start_fap_review: args.startFapReview,
end_fap_review: args.endFapReview,
start_notify: args.startNotify,
end_notify: args.endNotify,
start_cycle: args.startCycle,
end_cycle: args.endCycle,
cycle_comment: args.cycleComment,
submission_message: args.submissionMessage,
survey_comment: args.surveyComment,
proposal_workflow_id: args.proposalWorkflowId,
experiment_workflow_id: args.experimentWorkflowId,
call_ended: determineCallEndedFlag(
args.callEnded,
preUpdateCall.call_ended,
args.endCall
),
call_ended_internal: determineCallEndedFlag(
args.callEndedInternal,
preUpdateCall.call_ended_internal,
args.endCallInternal
),
call_review_ended: args.callReviewEnded,
call_fap_review_ended: args.callFapReviewEnded,
template_id: args.templateId,
esi_template_id: args.esiTemplateId,
proposal_pdf_template_id: args.proposalPdfTemplateId,
experiment_safety_pdf_template_id:
args.experimentSafetyPdfTemplateId,
fap_review_template_id: args.fapReviewTemplateId,
technical_review_template_id: args.technicalReviewTemplateId,
allocation_time_unit: args.allocationTimeUnit,
title: args.title,
description: args.description,
is_active: args.isActive,
},
['*']
)
.from('call')
.where('call_id', args.id)
.transacting(trx);
return await trx.commit(callUpdate);
} catch (error) {
logger.logException(
`Could not update call with id '${args.id}'`,
error
);
trx.rollback();
throw new GraphQLError('Could not update call');
}
});
return createCallObject(call[0]);
}
async setNewSortOrder(data: CallOrderArray): Promise<number> {
return await database
.update({ sort_order: data.sort_order + 1 })
.from('call')
.where({ call_id: data.callId });
}
async orderCalls(data: CallOrderInput): Promise<boolean> {
try {
data.data.forEach((item) => {
this.setNewSortOrder(item);
});
} catch {
throw new GraphQLError('Could not update call order');
}
return true;
}
async assignInstrumentsToCall(
args: AssignInstrumentsToCallInput
): Promise<Call> {
const valuesToInsert = args.instrumentFapIds.map((instrumentFap) => ({
instrument_id: instrumentFap.instrumentId,
fap_id: instrumentFap.fapId,
call_id: args.callId,
}));
await database.insert(valuesToInsert).into('call_has_instruments');
const callUpdated = await this.getCall(args.callId);
if (callUpdated) {
return callUpdated;
}
throw new GraphQLError(`Call not found ${args.callId}`);
}
async updateFapToCallInstrument(
args: UpdateFapToCallInstrumentInput
): Promise<Call> {
await database
.update({ fap_id: args.fapId ?? null })
.into('call_has_instruments')
.where('instrument_id', args.instrumentId)
.andWhere('call_id', args.callId);
const callUpdated = await this.getCall(args.callId);
if (callUpdated) {
return callUpdated;
}
throw new GraphQLError(`Call not found ${args.callId}`);
}
async removeAssignedInstrumentFromCall(
args: RemoveAssignedInstrumentFromCallInput
): Promise<Call> {
await database('call_has_instruments')
.del()
.where('instrument_id', args.instrumentId)
.andWhere('call_id', args.callId);
const callUpdated = await this.getCall(args.callId);
if (callUpdated) {
return callUpdated;
}
throw new GraphQLError(`Call not found ${args.callId}`);
}
async getCallsByInstrumentScientist(scientistId: number): Promise<Call[]> {
const records: CallRecord[] = await database('call')
.distinct(['call.*'])
.join(
'call_has_instruments',
'call_has_instruments.call_id',
'call.call_id'
)
.join(
'instrument_has_scientists',
'instrument_has_scientists.instrument_id',
'call_has_instruments.instrument_id'
)
.join(
'instruments',
'instruments.instrument_id',
'call_has_instruments.instrument_id'
)
.where('instrument_has_scientists.user_id', scientistId)
.orWhere('instruments.manager_user_id', scientistId);
return records.map(createCallObject);
}
public async isCallEnded(callId: number): Promise<boolean>;
public async isCallEnded(
callId: number,
checkIfInternalEnded: boolean
): Promise<boolean>;
public async isCallEnded(
callId: number,
checkIfInternalEnded: boolean = false
): Promise<boolean> {
const currentDate = new Date().toISOString();
return database
.select()
.from('call')
.where('start_call', '<=', currentDate)
.andWhere(
checkIfInternalEnded ? 'end_call_internal' : 'end_call',
'>=',
currentDate
)
.andWhere('call_id', '=', callId)
.first()
.then((call: CallRecord) => (call ? false : true));
}
public async getCallByAnswerIdProposal(answerId: number): Promise<Call> {
const records: CallRecord[] = await database('call')
.join(
'templates_has_questions',
'templates_has_questions.template_id',
'call.template_id'
)
.join(
database('answers')
.select()
.where('answers.answer_id', answerId)
.as('a'),
'a.question_id',
'templates_has_questions.question_id'
);
if (records.length > 0) {
return createCallObject(records[0]);
}
throw new GraphQLError(`Call not found for answerId: ${answerId}`);
}
private createProposalWorkflowObject(proposalWorkflow: WorkflowRecord) {
return new Workflow(
proposalWorkflow.workflow_id,
proposalWorkflow.name,
proposalWorkflow.description,
proposalWorkflow.entity_type,
proposalWorkflow.connection_line_type
);
}
async getProposalWorkflowByCall(callId: number): Promise<Workflow | null> {
return database
.select()
.from('call as c')
.join('workflows as w', {
'w.workflow_id': 'c.proposal_workflow_id',
})
.where('c.call_id', callId)
.first()
.then((proposalWorkflow: WorkflowRecord | null) =>
proposalWorkflow
? this.createProposalWorkflowObject(proposalWorkflow)
: null
);
}
async getExperimentWorkflowByCall(callId: number): Promise<Workflow | null> {
return database
.select()
.from('call as c')
.join('workflows as w', {
'w.workflow_id': 'c.experiment_workflow_id',
})
.where('c.call_id', callId)
.first()
.then((experimentWorkflow: WorkflowRecord | null) =>
experimentWorkflow
? this.createProposalWorkflowObject(experimentWorkflow)
: null
);
}
async getCallsOfFaps(fapIds: number[]): Promise<Call[]> {
return database
.distinct('call.*')
.from('call')
.join('call_has_faps as chf', 'chf.call_id', 'call.call_id')
.whereIn('chf.fap_id', fapIds)
.then((calls: CallRecord[]) => {
return calls.map((call) => createCallObject(call));
});
}
}