Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: confirm registration via graphql api #288

Merged
merged 13 commits into from
Nov 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ data

.history

graphql.schema.json
*.tar.gz
.secrets
.env*
5 changes: 5 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"apollographql.vscode-apollo"
]
}
8 changes: 8 additions & 0 deletions apollo.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"client": {
"service": {
"name": "@opencrvs/gateway",
"url": "http://localhost:7070/graphql"
}
}
}
19 changes: 0 additions & 19 deletions codegen.yml

This file was deleted.

9 changes: 0 additions & 9 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,8 @@
"sort-translations": "cross-env NODE_ENV=development ts-node -r tsconfig-paths/register src/sort-translations.ts"
},
"devDependencies": {
"@graphql-codegen/add": "^3.1.1",
"@graphql-codegen/cli": "^3.3.1",
"@graphql-codegen/introspection": "^3.0.1",
"@graphql-codegen/typescript": "^3.0.4",
"@graphql-codegen/typescript-operations": "^3.0.4",
"@inquirer/editor": "^1.2.13",
"@octokit/core": "4.2.1",
"@types/google-libphonenumber": "^7.4.23",
"@types/handlebars": "^4.1.0",
"@types/hapi__inert": "5.2.1",
"@types/inquirer": "^9.0.7",
Expand Down Expand Up @@ -91,9 +85,6 @@
"dotenv": "^16.4.5",
"envalid": "^8.0.0",
"esbuild": "^0.18.9",
"google-libphonenumber": "^3.2.32",
"graphql": "^16.3.0",
"graphql-tag": "^2.12.6",
"handlebars": "^4.7.7",
"hapi-auth-jwt2": "10.4.0",
"hapi-pino": "^9.0.0",
Expand Down
33 changes: 24 additions & 9 deletions src/api/event-registration/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,13 @@
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
*/
import * as Hapi from '@hapi/hapi'
import fetch from 'node-fetch'
import { logger } from '@countryconfig/logger'
import { CONFIRM_REGISTRATION_URL } from '@countryconfig/constants'
import { createUniqueRegistrationNumberFromBundle } from '@countryconfig/api/event-registration/service'
import { badImplementation } from '@hapi/boom'
import {
confirmRegistration
// rejectRegistration
} from '@countryconfig/utils/gateway-api'

export async function eventRegistrationHandler(
request: Hapi.Request,
Expand All @@ -33,15 +35,28 @@ export async function eventRegistrationHandler(
const bundle = request.payload as fhir.Bundle

const eventRegistrationIdentifiersResponse =
await createUniqueRegistrationNumberFromBundle(bundle)
createUniqueRegistrationNumberFromBundle(bundle)

await fetch(CONFIRM_REGISTRATION_URL, {
method: 'POST',
body: JSON.stringify(eventRegistrationIdentifiersResponse),
headers: request.headers
})
await confirmRegistration(
eventRegistrationIdentifiersResponse.compositionId,
eventRegistrationIdentifiersResponse,
{
headers: request.headers
}
)
} catch (err) {
// IF ANY ERROR OCCURS IN THIS API, THE REGISTRATION WILL BE REJECTED AND MUST BE RE-SUBMITTED BY A REGISTRAR ONCE THE ISSUE IS RESOLVED
// If the confirm registration endpoint throws an error, the registration will be retried through country-config
// If you don't want the registration to retry, you can call `rejectRegistration` from here and return 202 Accepted

// await confirmRegistration(
// eventRegistrationIdentifiersResponse.compositionId,
// {
// reason: 'other', // Refer to the GraphQL schema for other options
// comment: 'The comment that will be visible on audit log.'
// },
// { headers: request.headers }
// )

logger.error(err)

const boomError = badImplementation()
Expand Down
7 changes: 3 additions & 4 deletions src/api/event-registration/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ function generateRegistrationNumber(trackingId: string): string {
return brn
}

export async function createUniqueRegistrationNumberFromBundle(
bundle: fhir.Bundle
) {
export function createUniqueRegistrationNumberFromBundle(bundle: fhir.Bundle) {
const taskResource = getTaskResource(bundle)

if (!taskResource || !taskResource.extension) {
Expand All @@ -36,11 +34,12 @@ export async function createUniqueRegistrationNumberFromBundle(
}

const trackingId = getTrackingIdFromTaskResource(taskResource)
const compositionId = getCompositionId(bundle)

return {
trackingId,
compositionId,
registrationNumber: generateRegistrationNumber(trackingId),
compositionId: getCompositionId(bundle),
...(taskResource.code?.coding?.[0].code === 'BIRTH' && {
// Some countries desire to create multiple identifiers for citizens at the point of birth registration using external systems.
// OpenCRVS supports up to 3 additional, custom identifiers that can be created
Expand Down
1 change: 0 additions & 1 deletion src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,5 @@ export const APPLICATION_CONFIG_URL = env.APPLICATION_CONFIG_URL
export const SENTRY_DSN = env.SENTRY_DSN
export const CHECK_INVALID_TOKEN = env.CHECK_INVALID_TOKEN

export const CONFIRM_REGISTRATION_URL = env.CONFIRM_REGISTRATION_URL
export const PRODUCTION = env.isProd
export const QA_ENV = env.QA_ENV
3 changes: 2 additions & 1 deletion src/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ export const env = cleanEnv(process.env, {
LOGIN_URL: url({ devDefault: 'http://localhost:3020/' }),
CLIENT_APP_URL: url({ devDefault: 'http://localhost:3000/' }),
FHIR_URL: url({ devDefault: 'http://localhost:3447/fhir' }),
COUNTRY_CONFIG_HOST: str({ devDefault: '0.0.0.0' }),
COUNTRY_CONFIG_HOST: str({ default: '0.0.0.0' }),
COUNTRY_CONFIG_PORT: port({ default: 3040 }),
AUTH_URL: url({ devDefault: 'http://localhost:4040' }),
COUNTRY_CONFIG_URL: url({ devDefault: 'http://localhost:3040' }),
APPLICATION_CONFIG_URL: url({ devDefault: 'http://localhost:2021/' }),
SENTRY_DSN: str({ default: undefined }),
CHECK_INVALID_TOKEN: bool({
default: true,
devDefault: false,
desc: 'Check if the token has been invalidated in the auth service before it has expired'
}),
Expand Down
6 changes: 3 additions & 3 deletions src/form/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,12 @@ import { birthForm } from './birth'
import { deathForm } from './death'
import { marriageForm } from './marriage'
import { IForms, Event } from './types/types'
import { fetchUserLocationHierarchy } from '@countryconfig/utils/users'
import { fetchUserLocationHierarchy } from '@countryconfig/utils/gateway-api'

export async function formHandler(req: Request): Promise<IForms> {
const addressHierarchy = await fetchUserLocationHierarchy(
req.headers.authorization,
req.auth.credentials.sub as string
req.auth.credentials.sub as string,
{ headers: req.headers }
)
// ====================== NOTE REGARDING MIGRATING FROM OPNCRVS v1.2 OR EARLIER ======================

Expand Down
127 changes: 127 additions & 0 deletions src/utils/gateway-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* OpenCRVS is also distributed under the terms of the Civil Registration
* & Healthcare Disclaimer located at http://opencrvs.org/license.
*
* Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
*/
import { GATEWAY_URL } from '@countryconfig/constants'
import { URL } from 'url'
import fetch from 'node-fetch'

const GRAPHQL_GATEWAY_URL = new URL('graphql', GATEWAY_URL)

/** Communicates with opencrvs-core's GraphQL gateway */
const post = async <T = any>({
query,
variables,
headers
}: {
query: string
variables: Record<string, any>
headers: Record<string, any>
}) => {
const response = await fetch(GRAPHQL_GATEWAY_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...headers
},
body: JSON.stringify({
variables,
query
})
})

if (!response.ok) {
throw new Error(`not ok: ${await response.text()}`)
}

return response.json() as Promise<{ data: T }>
}

export const confirmRegistration = (
id: string,
variables: {
childIdentifiers?: Array<{ type: string; value: string }>
registrationNumber: string
},
{ headers }: { headers: Record<string, any> }
) =>
post({
query: /* GraphQL */ `
mutation confirmRegistration(
$id: ID!
$details: ConfirmRegistrationInput!
) {
confirmRegistration(id: $id, details: $details)
}
`,
variables: {
id,
details: {
identifiers: variables.childIdentifiers,
registrationNumber: variables.registrationNumber
}
},
headers
})

export const rejectRegistration = (
id: string,
{ reason, comment }: { reason: string; comment: string },
{ headers }: { headers: Record<string, any> }
) =>
post({
query: /* GraphQL */ `
mutation rejectRegistration(
$id: ID!
$details: RejectRegistrationInput!
) {
rejectRegistration(id: $id, details: $details)
}
`,
variables: {
id,
details: {
reason,
comment
}
},
headers
})

type GetUser = {
getUser: {
primaryOffice: {
hierarchy: Array<{
id: string
}>
}
}
}

export const fetchUserLocationHierarchy = async (
userId: string,
{ headers }: { headers: Record<string, any> }
) => {
const res = await post<GetUser>({
query: /* GraphQL */ `
query fetchUser($userId: String!) {
getUser(userId: $userId) {
primaryOffice {
hierarchy {
id
}
}
}
}
`,
variables: { userId },
headers
})
return res.data.getUser.primaryOffice.hierarchy.map(({ id }) => id)
}
25 changes: 7 additions & 18 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@

import fetch from 'node-fetch'
import { APPLICATION_CONFIG_URL, FHIR_URL } from '@countryconfig/constants'
import { callingCountries } from 'country-data'
import csv2json from 'csv2json'
import { createReadStream } from 'fs'
import fs from 'fs'
import { PhoneNumberFormat, PhoneNumberUtil } from 'google-libphonenumber'
import { URL } from 'url'
import { build } from 'esbuild'
import { memoize } from 'lodash'
Expand Down Expand Up @@ -64,9 +62,15 @@ export interface IApplicationConfigResponse {
}

export function getCompositionId(resBody: fhir.Bundle) {
return resBody.entry
const id = resBody.entry
?.map((e) => e.resource)
.find((res) => res?.resourceType === 'Composition')?.id

if (!id) {
throw new Error('Could not find composition id in FHIR Bundle')
}

return id
}

export function getTaskResource(
Expand Down Expand Up @@ -160,21 +164,6 @@ export async function updateResourceInHearth(resource: fhir.ResourceBase) {
return res.text()
}

export const convertToMSISDN = (phone: string, countryAlpha3: string) => {
const countryCode = callingCountries[countryAlpha3.toUpperCase()].alpha2

const phoneUtil = PhoneNumberUtil.getInstance()
const number = phoneUtil.parse(phone, countryCode)

return (
phoneUtil
.format(number, PhoneNumberFormat.INTERNATIONAL)
// libphonenumber adds spaces and dashes to phone numbers,
// which we do not want to keep for now
.replace(/[\s-]/g, '')
)
}

const csvStringify = promisify<Array<Record<string, any>>, Options>(stringify)
export async function writeJSONToCSV(
filename: string,
Expand Down
Loading
Loading