Skip to content

Commit

Permalink
connect QA to contracts
Browse files Browse the repository at this point in the history
  • Loading branch information
macrael committed Nov 1, 2023
1 parent 8baf735 commit 278cdec
Show file tree
Hide file tree
Showing 29 changed files with 274 additions and 141 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
BEGIN;

ALTER TABLE "Question" ADD COLUMN "contractID" TEXT;

-- AddForeignKey
ALTER TABLE "Question" ADD CONSTRAINT "Question_contractID_fkey" FOREIGN KEY ("contractID") REFERENCES "ContractTable"("id") ON DELETE RESTRICT ON UPDATE CASCADE;

-- migrate data over
UPDATE "Question" SET "contractID"="pkgID";

-- make not nullable, drop pkgID
ALTER TABLE "Question"
ALTER COLUMN "contractID" SET NOT NULL,
DROP CONSTRAINT "Question_pkgID_fkey",
DROP COLUMN "pkgID";

COMMIT;
55 changes: 28 additions & 27 deletions services/app-api/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ model HealthPlanPackageTable {
stateCode String
state State @relation(fields: [stateCode], references: [stateCode])
revisions HealthPlanRevisionTable[]
questions Question[]
}

model ProtoMigrationsTable {
Expand Down Expand Up @@ -41,9 +40,11 @@ model ContractTable {
mccrsID String?
stateCode String
state State @relation(fields: [stateCode], references: [stateCode])
state State @relation(fields: [stateCode], references: [stateCode])
stateNumber Int
questions Question[]
revisions ContractRevisionTable[]
// This relationship is a scam. We never call it in our code but Prisma
// requires that there be an inverse to RateRevision.draftContracts which we do use
Expand Down Expand Up @@ -72,8 +73,8 @@ model ContractRevisionTable {
contractID String
contract ContractTable @relation(fields: [contractID], references: [id])
rateRevisions RateRevisionsOnContractRevisionsTable[]
draftRates RateTable[]
rateRevisions RateRevisionsOnContractRevisionsTable[]
draftRates RateTable[]
unlockInfoID String?
unlockInfo UpdateInfoTable? @relation("unlockContractInfo", fields: [unlockInfoID], references: [id])
Expand Down Expand Up @@ -130,21 +131,21 @@ model RateRevisionTable {
submitInfoID String?
submitInfo UpdateInfoTable? @relation("submitRateInfo", fields: [submitInfoID], references: [id], onDelete: Cascade)
rateType RateType?
rateCapitationType RateCapitationType?
rateDocuments RateDocument[]
supportingDocuments RateSupportingDocument[]
rateDateStart DateTime? @db.Date
rateDateEnd DateTime? @db.Date
rateDateCertified DateTime? @db.Date
amendmentEffectiveDateStart DateTime? @db.Date
amendmentEffectiveDateEnd DateTime? @db.Date
rateProgramIDs String[]
rateCertificationName String?
certifyingActuaryContacts ActuaryContact[] @relation(name: "CertifyingActuaryOnRateRevision")
addtlActuaryContacts ActuaryContact[] @relation(name: "AddtlActuaryOnRateRevision")
actuaryCommunicationPreference ActuaryCommunication?
contractsWithSharedRateRevision ContractTable[] @relation(name: "SharedRateRevisions")
rateType RateType?
rateCapitationType RateCapitationType?
rateDocuments RateDocument[]
supportingDocuments RateSupportingDocument[]
rateDateStart DateTime? @db.Date
rateDateEnd DateTime? @db.Date
rateDateCertified DateTime? @db.Date
amendmentEffectiveDateStart DateTime? @db.Date
amendmentEffectiveDateEnd DateTime? @db.Date
rateProgramIDs String[]
rateCertificationName String?
certifyingActuaryContacts ActuaryContact[] @relation(name: "CertifyingActuaryOnRateRevision")
addtlActuaryContacts ActuaryContact[] @relation(name: "AddtlActuaryOnRateRevision")
actuaryCommunicationPreference ActuaryCommunication?
contractsWithSharedRateRevision ContractTable[] @relation(name: "SharedRateRevisions")
}

model RateRevisionsOnContractRevisionsTable {
Expand Down Expand Up @@ -291,12 +292,12 @@ model UserAudit {
}

model Question {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
pkgID String
pkg HealthPlanPackageTable @relation(fields: [pkgID], references: [id])
addedBy User @relation(fields: [addedByUserID], references: [id])
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @default(now()) @updatedAt
contractID String
contract ContractTable @relation(fields: [contractID], references: [id])
addedBy User @relation(fields: [addedByUserID], references: [id])
addedByUserID String
division Division
documents QuestionDocument[]
Expand Down Expand Up @@ -327,10 +328,10 @@ model QuestionResponse {
id String @id @default(uuid())
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
question Question @relation(fields: [questionID], references: [id])
addedBy User @relation(fields: [addedByUserID], references: [id])
questionID String
question Question @relation(fields: [questionID], references: [id])
addedByUserID String
addedBy User @relation(fields: [addedByUserID], references: [id])
documents QuestionResponseDocument[]
}

Expand Down
4 changes: 2 additions & 2 deletions services/app-api/src/domain-models/QuestionsType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Document = {

type Question = {
id: string
pkgID: string
contractID: string
createdAt: Date
addedBy: CMSUserType
documents: Document[]
Expand Down Expand Up @@ -40,7 +40,7 @@ type CreateQuestionPayload = {
}

type CreateQuestionInput = {
pkgID: string
contractID: string
documents: Document[]
}

Expand Down
10 changes: 4 additions & 6 deletions services/app-api/src/postgres/postgresStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ import {
insertManyUsers,
} from './user'
import {
findAllQuestionsByHealthPlanPackage,
findAllQuestionsByContract,
insertQuestion,
insertQuestionResponse,
} from './questionResponse'
Expand Down Expand Up @@ -139,9 +139,7 @@ type Store = {
user: CMSUserType
) => Promise<Question | StoreError>

findAllQuestionsByHealthPlanPackage: (
pkgID: string
) => Promise<Question[] | StoreError>
findAllQuestionsByContract: (pkgID: string) => Promise<Question[] | Error>

insertQuestionResponse: (
questionInput: InsertQuestionResponseArgs,
Expand Down Expand Up @@ -240,8 +238,8 @@ function NewPostgresStore(client: PrismaClient): Store {
findAllUsers: () => findAllUsers(client),
insertQuestion: (questionInput, user) =>
insertQuestion(client, questionInput, user),
findAllQuestionsByHealthPlanPackage: (pkgID) =>
findAllQuestionsByHealthPlanPackage(client, pkgID),
findAllQuestionsByContract: (pkgID) =>
findAllQuestionsByContract(client, pkgID),
insertQuestionResponse: (questionInput, user) =>
insertQuestionResponse(client, questionInput, user),
/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,15 @@ import type {
Question,
QuestionResponseType,
} from '../../domain-models'
import type { StoreError } from '../storeError'
import { convertPrismaErrorToStoreError } from '../storeError'

export async function findAllQuestionsByHealthPlanPackage(
export async function findAllQuestionsByContract(
client: PrismaClient,
pkgID: string
): Promise<Question[] | StoreError> {
contractID: string
): Promise<Question[] | Error> {
try {
const findResult = await client.question.findMany({
where: {
pkgID: pkgID,
contractID: contractID,
},
include: {
documents: {
Expand Down Expand Up @@ -49,6 +47,10 @@ export async function findAllQuestionsByHealthPlanPackage(

return questions
} catch (e: unknown) {
return convertPrismaErrorToStoreError(e)
if (e instanceof Error) {
return e
}
console.error('Unknown object thrown by Prisma', e)
return new Error('Unknown object thrown by Prisma')
}
}
2 changes: 1 addition & 1 deletion services/app-api/src/postgres/questionResponse/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { findAllQuestionsByHealthPlanPackage } from './findAllQuestionsByHealthPlanPackage'
export { findAllQuestionsByContract } from './findAllQuestionsByContract'
export { insertQuestion } from './insertQuestion'
export { convertToIndexQuestionsPayload } from './questionHelpers'
export { insertQuestionResponse } from './insertQuestionResponse'
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ export async function insertQuestion(
const result = await client.question.create({
data: {
id: uuidv4(),
pkg: {
contract: {
connect: {
id: questionInput.pkgID,
id: questionInput.contractID,
},
},
addedBy: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { protoToBase64 } from '../../../../app-web/src/common-code/proto/healthP
import statePrograms from '../../../../app-web/src/common-code/data/statePrograms.json'
import type { Resolvers } from '../../gen/gqlServer'
import type { Store } from '../../postgres'
import { isStoreError } from '../../postgres'
import { convertToIndexQuestionsPayload } from '../../postgres/questionResponse'
import { logError } from '../../logger'
import { setErrorAttributesOnActiveSpan } from '../attributeHelper'
Expand Down Expand Up @@ -59,15 +58,13 @@ export function healthPlanPackageResolver(
}
return state
},
questions: async (parent, args, context) => {
questions: async (parent, _args, context) => {
const { span } = context
const pkgID = parent.id
const result = await store.findAllQuestionsByHealthPlanPackage(
pkgID
)
const result = await store.findAllQuestionsByContract(pkgID)

if (isStoreError(result)) {
const errMessage = `Issue finding questions of type ${result.code} for package with id: ${pkgID}. Message: ${result.message}`
if (result instanceof Error) {
const errMessage = `Issue finding questions for package with id: ${pkgID}. Message: ${result.message}`
logError('indexQuestions', errMessage)
setErrorAttributesOnActiveSpan(errMessage, span)
throw new GraphQLError(errMessage, {
Expand Down
36 changes: 20 additions & 16 deletions services/app-api/src/resolvers/questionResponse/createQuestion.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import type { MutationResolvers } from '../../gen/gqlServer'
import { isCMSUser, packageStatus } from '../../domain-models'
import { isCMSUser } from '../../domain-models'
import { logError, logSuccess } from '../../logger'
import {
setErrorAttributesOnActiveSpan,
setSuccessAttributesOnActiveSpan,
} from '../attributeHelper'
import { ForbiddenError, UserInputError } from 'apollo-server-lambda'
import { NotFoundError } from '../../postgres'
import type { Store } from '../../postgres'
import { isStoreError } from '../../postgres'
import { GraphQLError } from 'graphql'
Expand Down Expand Up @@ -44,10 +45,20 @@ export function createQuestionResolver(
}

// Return error if package is not found or errors
const result = await store.findHealthPlanPackage(input.pkgID)
const contractResult = await store.findContractWithHistory(
input.contractID
)
if (contractResult instanceof Error) {
if (contractResult instanceof NotFoundError) {
const errMessage = `Package with id ${input.contractID} does not exist`
logError('createQuestion', errMessage)
setErrorAttributesOnActiveSpan(errMessage, span)
throw new GraphQLError(errMessage, {
extensions: { code: 'NOT_FOUND' },
})
}

if (isStoreError(result)) {
const errMessage = `Issue finding a package of type ${result.code}. Message: ${result.message}`
const errMessage = `Issue finding a package. Message: ${contractResult.message}`
logError('createQuestion', errMessage)
setErrorAttributesOnActiveSpan(errMessage, span)
throw new GraphQLError(errMessage, {
Expand All @@ -58,19 +69,12 @@ export function createQuestionResolver(
})
}

if (result === undefined) {
const errMessage = `Issue finding a package with id ${input.pkgID}. Message: Package with id ${input.pkgID} does not exist`
logError('createQuestion', errMessage)
setErrorAttributesOnActiveSpan(errMessage, span)
throw new GraphQLError(errMessage, {
extensions: { code: 'NOT_FOUND' },
})
}

// Return error if package status is DRAFT
const packageStats = packageStatus(result)

if (packageStats === 'DRAFT') {
// TODO we should have a helper for this
if (
contractResult.revisions.length === 1 &&
contractResult.revisions[0].submitInfo === undefined
) {
const errMessage = `Issue creating question for health plan package. Message: Cannot create question for health plan package in DRAFT status`
logError('createQuestion', errMessage)
setErrorAttributesOnActiveSpan(errMessage, span)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,25 @@ import {
createDBUsersWithFullData,
testCMSUser,
} from '../../testHelpers/userHelpers'
import { testLDService } from '../../testHelpers/launchDarklyHelpers'

describe('createQuestionResponse', () => {
const mockLDService = testLDService({ ['rates-db-refactor']: true })
const cmsUser = testCMSUser()
beforeAll(async () => {
//Inserting a new CMS user, with division assigned, in postgres in order to create the question to user relationship.
await createDBUsersWithFullData([cmsUser])
})

it('returns question response data', async () => {
const stateServer = await constructTestPostgresServer()
const stateServer = await constructTestPostgresServer({
ldService: mockLDService,
})
const cmsServer = await constructTestPostgresServer({
context: {
user: cmsUser,
},
ldService: mockLDService,
})

const submittedPkg = await createAndSubmitTestHealthPlanPackage(
Expand Down Expand Up @@ -58,7 +63,9 @@ describe('createQuestionResponse', () => {
})

it('returns an error when attempting to create response for a question that does not exist', async () => {
const stateServer = await constructTestPostgresServer()
const stateServer = await constructTestPostgresServer({
ldService: mockLDService,
})
const fakeID = 'abc-123'

const createdResponse = await stateServer.executeOperation({
Expand All @@ -84,11 +91,14 @@ describe('createQuestionResponse', () => {
})

it('returns an error if a cms user attempts to create a question response for a package', async () => {
const stateServer = await constructTestPostgresServer()
const stateServer = await constructTestPostgresServer({
ldService: mockLDService,
})
const cmsServer = await constructTestPostgresServer({
context: {
user: cmsUser,
},
ldService: mockLDService,
})
const submittedPkg = await createAndSubmitTestHealthPlanPackage(
stateServer
Expand Down
Loading

0 comments on commit 278cdec

Please sign in to comment.