Skip to content

Commit

Permalink
feat(CB2-11360): remove logic for generating adr cert
Browse files Browse the repository at this point in the history
  • Loading branch information
Daniel-Searle committed May 24, 2024
1 parent caf46b1 commit 4cdf8ea
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 52 deletions.
52 changes: 6 additions & 46 deletions src/handler/mot-update-vrm.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
import { TechRecordType } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-verb';
import { SQSEvent, SQSRecord } from 'aws-lambda';
import { ADRCertificateDetails } from '@dvsa/cvs-type-definitions/types/v3/tech-record/get/hgv/complete';
import { ADRCertificateTypes } from '@dvsa/cvs-type-definitions/types/v3/tech-record/enums/adrCertificateTypes.enum';
import { TechRecordType as TechRecordTypeByVehicle } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-vehicle-type';
import { MotCherishedTransfer } from '../models/motCherishedTransfer';
import { SearchCriteria } from '../models/search';
import { SNSMessageBody } from '../models/updateVrm';
Expand All @@ -11,11 +8,6 @@ import { getBySystemNumberAndCreatedTimestamp, searchByCriteria, updateVehicle }
import { publish } from '../services/sns';
import { StatusCode } from '../util/enum';
import logger from '../util/logger';
import { DocumentName, SQSRequestBody } from '../models/sqsPayload';
import { validateAdrCertificateDetails } from '../validators/adrCertificate';
import { addHttpHeaders } from '../util/httpHeaders';
import { formatTechRecord } from '../util/formatTechRecord';
import { addToSqs } from '../services/sqs';

const SYSTEM_USER = 'CVS Automated Cherished Transfer';

