@defra-fish/gafl-webapp-service 1.57.0-rc.3 → 1.57.0-rc.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,208 @@
1
+ import Joi from 'joi'
2
+ import { dateOfBirthValidator, startDateValidator, getDateErrorFlags } from '../validators.js'
3
+ import moment from 'moment-timezone'
4
+ const dateSchema = require('../../date.schema.js')
5
+
6
+ const setupMocks = () => {
7
+ Joi.originalAssert = Joi.assert
8
+ dateSchema.originalDateSchema = dateSchema.dateSchema
9
+ dateSchema.originalDateSchemaInput = dateSchema.dateSchemaInput
10
+
11
+ Joi.assert = jest.fn()
12
+ dateSchema.dateSchema = Symbol('dateSchema')
13
+ dateSchema.dateSchemaInput = jest.fn()
14
+ }
15
+
16
+ const tearDownMocks = () => {
17
+ Joi.assert = Joi.originalAssert
18
+ dateSchema.dateSchema = dateSchema.originalDateSchema
19
+ dateSchema.dateSchemaInput = dateSchema.originalDateSchemaInput
20
+ }
21
+
22
+ describe('dateOfBirth validator', () => {
23
+ beforeEach(jest.clearAllMocks)
24
+
25
+ const getSamplePayload = ({ day = '', month = '', year = '' } = {}) => ({
26
+ 'date-of-birth-day': day,
27
+ 'date-of-birth-month': month,
28
+ 'date-of-birth-year': year
29
+ })
30
+
31
+ it('throws an error for anyone over 120 years old', () => {
32
+ const invalidDoB = moment().subtract(120, 'years').subtract(1, 'day')
33
+ const samplePayload = getSamplePayload({
34
+ day: invalidDoB.format('DD'),
35
+ month: invalidDoB.format('MM'),
36
+ year: invalidDoB.format('YYYY')
37
+ })
38
+ expect(() => dateOfBirthValidator(samplePayload)).toThrow()
39
+ })
40
+
41
+ it('validates for anyone 120 years old', () => {
42
+ const validDoB = moment().subtract(120, 'years')
43
+ const samplePayload = getSamplePayload({
44
+ day: validDoB.format('DD'),
45
+ month: validDoB.format('MM'),
46
+ year: validDoB.format('YYYY')
47
+ })
48
+ expect(() => dateOfBirthValidator(samplePayload)).not.toThrow()
49
+ })
50
+
51
+ it.each([
52
+ ['today', moment()],
53
+ ['tomorrow', moment().add(1, 'day')],
54
+ ['in the future', moment().add(1, 'month')]
55
+ ])('throws an error for a date of birth %s', (_desc, invalidDoB) => {
56
+ const samplePayload = getSamplePayload({
57
+ day: invalidDoB.format('DD'),
58
+ month: invalidDoB.format('MM'),
59
+ year: invalidDoB.format('YYYY')
60
+ })
61
+ expect(() => dateOfBirthValidator(samplePayload)).toThrow()
62
+ })
63
+
64
+ it.each([
65
+ ['1-3-2004', '1', '3', '2004'],
66
+ ['12-1-1999', '12', '1', '1999'],
67
+ ['1-12-2006', '1', '12', '2006']
68
+ ])('handles single digit date %s', (_desc, day, month, year) => {
69
+ const samplePayload = getSamplePayload({
70
+ day,
71
+ month,
72
+ year
73
+ })
74
+ expect(() => dateOfBirthValidator(samplePayload)).not.toThrow()
75
+ })
76
+
77
+ it.each([
78
+ ['01', '03', '1994'],
79
+ ['10', '12', '2004']
80
+ ])('passes date of birth day (%s), month (%s) and year (%s) to dateSchemaInput', (day, month, year) => {
81
+ setupMocks()
82
+ dateOfBirthValidator(getSamplePayload({ day, month, year }))
83
+ expect(dateSchema.dateSchemaInput).toHaveBeenCalledWith(day, month, year)
84
+ tearDownMocks()
85
+ })
86
+
87
+ it('passes dateSchemaInput output and dateSchema to Joi.assert', () => {
88
+ setupMocks()
89
+ const dsi = Symbol('dsi')
90
+ dateSchema.dateSchemaInput.mockReturnValueOnce(dsi)
91
+ dateOfBirthValidator(getSamplePayload())
92
+ expect(Joi.assert).toHaveBeenCalledWith(dsi, dateSchema.dateSchema)
93
+ tearDownMocks()
94
+ })
95
+ })
96
+
97
+ describe('startDate validator', () => {
98
+ beforeEach(jest.clearAllMocks)
99
+
100
+ const getSamplePayload = ({ day = '', month = '', year = '' } = {}) => ({
101
+ 'licence-start-date-day': day,
102
+ 'licence-start-date-month': month,
103
+ 'licence-start-date-year': year,
104
+ 'licence-to-start': 'another-date'
105
+ })
106
+
107
+ it('throws an error for a licence starting before today', () => {
108
+ const invalidStartDate = moment().subtract(1, 'day')
109
+ const samplePayload = getSamplePayload({
110
+ day: invalidStartDate.format('DD'),
111
+ month: invalidStartDate.format('MM'),
112
+ year: invalidStartDate.format('YYYY')
113
+ })
114
+ expect(() => startDateValidator(samplePayload)).toThrow()
115
+ })
116
+
117
+ it('throws an error for a licence starting more than 30 days hence', () => {
118
+ const invalidStartDate = moment().add(31, 'days')
119
+ const samplePayload = getSamplePayload({
120
+ day: invalidStartDate.format('DD'),
121
+ month: invalidStartDate.format('MM'),
122
+ year: invalidStartDate.format('YYYY')
123
+ })
124
+ expect(() => startDateValidator(samplePayload)).toThrow()
125
+ })
126
+
127
+ it('validates for a date within the next 30 days', () => {
128
+ const validStartDate = moment().add(4, 'days')
129
+ const samplePayload = getSamplePayload({
130
+ day: validStartDate.format('DD'),
131
+ month: validStartDate.format('MM'),
132
+ year: validStartDate.format('YYYY')
133
+ })
134
+ expect(() => startDateValidator(samplePayload)).not.toThrow()
135
+ })
136
+
137
+ it.each([
138
+ ['1-3-2024', moment('2024-02-28')],
139
+ ['9-7-2024', moment('2024-07-08')]
140
+ ])('handles single digit date %s', (date, now) => {
141
+ jest.useFakeTimers()
142
+ jest.setSystemTime(now.toDate())
143
+
144
+ const [day, month, year] = date.split('-')
145
+ const samplePayload = getSamplePayload({
146
+ day,
147
+ month,
148
+ year
149
+ })
150
+ expect(() => startDateValidator(samplePayload)).not.toThrow()
151
+ jest.useRealTimers()
152
+ })
153
+
154
+ it.each([
155
+ ['01', '03', '1994'],
156
+ ['10', '12', '2004']
157
+ ])('passes start date day (%s), month (%s) and year (%s) to dateSchemaInput', (day, month, year) => {
158
+ setupMocks()
159
+ startDateValidator(getSamplePayload({ day, month, year }))
160
+ expect(dateSchema.dateSchemaInput).toHaveBeenCalledWith(day, month, year)
161
+ tearDownMocks()
162
+ })
163
+
164
+ it('passes dateSchemaInput output and dateSchema to Joi.assert', () => {
165
+ setupMocks()
166
+ const dsi = Symbol('dsi')
167
+ dateSchema.dateSchemaInput.mockReturnValueOnce(dsi)
168
+ startDateValidator(getSamplePayload())
169
+ expect(Joi.assert).toHaveBeenCalledWith(dsi, dateSchema.dateSchema)
170
+ tearDownMocks()
171
+ })
172
+
173
+ it('passes validation if licence is set to start after payment', () => {
174
+ const samplePayload = { 'licence-to-start': 'after-payment' }
175
+ expect(() => startDateValidator(samplePayload)).not.toThrow()
176
+ })
177
+
178
+ it('throws an error if licence-to-start is set to an invalid value', () => {
179
+ const samplePayload = { 'licence-to-start': '12th-of-never' }
180
+ expect(() => startDateValidator(samplePayload)).toThrow()
181
+ })
182
+ })
183
+
184
+ describe('getErrorFlags', () => {
185
+ it('sets all error flags to be false when there are no errors', () => {
186
+ const result = getDateErrorFlags()
187
+ expect(result).toEqual({ isDayError: false, isMonthError: false, isYearError: false })
188
+ })
189
+
190
+ it.each([
191
+ ['full-date', { isDayError: true, isMonthError: true, isYearError: true }],
192
+ ['day-and-month', { isDayError: true, isMonthError: true, isYearError: false }],
193
+ ['month-and-year', { isDayError: false, isMonthError: true, isYearError: true }],
194
+ ['day-and-year', { isDayError: true, isMonthError: false, isYearError: true }],
195
+ ['day', { isDayError: true, isMonthError: false, isYearError: false }],
196
+ ['month', { isDayError: false, isMonthError: true, isYearError: false }],
197
+ ['year', { isDayError: false, isMonthError: false, isYearError: true }],
198
+ ['invalid-date', { isDayError: true, isMonthError: true, isYearError: true }],
199
+ ['date-range', { isDayError: true, isMonthError: true, isYearError: true }],
200
+ ['non-numeric', { isDayError: true, isMonthError: true, isYearError: true }]
201
+ ])('when error is %s, should set %o in flags', (errorKey, expected) => {
202
+ const error = { [errorKey]: 'anything.at.all' }
203
+
204
+ const result = getDateErrorFlags(error)
205
+
206
+ expect(result).toEqual(expect.objectContaining(expected))
207
+ })
208
+ })
@@ -0,0 +1,65 @@
1
+ import Joi from 'joi'
2
+ import moment from 'moment'
3
+ import { ADVANCED_PURCHASE_MAX_DAYS, SERVICE_LOCAL_TIME } from '@defra-fish/business-rules-lib'
4
+ import { dateSchema, dateSchemaInput } from '../date.schema.js'
5
+
6
+ const MAX_AGE = 120
7
+ const LICENCE_TO_START_FIELD = 'licence-to-start'
8
+ const AFTER_PAYMENT = 'after-payment'
9
+ const ANOTHER_DATE = 'another-date'
10
+
11
+ const validateDate = (day, month, year, minDate, maxDate) => {
12
+ Joi.assert(dateSchemaInput(day, month, year), dateSchema)
13
+ const dateRange = moment(`${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`, 'YYYY-MM-DD')
14
+ .tz(SERVICE_LOCAL_TIME)
15
+ .startOf('day')
16
+ .toDate()
17
+ Joi.assert({ 'date-range': dateRange }, Joi.object({ 'date-range': Joi.date().min(minDate).max(maxDate) }))
18
+ }
19
+
20
+ export const dateOfBirthValidator = payload => {
21
+ const day = payload['date-of-birth-day']
22
+ const month = payload['date-of-birth-month']
23
+ const year = payload['date-of-birth-year']
24
+
25
+ const minDate = moment().tz(SERVICE_LOCAL_TIME).subtract(MAX_AGE, 'years').startOf('day').toDate()
26
+ const maxDate = moment().tz(SERVICE_LOCAL_TIME).subtract(1, 'day').startOf('day').toDate()
27
+ validateDate(day, month, year, minDate, maxDate)
28
+ }
29
+
30
+ export const startDateValidator = payload => {
31
+ Joi.assert(
32
+ { 'licence-to-start': payload[LICENCE_TO_START_FIELD] },
33
+ Joi.object({ 'licence-to-start': Joi.string().valid(AFTER_PAYMENT, ANOTHER_DATE).required() })
34
+ )
35
+ if (payload[LICENCE_TO_START_FIELD] === ANOTHER_DATE) {
36
+ const day = payload['licence-start-date-day']
37
+ const month = payload['licence-start-date-month']
38
+ const year = payload['licence-start-date-year']
39
+
40
+ const minDate = moment().tz(SERVICE_LOCAL_TIME).startOf('day').toDate()
41
+ const maxDate = moment().tz(SERVICE_LOCAL_TIME).add(ADVANCED_PURCHASE_MAX_DAYS, 'days').toDate()
42
+ validateDate(day, month, year, minDate, maxDate)
43
+ }
44
+ }
45
+
46
+ export const getDateErrorFlags = error => {
47
+ const errorFlags = { isDayError: false, isMonthError: false, isYearError: false }
48
+ const commonErrors = ['full-date', 'invalid-date', 'date-range', 'non-numeric']
49
+
50
+ if (error) {
51
+ const [errorKey] = Object.keys(error)
52
+
53
+ if (['day-and-month', 'day-and-year', 'day', ...commonErrors].includes(errorKey)) {
54
+ errorFlags.isDayError = true
55
+ }
56
+ if (['day-and-month', 'month-and-year', 'month', ...commonErrors].includes(errorKey)) {
57
+ errorFlags.isMonthError = true
58
+ }
59
+ if (['day-and-year', 'month-and-year', 'year', ...commonErrors].includes(errorKey)) {
60
+ errorFlags.isYearError = true
61
+ }
62
+ }
63
+
64
+ return errorFlags
65
+ }
@@ -1,36 +0,0 @@
1
- import pageRoute from '../../../../routes/page-route.js'
2
- import { addLanguageCodeToUri } from '../../../../processors/uri-helper.js'
3
- require('../route.js') // require rather than import to avoid lint error with unused variable
4
-
5
- jest.mock('../../../../routes/page-route.js', () => jest.fn())
6
- jest.mock('../../../../uri.js', () => ({
7
- IDENTIFY: { page: 'identify page', uri: 'identify uri' },
8
- AUTHENTICATE: { uri: Symbol('authenticate uri') }
9
- }))
10
- jest.mock('../../../../processors/uri-helper.js')
11
-
12
- describe('page route next', () => {
13
- const nextPage = pageRoute.mock.calls[0][3]
14
- beforeEach(jest.clearAllMocks)
15
-
16
- it('passes a function as the nextPage argument', () => {
17
- expect(typeof nextPage).toBe('function')
18
- })
19
-
20
- it('calls addLanguageCodeToUri', () => {
21
- nextPage()
22
- expect(addLanguageCodeToUri).toHaveBeenCalled()
23
- })
24
-
25
- it('passes request to addLanguageCodeToUri', () => {
26
- const request = Symbol('request')
27
- nextPage(request)
28
- expect(addLanguageCodeToUri).toHaveBeenCalledWith(request, expect.anything())
29
- })
30
-
31
- it('next page returns result of addLanguageCodeToUri', () => {
32
- const expectedResult = Symbol('add language code to uri')
33
- addLanguageCodeToUri.mockReturnValueOnce(expectedResult)
34
- expect(nextPage()).toBe(expectedResult)
35
- })
36
- })
@@ -1,38 +0,0 @@
1
- import { addLanguageCodeToUri } from '../../../../processors/uri-helper.js'
2
- import { getData } from '../route.js'
3
- import { NEW_TRANSACTION } from '../../../../uri.js'
4
-
5
- jest.mock('../../../../processors/uri-helper.js')
6
-
7
- const getMockRequest = referenceNumber => ({
8
- cache: () => ({
9
- helpers: {
10
- status: {
11
- getCurrentPermission: () => ({
12
- referenceNumber: referenceNumber
13
- })
14
- }
15
- }
16
- })
17
- })
18
-
19
- describe('getData', () => {
20
- it('addLanguageCodeToUri is called with the expected arguments', async () => {
21
- const request = getMockRequest('013AH6')
22
- await getData(request)
23
- expect(addLanguageCodeToUri).toHaveBeenCalledWith(request, NEW_TRANSACTION.uri)
24
- })
25
-
26
- it('getData returns correct URI', async () => {
27
- const expectedUri = Symbol('decorated uri')
28
- addLanguageCodeToUri.mockReturnValueOnce(expectedUri)
29
-
30
- const result = await getData(getMockRequest('013AH6'))
31
- expect(result.uri.new).toEqual(expectedUri)
32
- })
33
-
34
- it.each([['09F6VF'], ['013AH6'], ['LK563F']])('getData returns referenceNumber', async referenceNumber => {
35
- const result = await getData(getMockRequest(referenceNumber))
36
- expect(result.referenceNumber).toEqual(referenceNumber)
37
- })
38
- })