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

Create RP Record in CRM #2081

Merged
merged 7 commits into from
Dec 10, 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
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ describe('recurring payment entity', () => {
recurringPayment.agreementId = 'c9267c6e-573d-488b-99ab-ea18431fc472'
recurringPayment.publicId = '649-213'
recurringPayment.status = 1
recurringPayment.contactId = 'b3d33cln-2e83-ea11-a811-000d3a649213'
recurringPayment.activePermission = 'a5b24adf-2e83-ea11-a811-000d3a649213'

recurringPayment.bindToEntity(RecurringPayment.definition.relationships.contact, contact)
recurringPayment.bindToEntity(RecurringPayment.definition.relationships.activePermission, permission)
Expand Down Expand Up @@ -66,9 +64,7 @@ describe('recurring payment entity', () => {
endDate: '2019-12-15T00:00:00Z',
agreementId: 'c9267c6e-573d-488b-99ab-ea18431fc472',
publicId: '649-213',
status: 1,
activePermission: 'a5b24adf-2e83-ea11-a811-000d3a649213',
contactId: 'b3d33cln-2e83-ea11-a811-000d3a649213'
status: 1
})
)
})
Expand All @@ -93,8 +89,6 @@ describe('recurring payment entity', () => {
defra_agreementid: 'c9267c6e-573d-488b-99ab-ea18431fc472',
defra_publicid: '649-213',
statecode: 1,
_defra_activepermission_value: 'a5b24adf-2e83-ea11-a811-000d3a649213',
_defra_contact_value: 'b3d33cln-2e83-ea11-a811-000d3a649213',
'[email protected]': `$${contact.uniqueContentId}`,
'[email protected]': `$${permission.uniqueContentId}`
})
Expand All @@ -121,9 +115,7 @@ describe('recurring payment entity', () => {
endDate: '2019-12-15T00:00:00Z',
agreementId: 'c9267c6e-573d-488b-99ab-ea18431fc472',
publicId: '649-213',
status: 1,
activePermission: 'a5b24adf-2e83-ea11-a811-000d3a649213',
contactId: 'b3d33cln-2e83-ea11-a811-000d3a649213'
status: 1
})
)
})
Expand All @@ -143,8 +135,6 @@ describe('recurring payment entity', () => {
defra_agreementid: 'c9267c6e-573d-488b-99ab-ea18431fc472',
defra_publicid: '649-213',
statecode: 1,
_defra_activepermission_value: 'a5b24adf-2e83-ea11-a811-000d3a649213',
_defra_contact_value: 'b3d33cln-2e83-ea11-a811-000d3a649213',
'[email protected]': `$${contact.uniqueContentId}`,
'[email protected]': `$${permission.uniqueContentId}`
})
Expand Down
24 changes: 0 additions & 24 deletions packages/dynamics-lib/src/entities/recurring-payment.entity.js
Original file line number Diff line number Diff line change
Expand Up @@ -134,28 +134,4 @@ export class RecurringPayment extends BaseEntity {
set status (status) {
super._setState('status', status)
}

irisfaraway marked this conversation as resolved.
Show resolved Hide resolved
/**
* The ID of the associated contact
* @type {string}
*/
get contactId () {
return super._getState('contactId')
}

set contactId (contactId) {
super._setState('contactId', contactId)
}

/**
* The ID of the associated active permission
* @type {string}
*/
get activePermission () {
return super._getState('activePermission')
}

set activePermission (activePermission) {
super._setState('activePermission', activePermission)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Object {
"endDate": 2023-11-12T00:00:00.000Z,
"name": "Test Name",
"nextDueDate": 2023-11-02T00:00:00.000Z,
"publicId": "1234456",
"publicId": "abcdef99987",
"status": 0,
}
`;
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { findDueRecurringPayments } from '@defra-fish/dynamics-lib'
import { getRecurringPayments, processRecurringPayment } from '../recurring-payments.service.js'
import { findDueRecurringPayments, Permission } from '@defra-fish/dynamics-lib'
import { getRecurringPayments, processRecurringPayment, generateRecurringPaymentRecord } from '../recurring-payments.service.js'
import { createHash } from 'node:crypto'

jest.mock('@defra-fish/dynamics-lib', () => ({
...jest.requireActual('@defra-fish/dynamics-lib'),
Expand All @@ -8,6 +9,13 @@ jest.mock('@defra-fish/dynamics-lib', () => ({
findDueRecurringPayments: jest.fn()
}))

jest.mock('node:crypto', () => ({
createHash: jest.fn(() => ({
update: () => {},
digest: () => 'abcdef99987'
}))
}))

const dynamicsLib = jest.requireMock('@defra-fish/dynamics-lib')

const getMockRecurringPayment = () => ({
Expand Down Expand Up @@ -81,6 +89,22 @@ const getMockPermission = () => ({
})

describe('recurring payments service', () => {
const createSimpleSampleTransactionRecord = () => ({ payment: { recurring: true }, permissions: [{}] })
const createSamplePermission = overrides => {
const p = new Permission()
p.referenceNumber = 'ABC123'
p.issueDate = '2024-12-04T11:15:12Z'
p.startDate = '2024-12-04T11:45:12Z'
p.endDate = '2025-12-03T23:59:59.999Z'
p.stagingId = 'aaa-111-bbb-222'
p.isRenewal = false
p.isLicenseForYou = 1
for (const key in overrides) {
p[key] = overrides[key]
}
return p
}

beforeEach(jest.clearAllMocks)
describe('getRecurringPayments', () => {
it('should equal result of findDueRecurringPayments query', async () => {
Expand Down Expand Up @@ -123,7 +147,6 @@ describe('recurring payments service', () => {
cancelledReason: null,
endDate: new Date('2023-11-12'),
agreementId: '435678',
publicId: '1234456',
status: 0
}
},
Expand All @@ -133,5 +156,175 @@ describe('recurring payments service', () => {
const result = await processRecurringPayment(transactionRecord, contact)
expect(result.recurringPayment).toMatchSnapshot()
})

it.each(['abc-123', 'def-987'])('generates a publicId %s for the recurring payment', async samplePublicId => {
createHash.mockReturnValue({
update: () => {},
digest: () => samplePublicId
})
const result = await processRecurringPayment(createSimpleSampleTransactionRecord(), getMockContact())
expect(result.recurringPayment.publicId).toBe(samplePublicId)
})

it('passes the unique id of the entity to the hash.update function', async () => {
const update = jest.fn()
createHash.mockReturnValueOnce({
update,
digest: () => {}
})
const { recurringPayment } = await processRecurringPayment(createSimpleSampleTransactionRecord(), getMockContact())
expect(update).toHaveBeenCalledWith(recurringPayment.uniqueContentId)
})

it('hashes using sha256', async () => {
await processRecurringPayment(createSimpleSampleTransactionRecord(), getMockContact())
expect(createHash).toHaveBeenCalledWith('sha256')
})

it('uses base64 hash string', async () => {
const digest = jest.fn()
createHash.mockReturnValueOnce({
update: () => {},
digest
})
await processRecurringPayment(createSimpleSampleTransactionRecord(), getMockContact())
expect(digest).toHaveBeenCalledWith('base64')
})
})

describe('generateRecurringPaymentRecord', () => {
const createFinalisedSampleTransaction = (agreementId, permission) => ({
expires: 1732892402,
cost: 35.8,
isRecurringPaymentSupported: true,
permissions: [
{
permitId: 'permit-id-1',
licensee: {},
referenceNumber: '23211125-2WC3FBP-ABNDT8',
isLicenceForYou: true,
...permission
}
],
agreementId,
payment: {
amount: 35.8,
source: 'Gov Pay',
method: 'Debit card',
timestamp: '2024-11-22T15:00:45.922Z'
},
id: 'd26d646f-ed0f-4cf1-b6c1-ccfbbd611757',
dataSource: 'Web Sales',
transactionId: 'd26d646f-ed0f-4cf1-b6c1-ccfbbd611757',
status: { id: 'FINALISED' }
})

it.each([
[
Copy link
Member

Choose a reason for hiding this comment

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

It's a recipe for suffering, I know, but could we have some tests for leap years and daylight savings?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Good reminder, I'd meant to add these but then forgot

'same day start - next due on issue date plus one year minus ten days',
'iujhy7u8ijhy7u8iuuiuu8ie89',
{
startDate: '2024-11-22T15:30:45.922Z',
issueDate: '2024-11-22T15:00:45.922Z',
endDate: '2025-11-21T23:59:59.999Z'
},
'2025-11-12T00:00:00.000Z'
],
[
'next day start - next due on end date minus ten days',
'89iujhy7u8i87yu9iokjuij901',
{
startDate: '2024-11-23T00:00:00.000Z',
issueDate: '2024-11-22T15:00:45.922Z',
endDate: '2025-11-22T23:59:59.999Z'
},
'2025-11-12T00:00:00.000Z'
],
[
'starts ten days after issue - next due on issue date plus one year',
'9o8u7yhui89u8i9oiu8i8u7yhu',
{
startDate: '2024-11-22T00:00:00.000Z',
issueDate: '2024-11-12T15:00:45.922Z',
endDate: '2025-11-21T23:59:59.999Z'
},
'2025-11-12T00:00:00.000Z'
],
[
'starts twenty days after issue - next due on issue date plus one year',
'9o8u7yhui89u8i9oiu8i8u7yhu',
{
startDate: '2024-12-01T00:00:00.000Z',
issueDate: '2024-11-12T15:00:45.922Z',
endDate: '2025-01-30T23:59:59.999Z'
},
'2025-11-12T00:00:00.000Z'
],
[
"issued on 29th Feb '24, starts on 30th March '24 - next due on 28th Feb '25",
'hy7u8ijhyu78jhyu8iu8hjiujn',
{
startDate: '2024-03-30T00:00:00.000Z',
issueDate: '2024-02-29T12:38:24.123Z',
endDate: '2025-03-29T23:59:59.999Z'
},
'2025-02-28T00:00:00.000Z'
],
[
"issued on 30th March '25 at 1am, starts at 1:30am - next due on 20th March '26",
'jhy67uijhy67u87yhtgjui8u7j',
irisfaraway marked this conversation as resolved.
Show resolved Hide resolved
{
startDate: '2025-03-30T01:30:00.000Z',
issueDate: '2025-03-30T01:00:00.000Z',
endDate: '2026-03-29T23:59:59.999Z'
},
'2026-03-20T00:00:00.000Z'
]
])('creates record from transaction with %s', (_d, agreementId, permissionData, expectedNextDueDate) => {
const sampleTransaction = createFinalisedSampleTransaction(agreementId, permissionData)
const permission = createSamplePermission(permissionData)

const rpRecord = generateRecurringPaymentRecord(sampleTransaction, permission)

expect(rpRecord).toEqual(
expect.objectContaining({
payment: expect.objectContaining({
recurring: expect.objectContaining({
name: '',
nextDueDate: expectedNextDueDate,
cancelledDate: null,
cancelledReason: null,
endDate: permissionData.endDate,
agreementId,
status: 1
})
}),
permissions: expect.arrayContaining([permission])
})
)
})

it.each([
[
'start date is thirty one days after issue date',
{
startDate: '2024-12-14T00:00:00.000Z',
issueDate: '2024-11-12T15:00:45.922Z',
endDate: '2025-12-13T23:59:59.999Z'
}
],
[
'start date precedes issue date',
{
startDate: '2024-11-11T00:00:00.000Z',
issueDate: '2024-11-12T15:00:45.922Z',
endDate: '2025-11-10T23:59:59.999Z'
}
]
])('throws an error for invalid dates when %s', (_d, permission) => {
const sampleTransaction = createFinalisedSampleTransaction('hyu78ijhyu78ijuhyu78ij9iu6', permission)

expect(() => generateRecurringPaymentRecord(sampleTransaction)).toThrow('Invalid dates provided for permission')
})
})
})
Original file line number Diff line number Diff line change
@@ -1,22 +1,59 @@
import { executeQuery, findDueRecurringPayments, RecurringPayment } from '@defra-fish/dynamics-lib'
import { createHash } from 'node:crypto'
import { ADVANCED_PURCHASE_MAX_DAYS } from '@defra-fish/business-rules-lib'
import moment from 'moment'

export const getRecurringPayments = date => executeQuery(findDueRecurringPayments(date))

const getNextDueDate = (startDate, issueDate, endDate) => {
const mStart = moment(startDate)
if (mStart.isAfter(moment(issueDate)) && mStart.isSameOrBefore(moment(issueDate).add(ADVANCED_PURCHASE_MAX_DAYS, 'days'), 'day')) {
if (mStart.isSame(moment(issueDate), 'day')) {
return moment(startDate).add(1, 'year').subtract(10, 'days').startOf('day').toISOString()
}
if (mStart.isBefore(moment(issueDate).add(10, 'days'), 'day')) {
return moment(endDate).subtract(10, 'days').startOf('day').toISOString()
}
return moment(issueDate).add(1, 'year').startOf('day').toISOString()
}
throw new Error('Invalid dates provided for permission')
}

export const generateRecurringPaymentRecord = (transactionRecord, permission) => {
const [{ startDate, issueDate, endDate }] = transactionRecord.permissions
return {
payment: {
recurring: {
name: '',
nextDueDate: getNextDueDate(startDate, issueDate, endDate),
cancelledDate: null,
cancelledReason: null,
endDate,
agreementId: transactionRecord.agreementId,
status: 1
}
},
permissions: [permission]
}
}

/**
* Process a recurring payment instruction
* @param transactionRecord
* @returns {Promise<{recurringPayment: RecurringPayment | null}>}
*/
export const processRecurringPayment = async (transactionRecord, contact) => {
const hash = createHash('sha256')
if (transactionRecord.payment?.recurring) {
const recurringPayment = new RecurringPayment()
hash.update(recurringPayment.uniqueContentId)
recurringPayment.name = transactionRecord.payment.recurring.name
recurringPayment.nextDueDate = transactionRecord.payment.recurring.nextDueDate
recurringPayment.cancelledDate = transactionRecord.payment.recurring.cancelledDate
recurringPayment.cancelledReason = transactionRecord.payment.recurring.cancelledReason
recurringPayment.endDate = transactionRecord.payment.recurring.endDate
recurringPayment.agreementId = transactionRecord.payment.recurring.agreementId
recurringPayment.publicId = transactionRecord.payment.recurring.publicId
recurringPayment.publicId = hash.digest('base64')
recurringPayment.status = transactionRecord.payment.recurring.status
const [permission] = transactionRecord.permissions
recurringPayment.bindToEntity(RecurringPayment.definition.relationships.activePermission, permission)
Expand Down
Loading
Loading