Skip to content

Commit

Permalink
fix: introduce onBeforeSave
Browse files Browse the repository at this point in the history
  • Loading branch information
enthusiastio committed Jun 29, 2023
1 parent fdb6374 commit 6833d53
Show file tree
Hide file tree
Showing 9 changed files with 70 additions and 154 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import {
Questionary,
QuestionaryStep,
} from '../models/Questionary';
import { DataType, Question, Template } from '../models/Template';
import { Template } from '../models/Template';

export interface QuestionaryDataSource {
getCount(templateId: number): Promise<number>;
Expand All @@ -18,10 +18,6 @@ export interface QuestionaryDataSource {
getBlankQuestionarySteps(templateId: number): Promise<QuestionaryStep[]>;
getBlankQuestionaryStepsByCallId(callId: number): Promise<QuestionaryStep[]>;
getAnswers(questionId: string): Promise<AnswerBasic[]>;
getLatestAnswerByQuestionaryIdAndDataType(
questionaryId: number,
dataType: DataType
): Promise<{ answer: AnswerBasic; question: Question } | null>;
getTemplates(questionId: string): Promise<Template[]>;
getIsCompleted(questionaryId: number): Promise<boolean>;
updateAnswer(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -387,13 +387,6 @@ export class QuestionaryDataSourceMock implements QuestionaryDataSource {
return [];
}

async getLatestAnswerByQuestionaryIdAndDataType(
questionaryId: number,
dataType: DataType
): Promise<{ answer: AnswerBasic; question: Question } | null> {
return null;
}

async getTemplates(questionId: string): Promise<Template[]> {
return [];
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import {
import {
DataType,
FieldDependency,
Question,
Template,
Topic,
} from '../../models/Template';
Expand All @@ -36,7 +35,6 @@ import {
TopicRecord,
ProposalRecord,
createProposalObject,
createQuestionObject,
} from './records';

type AnswerRecord<T extends DataType> = QuestionRecord &
Expand Down Expand Up @@ -130,33 +128,6 @@ export default class PostgresQuestionaryDataSource
});
}

async getLatestAnswerByQuestionaryIdAndDataType(
questionaryId: number,
dataType: DataType
): Promise<{ answer: AnswerBasic; question: Question } | null> {
return database('answers')
.leftJoin(
'questions',
'questions.question_id',
'=',
'answers.question_id'
)
.where('answers.questionary_id', questionaryId)
.where('questions.data_type', dataType)
.orderBy('answers.created_at', 'desc')
.limit(1)
.then((rows) => {
if (rows.length == 0) {
return null;
}

return {
answer: createAnswerBasic(rows[0]),
question: createQuestionObject(rows[0]),
};
});
}

async getTemplates(questionId: string): Promise<Template[]> {
return database('templates_has_questions')
.leftJoin(
Expand Down
2 changes: 0 additions & 2 deletions apps/user-office-backend/src/eventHandlers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import createCustomHandler from './customHandler';
import createLoggingHandler from './logging';
import { createPostToQueueHandler } from './messageBroker';
import createProposalWorkflowHandler from './proposalWorkflow';
import createInstrumentPickerHandler from './questionary/instrumentPicker';

export default function createEventHandlers() {
const emailHandler = container.resolve<
Expand All @@ -19,6 +18,5 @@ export default function createEventHandlers() {
createPostToQueueHandler(),
createProposalWorkflowHandler(),
createCustomHandler(),
createInstrumentPickerHandler(),
];
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { container } from 'tsyringe';

import { Tokens } from '../../config/Tokens';
import { InstrumentDataSource } from '../../datasources/InstrumentDataSource';
import { ProposalDataSource } from '../../datasources/ProposalDataSource';
import { InstrumentPickerConfig } from '../../resolvers/types/FieldConfig';
import { QuestionFilterCompareOperator } from '../Questionary';
import { DataType, QuestionTemplateRelation } from '../Template';
Expand Down Expand Up @@ -73,4 +74,26 @@ export const instrumentPickerDefinition: Question<DataType.INSTRUMENT_PICKER> =

return fallBackConfig;
},
async onBeforeSave(questionaryId, questionTemplateRelation, answer) {
const instrumentDataSource = container.resolve<InstrumentDataSource>(
Tokens.InstrumentDataSource
);

const proposalDataSource = container.resolve<ProposalDataSource>(
Tokens.ProposalDataSource
);

const proposal = await proposalDataSource.getByQuestionaryId(
questionaryId
);
if (!proposal) {
throw new GraphQLError('Proposal not found');
}

const { value } = JSON.parse(answer.value);
await instrumentDataSource.assignProposalsToInstrument(
[proposal?.primaryKey],
value
);
},
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { logger } from '@user-office-software/duo-logger';
import { GraphQLError } from 'graphql';
import { Knex } from 'knex';

import { AnswerInput } from '../../resolvers/mutations/AnswerTopicMutation';
import { QuestionFilterInput } from '../../resolvers/queries/ProposalsQuery';
import {
BooleanConfig,
Expand Down Expand Up @@ -142,6 +143,12 @@ export interface Question<T extends DataType> {
config: QuestionDataTypeConfigMapping<T>,
callId?: number
) => Promise<QuestionDataTypeConfigMapping<T>>;

onBeforeSave?: (
questionaryId: number,
questionTemplateRelation: QuestionTemplateRelation,
answer: AnswerInput
) => Promise<void>;
}

// Add new component definitions here
Expand Down
57 changes: 26 additions & 31 deletions apps/user-office-backend/src/mutations/InstrumentMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,36 +126,38 @@ export default class InstrumentMutations {
}

@EventBus(Event.PROPOSAL_INSTRUMENT_SELECTED)
async assignProposalsToInstrumentHelper(
@ValidateArgs(assignProposalsToInstrumentValidationSchema)
@Authorized([Roles.USER_OFFICER])
async assignProposalsToInstrument(
agent: UserWithRole | null,
args: AssignProposalsToInstrumentArgs
) {
): Promise<ProposalPks | Rejection> {
const allProposalsAreOnSameCallAsInstrument =
await this.checkIfProposalsAreOnSameCallAsInstrument(args);

if (!allProposalsAreOnSameCallAsInstrument) {
return rejection(
'One or more proposals can not be assigned to instrument, because instrument is not in the call',
{ args }
);
}

const instrument = await this.dataSource.getInstrument(args.instrumentId);

if (!instrument) {
return rejection(
'Could not assign proposal/s to instrument, instrument not found',
'Cannot assign the proposal to the instrument because the proposals call has no such instrument',
{ agent, args }
);
}

const proposalPks = args.proposals.map((proposal) => proposal.primaryKey);

const result = await this.dataSource.assignProposalsToInstrument(
proposalPks,
args.instrumentId
);

if (result.proposalPks.length !== proposalPks.length) {
return rejection('Could not assign proposal/s to instrument', {
agent,
args,
});
}
for await (const proposalPk of proposalPks) {
const technicalReview = await this.reviewDataSource.getTechnicalReview(
proposalPk
);

if (technicalReview) {
await this.proposalDataSource.updateProposalTechnicalReviewer({
userId: instrument.managerUserId,
Expand All @@ -182,26 +184,19 @@ export default class InstrumentMutations {
}
}

return result;
}

@ValidateArgs(assignProposalsToInstrumentValidationSchema)
@Authorized([Roles.USER_OFFICER])
async assignProposalsToInstrument(
agent: UserWithRole | null,
args: AssignProposalsToInstrumentArgs
): Promise<ProposalPks | Rejection> {
const allProposalsAreOnSameCallAsInstrument =
await this.checkIfProposalsAreOnSameCallAsInstrument(args);
const result = await this.dataSource.assignProposalsToInstrument(
proposalPks,
args.instrumentId
);

if (!allProposalsAreOnSameCallAsInstrument) {
return rejection(
'One or more proposals can not be assigned to instrument, because instrument is not in the call',
{ args }
);
if (result.proposalPks.length !== proposalPks.length) {
return rejection('Could not assign proposal/s to instrument', {
agent,
args,
});
}

return this.assignProposalsToInstrumentHelper(agent, args);
return result;
}

@Authorized([Roles.USER_OFFICER])
Expand Down
13 changes: 13 additions & 0 deletions apps/user-office-backend/src/mutations/QuestionaryMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
isMatchingConstraints,
transformAnswerValueIfNeeded,
} from '../models/ProposalModelFunctions';
import { getQuestionDefinition } from '../models/questionTypes/QuestionRegistry';
import { rejection } from '../models/Rejection';
import { UserJWT, UserWithRole } from '../models/User';
import { AnswerTopicArgs } from '../resolvers/mutations/AnswerTopicMutation';
Expand Down Expand Up @@ -130,6 +131,18 @@ export default class QuestionaryMutations {
});
}

const definition = getQuestionDefinition(
questionTemplateRelation.question.dataType
);

if (definition.onBeforeSave) {
definition.onBeforeSave(
questionaryId,
questionTemplateRelation,
answer
);
}

await this.dataSource.updateAnswer(
questionaryId,
answer.questionId,
Expand Down

0 comments on commit 6833d53

Please sign in to comment.