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

PIMS-1946 Cancel/Stop Notifications #2726

Merged
merged 6 commits into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
49 changes: 43 additions & 6 deletions express-api/src/services/projects/projectsServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ import {
import { ProjectFilter } from '@/services/projects/projectSchema';
import { PropertyType } from '@/constants/propertyType';
import { ProjectRisk } from '@/constants/projectRisk';
import notificationServices, { AgencyResponseType } from '../notifications/notificationServices';
import notificationServices, {
AgencyResponseType,
NotificationStatus,
} from '../notifications/notificationServices';
import {
constructFindOptionFromQuery,
constructFindOptionFromQuerySingleSelect,
Expand Down Expand Up @@ -413,6 +416,29 @@ const handleProjectNotifications = async (
Id: projectId,
},
});

// If the project is cancelled, cancel pending notifications
if (projectWithRelations.StatusId === ProjectStatus.CANCELLED) {
const pendingNotifications = await queryRunner.manager.find(NotificationQueue, {
where: [
{
ProjectId: projectWithRelations.Id,
Status: NotificationStatus.Accepted,
},
{
ProjectId: projectWithRelations.Id,
Status: NotificationStatus.Pending,
},
],
});
await Promise.allSettled(
pendingNotifications.map(async (notification) => {
await notificationServices.cancelNotificationById(notification.Id, user);
}),
);
return [];
}