Expand All @@ -24,14 +16,12 @@ export const handler = async (event: SQSEvent): Promise<void> => {

try {
const recordsToSend: SNSMessageBody[] = [];

const processRecordWrapper = async (record: SQSRecord): Promise<void> => {
const result = await processRecord(record);
recordsToSend.push(...result);
};

await Promise.all(event.Records.map(processRecordWrapper));

if (recordsToSend.length) {
await publish(JSON.stringify(recordsToSend), process.env.VRM_TRANSFERRED_ARN ?? '');
}
Expand All @@ -43,15 +33,14 @@ export const handler = async (event: SQSEvent): Promise<void> => {
}
};

const processRecord = async (cherishedTransfer: SQSRecord): Promise<SNSMessageBody[]> => {
const processRecord = async (cherishedTransfer: SQSRecord) => {
const parsedRecord = JSON.parse(cherishedTransfer.body) as MotCherishedTransfer;
const allRecords = await searchByCriteria(SearchCriteria.VIN, parsedRecord.vin);

if (!allRecords.length) {
logger.info(`No record found for VIN: ${parsedRecord.vin}`);
return [];
}

const allCurrentRecords = allRecords.filter(({ techRecord_statusCode }) => techRecord_statusCode === StatusCode.CURRENT);

if (!allCurrentRecords.length) {
Expand All @@ -74,7 +63,10 @@ const processRecord = async (cherishedTransfer: SQSRecord): Promise<SNSMessageBo
currentRecord.createdTimestamp,
);

const { recordsToArchive, recordsToUpdate } = processCherishedTransfer(
const {
recordsToArchive,
recordsToUpdate,
} = processCherishedTransfer(
{
msOid: SYSTEM_USER,
username: SYSTEM_USER,
Expand All @@ -86,37 +78,5 @@ const processRecord = async (cherishedTransfer: SQSRecord): Promise<SNSMessageBo
await updateVehicle(recordsToArchive, recordsToUpdate);
logger.info(`Updated systemNumber ${currentRecord.systemNumber} with VRM ${parsedRecord.vrm}`);

const newAdrCertificate = createAdrCertificate(currentRecord.systemNumber);
const adrCertificateDetailsErrors = validateAdrCertificateDetails(newAdrCertificate);
if (adrCertificateDetailsErrors) {
addHttpHeaders(adrCertificateDetailsErrors);
return [];
}

const formattedTechRecord = formatTechRecord<TechRecordTypeByVehicle<'hgv' | 'trl' | 'lgv'>>(completeTechRecord);
formattedTechRecord.techRecord_adrPassCertificateDetails = formattedTechRecord.techRecord_adrPassCertificateDetails
? [...formattedTechRecord.techRecord_adrPassCertificateDetails, newAdrCertificate]
: [newAdrCertificate];

const adrCertSqsPayload: SQSRequestBody = {
techRecord: formattedTechRecord,
adrCertificate: newAdrCertificate,
documentName: DocumentName.ADR_PASS_CERTIFICATE,
recipientEmailAddress: '',
};

await addToSqs(adrCertSqsPayload, process.env.DOC_GEN_SQS_QUEUE ?? '');
return recordsToUpdate.map((record) => ({ ...record, userEmail: SYSTEM_USER }));
};

const createAdrCertificate = (systemNumber: string): ADRCertificateDetails => {
const generatedTimestamp = new Date().toISOString();
const certificateId = `adr_pass_${systemNumber}_${generatedTimestamp}`;

return {
createdByName: SYSTEM_USER,
certificateType: 'PASS' as ADRCertificateTypes,
generatedTimestamp,
certificateId,
};
return recordsToUpdate;
};
52 changes: 46 additions & 6 deletions tests/unit/handler/mot-update-vrm.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@ const mockGetBySystemNumberAndCreatedTimestamp = jest.fn();
const mockSearchByCriteria = jest.fn();
const mockUpdateVehicle = jest.fn();
const mockPublish = jest.fn();
const mockSqs = jest.fn();

import { handler } from '../../../src/handler/mot-update-vrm';
import { StatusCode } from '../../../src/util/enum';
import logger from '../../../src/util/logger';
import updateEventMultiple from '../../resources/mot-vrm-update-event-multiple.json';
import updateEvent from '../../resources/mot-vrm-update-event.json';

jest.mock('../../../src/services/database.ts', () => ({
Expand All @@ -21,10 +21,6 @@ jest.mock('../../../src/services/sns', () => ({
publish: mockPublish,
}));

jest.mock('../../../src/services/sqs', () => ({
addToSqs: mockSqs,
}));

describe('Test Mot Update Vrm Lambda Function', () => {
beforeEach(() => {
jest.resetAllMocks();
Expand Down Expand Up @@ -120,7 +116,6 @@ describe('Test Mot Update Vrm Lambda Function', () => {
});

it('should log when there is a current record with a matching VIN and no matching VRM', async () => {
mockSqs.mockResolvedValueOnce(undefined);
mockSearchByCriteria.mockReturnValue([{
primaryVrm: '1',
vin: '2',
Expand All @@ -145,4 +140,49 @@ describe('Test Mot Update Vrm Lambda Function', () => {
expect(mockUpdateVehicle).toHaveBeenCalled();
expect(mockPublish).toHaveBeenCalled();
});

it('should run three events, pass one, fail one, pass the third one', async () => {
mockSearchByCriteria.mockReturnValueOnce([{
primaryVrm: '1',
vin: '2',
techRecord_statusCode: StatusCode.CURRENT,
systemNumber: '15',
},
]).mockReturnValueOnce([]).mockReturnValue([
{
primaryVrm: '10',
vin: '5',
techRecord_statusCode: StatusCode.CURRENT,
systemNumber: '16',
},
]);

mockUpdateVehicle.mockResolvedValue(true);
mockGetBySystemNumberAndCreatedTimestamp.mockResolvedValue({});
const loggerSpy = jest.spyOn(logger, 'info');

updateEventMultiple.Records[0].body = JSON.stringify({
vin: '2',
vrm: '3',
});

updateEventMultiple.Records[1].body = JSON.stringify({
vin: '3',
vrm: '4',
});

updateEventMultiple.Records[2].body = JSON.stringify({
vin: '5',
vrm: '6',
});

await handler(updateEventMultiple);

expect(loggerSpy).toHaveBeenCalledWith('Updated systemNumber 15 with VRM 3');
expect(loggerSpy).toHaveBeenCalledWith('No record found for VIN: 3');
expect(loggerSpy).toHaveBeenCalledWith('Updated systemNumber 16 with VRM 6');
expect(mockUpdateVehicle).toHaveBeenCalledTimes(2);
expect(mockPublish).toHaveBeenCalled();
expect(loggerSpy).toHaveBeenLastCalledWith('All records processed in SQS event');
});
});

0 comments on commit 4cdf8ea

Please sign in to comment.