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

CB2-11360: Create a new Lambda to process Cherished Transfers from DVLA #148

Merged
merged 16 commits into from
May 28, 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
"@aws-sdk/smithy-client": "^3.341.0",
"@aws-sdk/types": "^3.341.0",
"@aws-sdk/util-dynamodb": "^3.362.0",
"@dvsa/eslint-config-ts": "^3.0.0",
"@dvsa/eslint-config-ts": "^3.0.1",
"@types/aws-lambda": "^8.10.114",
"@types/jest": "^29.5.12",
"@types/lodash": "^4.14.195",
Expand Down
66 changes: 9 additions & 57 deletions src/handler/mot-update-vrm.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,27 @@
/* eslint-disable no-continue */
/* eslint-disable no-await-in-loop */
import { TechRecordType } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-verb';
import { SQSEvent } from 'aws-lambda';
import { MotCherishedTransfer } from '../models/motCherishedTransfer';
import { SearchCriteria } from '../models/search';
import { SQSEvent, SQSRecord } from 'aws-lambda';
import { SNSMessageBody } from '../models/updateVrm';
import { processCherishedTransfer } from '../processors/processCherishedTransfer';
import { searchByCriteria, updateVehicle } from '../services/database';
import { processRecord } from '../processors/processCherishedTransfer';
import { publish } from '../services/sns';
import { StatusCode } from '../util/enum';
import logger from '../util/logger';

