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

VB-3518, additional support page #58

Merged
merged 3 commits into from
May 20, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 2 additions & 0 deletions server/@types/bapv.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ export type BookingJourneyData = {

// selected visitors for this visit
selectedVisitors?: VisitorInfoDto[]

visitorSupport?: string
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We've got a bit of a mix in the code of visitorSupport vs additionalSupport: should we standardise on one?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we send it as visitor support - that's why I chose this naming

}

export type FlashData = {
Expand Down
26 changes: 18 additions & 8 deletions server/@types/orchestration-api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -695,21 +695,21 @@ export interface components {
visitTimeSlot: components['schemas']['SessionTimeSlotDto']
}
PageVisitDto: {
/** Format: int64 */
totalElements?: number
/** Format: int32 */
totalPages?: number
/** Format: int64 */
totalElements?: number
first?: boolean
last?: boolean
content?: components['schemas']['VisitDto'][]
/** Format: int32 */
size?: number
content?: components['schemas']['VisitDto'][]
/** Format: int32 */
number?: number
sort?: components['schemas']['SortObject'][]
pageable?: components['schemas']['PageableObject']
/** Format: int32 */
numberOfElements?: number
pageable?: components['schemas']['PageableObject']
first?: boolean
last?: boolean
empty?: boolean
}
PageableObject: {
Expand Down Expand Up @@ -920,13 +920,18 @@ export interface components {
* @example 2020-11-01
*/
sessionDate: string
/**
* @description sessionTemplateReference
* @example v9d.7ed.7u
*/
sessionTemplateReference: string
sessionTimeSlot: components['schemas']['SessionTimeSlotDto']
/**
* @description Visit Restriction
* @example OPEN
* @enum {string}
*/
visitRestriction: 'OPEN' | 'CLOSED' | 'UNKNOWN'
visitRestriction: 'OPEN' | 'CLOSED'
}
GetDlqResult: {
/** Format: int32 */
Expand Down Expand Up @@ -2171,7 +2176,12 @@ export interface operations {
* @description Filter sessions by session restriction - OPEN or CLOSED, if prisoner has CLOSED it will use that
* @example CLOSED
*/
sessionRestriction: 'OPEN' | 'CLOSED'
sessionRestriction?: 'OPEN' | 'CLOSED'
/**
* @description List of visitors who require visit sessions
* @example 4729510,4729220
*/
visitors?: number[]
}
}
responses: {
Expand Down
15 changes: 15 additions & 0 deletions server/routes/bookingJourney/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import type { Services } from '../../services'
import SelectPrisonerController from './selectPrisonerController'
import SelectVisitorsController from './selectVisitorsController'
import DateAndTimeController from './selectDateAndTimeController'
import AdditionalSupportController from './selectAdditionalSupportController'
import MainContactController from './selectMainContactController'

export default function routes(services: Services): Router {
const router = Router()
Expand All @@ -18,6 +20,8 @@ export default function routes(services: Services): Router {
const selectPrisonerController = new SelectPrisonerController()
const selectVisitorsController = new SelectVisitorsController(services.bookerService, services.prisonService)
const dateAndTimeController = new DateAndTimeController(services.bookerService)
const additionalSupportController = new AdditionalSupportController(services.bookerService)
const mainContactController = new MainContactController(services.bookerService)

// TODO need session checks for each stage to validate what is in session - add middleware here to apply to all booking journey routes?

Expand All @@ -28,5 +32,16 @@ export default function routes(services: Services): Router {
postWithValidation('/select-visitors', selectVisitorsController.validate(), selectVisitorsController.submit())

get('/select-date-and-time', dateAndTimeController.view())

get('/select-additional-support', additionalSupportController.view())

postWithValidation(
'/select-additional-support',
additionalSupportController.validate(),
additionalSupportController.submit(),
)

get('/select-main-contact', mainContactController.view())

return router
}
169 changes: 169 additions & 0 deletions server/routes/bookingJourney/selectAdditionalSupport.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
import type { Express } from 'express'
import request from 'supertest'
import * as cheerio from 'cheerio'
import { SessionData } from 'express-session'
import { FieldValidationError } from 'express-validator'
import { appWithAllRoutes, flashProvider } from '../testutils/appSetup'
import { createMockBookerService, createMockPrisonService } from '../../services/testutils/mocks'
import TestData from '../testutils/testData'
import { FlashData } from '../../@types/bapv'

let app: Express

const bookerService = createMockBookerService()
const prisonService = createMockPrisonService()
let sessionData: SessionData

const url = '/book-a-visit/select-additional-support'

const bookerReference = TestData.bookerReference().value
const prisoner = TestData.prisonerInfoDto()
const prison = TestData.prisonDto()
const visitors = [
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
TestData.visitorInfoDto({ personId: 1, firstName: 'Visitor', lastName: 'One', dateOfBirth: '1980-02-03' }),
TestData.visitorInfoDto({ personId: 2, firstName: 'Visitor', lastName: 'Two', dateOfBirth: '1990-09-03' }),
TestData.visitorInfoDto({ personId: 3, firstName: 'Visitor', lastName: 'Three', dateOfBirth: '2024-03-01' }),
]

afterEach(() => {
jest.resetAllMocks()
jest.useRealTimers()
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
})

describe('Select additional support page', () => {
let flashData: FlashData

describe(`GET ${url}`, () => {
beforeEach(() => {
flashData = {}
flashProvider.mockImplementation((key: keyof FlashData) => flashData[key])

sessionData = {
booker: { reference: bookerReference, prisoners: [prisoner] },
bookingJourney: { allVisitors: visitors, selectedVisitors: visitors, prisoner, prison },
} as SessionData

app = appWithAllRoutes({ services: { bookerService, prisonService }, sessionData })
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
})

it('should render additional support page', () => {
return request(app)
.get(url)
.expect('Content-Type', /html/)
.expect(res => {
const $ = cheerio.load(res.text)
expect($('title').text()).toMatch(/^Any additional support needs\? -/)
expect($('[data-test="back-link"]').attr('href')).toBe('/')
expect($('h1').text()).toBe('Is additional support needed for any of the visitors?')

expect($('[data-test=prison-name]').text().trim()).toContain('Hewell (HMP)')

expect($('form[method=POST]').attr('action')).toBe('/book-a-visit/select-additional-support')

expect($('[data-test="continue-button"]').text().trim()).toBe('Continue')
})
})

it('should render validation errors', () => {
const validationError: FieldValidationError = {
type: 'field',
location: 'body',
path: 'additionalSupport',
value: [],
msg: 'Enter details of the request',
}

flashData = { errors: [validationError], formValues: { visitorIds: [] } }

return request(app)
.get(url)
.expect('Content-Type', /html/)
.expect(res => {
const $ = cheerio.load(res.text)
expect($('.govuk-error-summary a[href="#additionalSupport-error"]').text()).toBe(
'Enter details of the request',
)
expect($('#additionalSupport-error').text()).toContain('Enter details of the request')
})
})
})

describe(`POST ${url}`, () => {
beforeEach(() => {
sessionData = {
booker: {
reference: bookerReference,
prisoners: [prisoner],
},
bookingJourney: {
prisoner,
prison,
allVisitors: visitors,
selectedVisitors: [visitors[0], visitors[2]],
},
} as SessionData

app = appWithAllRoutes({ sessionData })
})

it('should should save entered additional support to session and redirect to main contact page', () => {
return request(app)
.post(url)
.send({ additionalSupportRequired: 'yes', additionalSupport: 'Wheelchair access' })
.expect(302)
.expect('Location', '/book-a-visit/select-main-contact')
.expect(() => {
expect(sessionData).toStrictEqual({
booker: {
reference: bookerReference,
prisoners: [prisoner],
},
bookingJourney: {
prisoner,
prison,
allVisitors: visitors,
selectedVisitors: [visitors[0], visitors[2]],
visitorSupport: 'Wheelchair access',
},
} as SessionData)
})
})

it('should set a validation error and redirect to original page when no options selected', () => {
const expectedFlashData: FlashData = {
errors: [
{
type: 'field',
location: 'body',
path: 'additionalSupportRequired',
value: undefined,
msg: 'No answer selected',
},
],
formValues: { additionalSupport: '' },
}

return request(app)
.post(url)
.expect(302)
.expect('Location', url)
.expect(() => {
expect(flashProvider).toHaveBeenCalledWith('errors', expectedFlashData.errors)
expect(flashProvider).toHaveBeenCalledWith('formValues', expectedFlashData.formValues)

expect(sessionData).toStrictEqual({
booker: {
reference: bookerReference,
prisoners: [prisoner],
},
bookingJourney: {
prisoner,
prison,
allVisitors: visitors,
selectedVisitors: [visitors[0], visitors[2]],
},
} as SessionData)
})
})
})
})
49 changes: 49 additions & 0 deletions server/routes/bookingJourney/selectAdditionalSupportController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { RequestHandler } from 'express'
import { ValidationChain, body, validationResult } from 'express-validator'
import { BookerService } from '../../services'

export default class AdditionalSupportController {
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
public constructor(private readonly bookerService: BookerService) {}
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved

public view(): RequestHandler {
return async (req, res) => {
res.render('pages/bookingJourney/selectAdditionalSupport', {
errors: req.flash('errors'),
formValues: req.flash('formValues')?.[0] || {},
booker: req.session.booker,
bookingJourney: req.session.bookingJourney,
})
}
}

public submit(): RequestHandler {
return async (req, res) => {
const { bookingJourney } = req.session
const errors = validationResult(req)

if (!errors.isEmpty()) {
req.flash('errors', errors.array() as [])
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
req.flash('formValues', req.body)
return res.redirect(`/book-a-visit/select-additional-support`)
}

bookingJourney.visitorSupport = req.body.additionalSupportRequired === 'no' ? '' : req.body.additionalSupport

return res.redirect('/book-a-visit/select-main-contact')
}
}

validate(): ValidationChain[] {
return [
body('additionalSupportRequired').isIn(['yes', 'no']).withMessage('No answer selected'),
body('additionalSupport')
.trim()
.if(body('additionalSupportRequired').equals('yes'))
.notEmpty()
.withMessage('Enter details of the request')
.bail()
.isLength({ min: 3, max: 512 })
.withMessage('Please enter at least 3 and no more than 512 characters'),
]
}
}
15 changes: 15 additions & 0 deletions server/routes/bookingJourney/selectMainContactController.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { RequestHandler } from 'express'
import { BookerService } from '../../services'

export default class MainContactController {
hutcheonb-moj marked this conversation as resolved.
Show resolved Hide resolved
public constructor(private readonly bookerService: BookerService) {}

public view(): RequestHandler {
return async (req, res) => {
res.render('pages/bookingJourney/selectMainContact', {
booker: req.session.booker,
bookingJourney: req.session.bookingJourney,
})
}
}
}
Loading
Loading