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

chore:[#186705729] add query find user by business name #9283

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions api/src/api/externalEndpointRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe("externalEndpointRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};
stubAddNewsletter = jest.fn();
stubAddToUserTesting = jest.fn();
Expand Down
1 change: 1 addition & 0 deletions api/src/api/formationRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ describe("formationRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};
app = setupExpress(false);
app.use(formationRouterFactory(stubFormationClient, stubDynamoDataClient, { shouldSaveDocuments: true }));
Expand Down
1 change: 1 addition & 0 deletions api/src/api/licenseStatusRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ describe("licenseStatusRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};
stubDynamoDataClient.put.mockImplementation((userData) => {
return Promise.resolve(userData);
Expand Down
1 change: 1 addition & 0 deletions api/src/api/selfRegRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ describe("selfRegRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};

stubSelfRegClient = {
Expand Down
1 change: 1 addition & 0 deletions api/src/api/taxFilingRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe("taxFilingRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};
apiTaxFilingClient = {
lookup: jest.fn(),
Expand Down
1 change: 1 addition & 0 deletions api/src/api/userRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ describe("userRouter", () => {
get: jest.fn(),
put: jest.fn(),
findByEmail: jest.fn(),
findUserByBusinessName: jest.fn(),
};
stubUpdateLicenseStatus = jest.fn();
stubUpdateRoadmapSidebarCards = jest.fn();
Expand Down
44 changes: 42 additions & 2 deletions api/src/db/DynamoDataClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,7 @@ describe("User and Business Migration with DynamoDataClient", () => {
const naicsCode = `naics-code-${randomInt()}`;
const industry = `industry-${randomInt()}`;
const encryptedTaxId = `encryptedId-${randomInt()}`;

const generateUserData = (): UserData => {
const generateUserData = (businessName = "Default Business Name"): UserData => {
return generateUserDataForBusiness(
generateBusiness({
profileData: generateProfileData({
Expand All @@ -55,13 +54,15 @@ describe("User and Business Migration with DynamoDataClient", () => {
naicsCode: naicsCode,
industryId: industry,
encryptedTaxId: encryptedTaxId,
businessName: businessName,
}),
taxFilingData: generateTaxFilingData({
filings: [],
}),
})
);
};

const userData = generateUserData();

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
Expand Down Expand Up @@ -129,4 +130,43 @@ describe("User and Business Migration with DynamoDataClient", () => {

expect(logger.LogInfo).not.toHaveBeenCalledWith("Successfully migrated business");
});

it("should migrate data for multiple users with outdated versions", async () => {
const userData1 = { ...structuredClone(generateUserData()), version: 140 };
const userData2 = { ...structuredClone(generateUserData()), version: 143 };
jest
.spyOn(dynamoUsersDataClient, "getUsersWithOutdatedVersion")
.mockResolvedValue([userData1, userData2]);
const result = await dynamoDataClient.migrateData();

expect(result.success).toBe(true);
expect(result.migratedCount).toBe(2);
expect(dynamoBusinessesDataClient.put).toHaveBeenCalledTimes(2);

for (const data of [userData1, userData2]) {
const businessId = data.businesses[data.currentBusinessId].id;
expect(dynamoBusinessesDataClient.put).toHaveBeenCalledWith(
expect.objectContaining({ id: businessId })
);
expect(logger.LogInfo).toHaveBeenCalledWith(expect.stringContaining(`Updated business ${businessId}`));
}
});

it("should find user by businessName", async () => {
const businessName = "Test Business Name";
const userData1 = generateUserData(businessName);
const userData2 = generateUserData(businessName);
const userData3 = generateUserData();
const userData4 = generateUserData("test Business Name");
const userData5 = generateUserData("test Business Name!");

jest
.spyOn(dynamoUsersDataClient, "queryUsersWithBusinesses")
.mockResolvedValue([userData1, userData2, userData3, userData4, userData5]);

const result = await dynamoDataClient.findUserByBusinessName(businessName);

expect(dynamoUsersDataClient.queryUsersWithBusinesses).toHaveBeenCalledTimes(1);
expect(result).toEqual([userData1, userData2, userData4, userData5]);
});
});
25 changes: 24 additions & 1 deletion api/src/db/DynamoDataClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BusinessesDataClient, DatabaseClient, UserDataClient } from "@domain/types";
import { LogWriterType } from "@libs/logWriter";
import { CURRENT_VERSION, UserData } from "@shared/userData";
import { Business, CURRENT_VERSION, UserData } from "@shared/userData";
import { get as levenshteinDistance } from "fast-levenshtein";

export const DynamoDataClient = (
userDataClient: UserDataClient,
Expand Down Expand Up @@ -72,6 +73,27 @@ export const DynamoDataClient = (
}
};

const findUserByBusinessName = async (businessName: string): Promise<UserData[]> => {
const usersWithBusinesses = await userDataClient.queryUsersWithBusinesses();
aadedejifearless marked this conversation as resolved.
Show resolved Hide resolved
const normalizedBusinessName = businessName.trim().toLowerCase();

const usersWithMatchingBusinessNames = await Promise.all(
usersWithBusinesses.map(async (user: UserData) => {
const hasMatchingBusiness = await Promise.all(
Object.values(user.businesses).map(async (business: Business) => {
const businessNameNormalized = business.profileData?.businessName?.toLowerCase();
if (!businessNameNormalized) return false;
const distance = levenshteinDistance(normalizedBusinessName, businessNameNormalized);
return distance <= 2;
})
);
return hasMatchingBusiness.some(Boolean);
})
);

return usersWithBusinesses.filter((_, index) => usersWithMatchingBusinessNames[index]);
};

const put = async (userData: UserData): Promise<UserData> => {
try {
await updateUserAndBusinesses(userData);
Expand All @@ -92,5 +114,6 @@ export const DynamoDataClient = (
get,
put,
findByEmail,
findUserByBusinessName,
};
};
10 changes: 8 additions & 2 deletions api/src/db/DynamoUserDataClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,14 @@ export const DynamoUserDataClient = (
return search(statement);
};

const getUsersWithOutdatedVersion = async (latestVersion: number): Promise<UserData[]> => {
const getUsersWithOutdatedVersion = (latestVersion: number): Promise<UserData[]> => {
aadedejifearless marked this conversation as resolved.
Show resolved Hide resolved
const statement = `SELECT data FROM "${tableName}" WHERE data["version"] < ${CURRENT_VERSION}`;
return await search(statement);
return search(statement);
};

const queryUsersWithBusinesses = (): Promise<UserData[]> => {
const statement = `SELECT data FROM "${tableName}" WHERE data["businesses"] IS NOT MISSING AND size(data["businesses"]) > 0`;
return search(statement);
};

const search = async (statement: string): Promise<UserData[]> => {
Expand All @@ -160,5 +165,6 @@ export const DynamoUserDataClient = (
getNeedToAddToUserTestingUsers,
getNeedTaxIdEncryptionUsers,
getUsersWithOutdatedVersion,
queryUsersWithBusinesses,
};
};
1 change: 1 addition & 0 deletions api/src/domain/newsletter/addNewsletterBatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe("addNewsletterBatch", () => {
getNeedToAddToUserTestingUsers: jest.fn(),
getNeedTaxIdEncryptionUsers: jest.fn(),
getUsersWithOutdatedVersion: jest.fn(),
queryUsersWithBusinesses: jest.fn(),
};
addNewsletter = addNewsletterFactory(stubNewsletterClient);
});
Expand Down
2 changes: 2 additions & 0 deletions api/src/domain/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export interface DatabaseClient {
get: (userId: string) => Promise<UserData>;
put: (userData: UserData) => Promise<UserData>;
findByEmail: (email: string) => Promise<UserData | undefined>;
findUserByBusinessName: (businessName: string) => Promise<UserData[]>;
}

export interface UserDataClient {
Expand All @@ -36,6 +37,7 @@ export interface UserDataClient {
getNeedToAddToUserTestingUsers: () => Promise<UserData[]>;
getNeedTaxIdEncryptionUsers: () => Promise<UserData[]>;
getUsersWithOutdatedVersion: (latestVersion: number) => Promise<UserData[]>;
queryUsersWithBusinesses: () => Promise<UserData[]>;
}

export interface BusinessesDataClient {
Expand Down
1 change: 1 addition & 0 deletions api/src/domain/user-testing/addToUserTestingBatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe("addToUserTestingBatch", () => {
getNeedNewsletterUsers: jest.fn(),
getNeedToAddToUserTestingUsers: jest.fn(),
getUsersWithOutdatedVersion: jest.fn(),
queryUsersWithBusinesses: jest.fn(),
};
addToUserTesting = addToUserTestingFactory(stubUserTestingClient);
});
Expand Down
1 change: 1 addition & 0 deletions api/src/domain/user/encryptTaxIdBatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ describe("encryptTaxIdBatch", () => {
getNeedToAddToUserTestingUsers: jest.fn(),
getNeedTaxIdEncryptionUsers: jest.fn(),
getUsersWithOutdatedVersion: jest.fn(),
queryUsersWithBusinesses: jest.fn(),
};
encryptTaxId = encryptTaxIdFactory(stubEncryptionDecryptionClient);
});
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
"@newjersey/njwds": "0.3.0",
"@smithy/node-http-handler": "2.5.0",
"@storybook/addon-outline": "7.6.20",
"@types/fast-levenshtein": "^0.0.4",
"@types/mdast": "4.0.4",
"airtable": "0.12.2",
"axios": "1.7.8",
Expand All @@ -69,6 +70,7 @@
"dedent": "1.5.3",
"express": "4.21.1",
"fast-deep-equal": "3.1.3",
"fast-levenshtein": "^3.0.0",
"focus-trap-react": "10.2.3",
"gray-matter": "4.0.3",
"helmet": "7.2.0",
Expand Down
20 changes: 19 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5044,6 +5044,7 @@ __metadata:
"@types/cypress-dotenv": 2.0.3
"@types/dedent": 0.7.2
"@types/express": 4.17.21
"@types/fast-levenshtein": ^0.0.4
"@types/jest": 29.5.14
"@types/js-yaml": 4.0.9
"@types/jsonwebtoken": 9.0.7
Expand Down Expand Up @@ -5101,6 +5102,7 @@ __metadata:
eslint-plugin-unicorn: 51.0.1
express: 4.21.1
fast-deep-equal: 3.1.3
fast-levenshtein: ^3.0.0
focus-trap-react: 10.2.3
gray-matter: 4.0.3
helmet: 7.2.0
Expand Down Expand Up @@ -12342,6 +12344,13 @@ __metadata:
languageName: node
linkType: hard

"@types/fast-levenshtein@npm:^0.0.4":
version: 0.0.4
resolution: "@types/fast-levenshtein@npm:0.0.4"
checksum: ce91d48485a5cbcbb8b41ae6bf198b0b505601c075d9b55e98e8cff0d10cfe4aa6bf9b519534f6bdba41f508f045d3038c7a89a1c02c367aec10615ca00330c9
languageName: node
linkType: hard

"@types/find-cache-dir@npm:^3.2.1":
version: 3.2.1
resolution: "@types/find-cache-dir@npm:3.2.1"
Expand Down Expand Up @@ -20141,6 +20150,15 @@ __metadata:
languageName: node
linkType: hard

"fast-levenshtein@npm:^3.0.0":
version: 3.0.0
resolution: "fast-levenshtein@npm:3.0.0"
dependencies:
fastest-levenshtein: ^1.0.7
checksum: 02732ba6c656797ca7e987c25f3e53718c8fcc39a4bfab46def78eef7a8729eb629632d4a7eca4c27a33e10deabffa9984839557e18a96e91ecf7ccaeedb9890
languageName: node
linkType: hard

"fast-safe-stringify@npm:^2.0.7, fast-safe-stringify@npm:^2.1.1":
version: 2.1.1
resolution: "fast-safe-stringify@npm:2.1.1"
Expand All @@ -20166,7 +20184,7 @@ __metadata:
languageName: node
linkType: hard

"fastest-levenshtein@npm:^1.0.12, fastest-levenshtein@npm:^1.0.16":
"fastest-levenshtein@npm:^1.0.12, fastest-levenshtein@npm:^1.0.16, fastest-levenshtein@npm:^1.0.7":
version: 1.0.16
resolution: "fastest-levenshtein@npm:1.0.16"
checksum: a78d44285c9e2ae2c25f3ef0f8a73f332c1247b7ea7fb4a191e6bb51aa6ee1ef0dfb3ed113616dcdc7023e18e35a8db41f61c8d88988e877cf510df8edafbc71
Expand Down