export const handler = async (event: SQSEvent) => {
export const handler = async (event: SQSEvent): Promise<void> => {
logger.info('mot-update-vrm lambda triggered');

const SYSTEM_USER = 'CVS Automated Cherished Transfer';

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

// eslint-disable-next-line no-restricted-syntax
for (const cherishedTransfer of event.Records) {
const parsedRecord: MotCherishedTransfer = 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}`);
continue;
}

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

if (!allCurrentRecords.length) {
logger.info(`No current record found for VIN: ${parsedRecord.vin}`);
continue;
}

const matchingCurrentVrmRecords = allCurrentRecords.find((x) => x.primaryVrm === parsedRecord.vrm);

if (allCurrentRecords.length > 1) {
logger.info(`Duplicate current records found for VIN ${parsedRecord.vin}`);
} else if (matchingCurrentVrmRecords) {
logger.info(`No update needed for VRM ${parsedRecord.vrm} and VIN ${parsedRecord.vin}`);
} else {
const currentRecord = allCurrentRecords[0];
const { recordsToArchive, recordsToUpdate } = processCherishedTransfer(
{
msOid: SYSTEM_USER,
username: SYSTEM_USER,
email: '',
},
parsedRecord.vrm,
currentRecord as TechRecordType<'get'>,
);

await updateVehicle(recordsToArchive, recordsToUpdate);

logger.info(`Updated systemNumber ${currentRecord.systemNumber} with VRM ${parsedRecord.vrm}`);

recordsToUpdate.forEach((record) => recordsToSend.push({ ...record, userEmail: SYSTEM_USER }));
}
}

await Promise.all(event.Records.map(processRecordWrapper));
if (recordsToSend.length) {
await publish(JSON.stringify(recordsToSend), process.env.VRM_TRANSFERRED_ARN ?? '');
}

logger.info('All records processed in SQS event');
} catch (error) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
logger.error(`an error occurred during processing mot update vrm ${error}`);
logger.error(`An error occurred during processing mot update vrm: ${(error as Error).message}`);
throw error;
}
};
61 changes: 60 additions & 1 deletion src/processors/processCherishedTransfer.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import { TechRecordType } from '@dvsa/cvs-type-definitions/types/v3/tech-record/tech-record-verb';
import { SQSRecord } from 'aws-lambda';
import { setCreatedAuditDetails, setLastUpdatedAuditDetails } from '../services/audit';
import { UserDetails } from '../services/user';
import { StatusCode } from '../util/enum';
import { MotCherishedTransfer } from '../models/motCherishedTransfer';
import { getBySystemNumberAndCreatedTimestamp, searchByCriteria, updateVehicle } from '../services/database';
import { SearchCriteria } from '../models/search';
import logger from '../util/logger';

const SYSTEM_USER = 'CVS Automated Cherished Transfer';

export const processCherishedTransfer = (
userDetails: UserDetails,
Expand Down Expand Up @@ -52,12 +59,16 @@ export const processCherishedTransfer = (
StatusCode.ARCHIVED,
);

const newStatusCode = recipientRecord.techRecord_statusCode === StatusCode.CURRENT
? StatusCode.CURRENT
: recipientRecord.techRecord_statusCode as StatusCode;

const updatedRecipientNewRecord = setCreatedAuditDetails(
newRecord,
userDetails.username,
userDetails.msOid,
new Date().toISOString(),
recipientRecord.techRecord_statusCode as StatusCode,
newStatusCode,
);
if (updatedRecipientNewRecord.techRecord_vehicleType !== 'trl') {
updatedRecipientNewRecord.primaryVrm = newVrm.toUpperCase();
Expand All @@ -78,3 +89,51 @@ const formatSecondaryVrms = (record:TechRecordType<'get'>): Array<string> | unde
}
return undefined;
};

export 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) {
logger.info(`No current record found for VIN: ${parsedRecord.vin}`);
return [];
}

if (allCurrentRecords.length > 1) {
logger.info(`Duplicate current records found for VIN ${parsedRecord.vin}`);
return [];
}
const currentRecord = allCurrentRecords[0];
if (currentRecord.primaryVrm === parsedRecord.vrm) {
logger.info(`No update needed for VRM ${parsedRecord.vrm} and VIN ${parsedRecord.vin}`);
return [];
}

const completeTechRecord: TechRecordType<'get'> = await getBySystemNumberAndCreatedTimestamp(
currentRecord.systemNumber,
currentRecord.createdTimestamp,
);

const {
recordsToArchive,
recordsToUpdate,
} = processCherishedTransfer(
{
msOid: SYSTEM_USER,
username: SYSTEM_USER,
email: '',
},
parsedRecord.vrm,
completeTechRecord,
);
await updateVehicle(recordsToArchive, recordsToUpdate);
logger.info(`Updated systemNumber ${currentRecord.systemNumber} with VRM ${parsedRecord.vrm}`);

return recordsToUpdate;
};
6 changes: 5 additions & 1 deletion tests/unit/handler/mot-update-vrm.unit.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
/* eslint-disable import/first */

const mockGetBySystemNumberAndCreatedTimestamp = jest.fn();
const mockSearchByCriteria = jest.fn();
const mockUpdateVehicle = jest.fn();
const mockPublish = jest.fn();
Expand All @@ -12,6 +14,7 @@ import updateEvent from '../../resources/mot-vrm-update-event.json';
jest.mock('../../../src/services/database.ts', () => ({
searchByCriteria: mockSearchByCriteria,
updateVehicle: mockUpdateVehicle,
getBySystemNumberAndCreatedTimestamp: mockGetBySystemNumberAndCreatedTimestamp,
}));

jest.mock('../../../src/services/sns', () => ({
Expand Down Expand Up @@ -121,6 +124,7 @@ describe('Test Mot Update Vrm Lambda Function', () => {
},
]);

mockGetBySystemNumberAndCreatedTimestamp.mockResolvedValueOnce({});
mockUpdateVehicle.mockResolvedValue(true);

const loggerSpy = jest.spyOn(logger, 'info');
Expand Down Expand Up @@ -154,7 +158,7 @@ describe('Test Mot Update Vrm Lambda Function', () => {
]);

mockUpdateVehicle.mockResolvedValue(true);

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

updateEventMultiple.Records[0].body = JSON.stringify({
Expand Down
Loading