const projectAgency = await queryRunner.manager.findOne(Agency, {
where: { Id: projectWithRelations.AgencyId },
});
Expand All @@ -428,13 +454,23 @@ const handleProjectNotifications = async (

const notifsToSend: Array<NotificationQueue> = [];

// If the status has been changed
if (previousStatus !== projectWithRelations.StatusId) {
const statusChangeNotifs = await notificationServices.generateProjectNotifications(
projectWithRelations,
previousStatus,
queryRunner,
// Has the project previously been to this status? If so, don't re-queue notifications.
const previousStatuses = await queryRunner.manager.find(ProjectStatusHistory, {
where: { ProjectId: projectWithRelations.Id },
});
const statusPreviouslyVisited = previousStatuses.some(
(record: ProjectStatusHistory) => record.StatusId === projectWithRelations.StatusId,
);
notifsToSend.push(...statusChangeNotifs);
if (!statusPreviouslyVisited) {
const statusChangeNotifs = await notificationServices.generateProjectNotifications(
projectWithRelations,
previousStatus,
queryRunner,
);
notifsToSend.push(...statusChangeNotifs);
}
}

if (projectAgencyResponses.length) {
Expand Down Expand Up @@ -1050,6 +1086,7 @@ const projectServices = {
updateProject,
getProjects,
getProjectsForExport,
handleProjectNotifications,
};

export default projectServices;
148 changes: 88 additions & 60 deletions express-api/tests/unit/services/projects/projectsServices.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AppDataSource } from '@/appDataSource';
import { ProjectStatus } from '@/constants/projectStatus';
import { ProjectType } from '@/constants/projectType';
import { Roles } from '@/constants/roles';
import { NotificationStatus } from '@/services/notifications/notificationServices';
import projectServices from '@/services/projects/projectsServices';
import userServices from '@/services/users/usersServices';
import { Agency } from '@/typeorm/Entities/Agency';
Expand Down Expand Up @@ -244,8 +245,9 @@ jest
.mockImplementation(() => projectJoinQueryBuilder);

const _generateProjectWatchNotifications = jest.fn(async () => [produceNotificationQueue()]);
const _generateProjectNotifications = jest.fn(async () => [produceNotificationQueue()]);
jest.mock('@/services/notifications/notificationServices', () => ({
generateProjectNotifications: jest.fn(async () => [produceNotificationQueue()]),
generateProjectNotifications: async () => _generateProjectNotifications(),
sendNotification: jest.fn(async () => produceNotificationQueue()),
generateProjectWatchNotifications: async () => _generateProjectWatchNotifications(),
NotificationStatus: { Accepted: 0, Pending: 1, Cancelled: 2, Failed: 3, Completed: 4 },
Expand Down Expand Up @@ -616,70 +618,96 @@ describe('UNIT - Project Services', () => {
);
expect(_generateProjectWatchNotifications).toHaveBeenCalled();
});
});

describe('getProjects', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return projects based on filter conditions', async () => {
const filter = {
statusId: 1,
agencyId: [3],
quantity: 10,
page: 1,
market: '$12',
netBook: '$12',
agency: 'contains,aaa',
status: 'contains,aaa',
projectNumber: 'contains,aaa',
name: 'contains,Project',
updatedOn: 'before,' + new Date(),
updatedBy: 'Jane',
sortOrder: 'asc',
sortKey: 'Status',
quickFilter: 'hi',
};

// Call the service function
const projectsResponse = await projectServices.getProjects(filter); // Pass the mocked projectRepo
// Returned project should be the one based on the agency and status id in the filter
expect(projectsResponse.totalCount).toEqual(1);
expect(projectsResponse.data.length).toEqual(1);
describe('handleProjectNotifications', () => {
it('should not send notifications when status becomes Cancelled', async () => {
const project = produceProject({
AgencyResponses: [produceAgencyResponse()],
StatusId: ProjectStatus.CANCELLED,
CancelledOn: new Date(),
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const queryRunner: any = {
manager: {
findOne: async () => project,
find: () => [produceNotificationQueue({ Status: NotificationStatus.Pending })],
},
};
await projectServices.handleProjectNotifications(
project.Id,
ProjectStatus.ON_HOLD,
[produceAgencyResponse()],
producePimsRequestUser(),
queryRunner,
);
expect(_generateProjectWatchNotifications).not.toHaveBeenCalled();
expect(_generateProjectNotifications).not.toHaveBeenCalled();
});
});

describe('getProjectsForExport', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return projects based on filter conditions', async () => {
const filter = {
statusId: 1,
agencyId: [3],
quantity: 10,
page: 0,
};

_projectFind.mockImplementationOnce(async () => {
const mockProjects: Project[] = [
produceProject({ Id: 1, Name: 'Project 1', StatusId: 1, AgencyId: 3 }),
produceProject({ Id: 2, Name: 'Project 2', StatusId: 4, AgencyId: 14 }),
];
// Check if the project matches the filter conditions
return mockProjects.filter(
(project) =>
filter.statusId === project.StatusId && filter.agencyId.includes(project.AgencyId),
);
});

// Call the service function
const projects = await projectServices.getProjectsForExport(filter); // Pass the mocked projectRepo

// Assertions
expect(_projectFind).toHaveBeenCalled();
// Returned project should be the one based on the agency and status id in the filter
expect(projects.length).toEqual(1);
describe('getProjects', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return projects based on filter conditions', async () => {
const filter = {
statusId: 1,
agencyId: [3],
quantity: 10,
page: 1,
market: '$12',
netBook: '$12',
agency: 'contains,aaa',
status: 'contains,aaa',
projectNumber: 'contains,aaa',
name: 'contains,Project',
updatedOn: 'before,' + new Date(),
updatedBy: 'Jane',
sortOrder: 'asc',
sortKey: 'Status',
quickFilter: 'hi',
};

// Call the service function
const projectsResponse = await projectServices.getProjects(filter); // Pass the mocked projectRepo
// Returned project should be the one based on the agency and status id in the filter
expect(projectsResponse.totalCount).toEqual(1);
expect(projectsResponse.data.length).toEqual(1);
});
});

describe('getProjectsForExport', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should return projects based on filter conditions', async () => {
const filter = {
statusId: 1,
agencyId: [3],
quantity: 10,
page: 0,
};

_projectFind.mockImplementationOnce(async () => {
const mockProjects: Project[] = [
produceProject({ Id: 1, Name: 'Project 1', StatusId: 1, AgencyId: 3 }),
produceProject({ Id: 2, Name: 'Project 2', StatusId: 4, AgencyId: 14 }),
];
// Check if the project matches the filter conditions
return mockProjects.filter(
(project) =>
filter.statusId === project.StatusId && filter.agencyId.includes(project.AgencyId),
);
});

// Call the service function
const projects = await projectServices.getProjectsForExport(filter); // Pass the mocked projectRepo

// Assertions
expect(_projectFind).toHaveBeenCalled();
// Returned project should be the one based on the agency and status id in the filter
expect(projects.length).toEqual(1);
});
});
});
Loading