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

tweak(datatrakWeb): RN-1331: Update to task details/comments #5823

Merged
merged 9 commits into from
Aug 5, 2024
Merged
Show file tree
Hide file tree
Changes from 8 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
3 changes: 2 additions & 1 deletion packages/central-server/src/apiV2/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ import {
} from './dashboardMailingListEntries';
import { EditEntityHierarchy, GETEntityHierarchy } from './entityHierarchy';
import { CreateTask, EditTask, GETTasks } from './tasks';
import { GETTaskComments } from './taskComments';
import { CreateTaskComment, GETTaskComments } from './taskComments';

// quick and dirty permission wrapper for open endpoints
const allowAnyone = routeHandler => (req, res, next) => {
Expand Down Expand Up @@ -318,6 +318,7 @@ apiV2.post('/surveys', multipartJson(), useRouteHandler(CreateSurvey));
apiV2.post('/dhisInstances', useRouteHandler(BESAdminCreateHandler));
apiV2.post('/supersetInstances', useRouteHandler(BESAdminCreateHandler));
apiV2.post('/tasks', useRouteHandler(CreateTask));
apiV2.post('/tasks/:parentRecordId/taskComments', useRouteHandler(CreateTaskComment));
/**
* PUT routes
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/
import { CreateHandler } from '../CreateHandler';
import { assertAnyPermissions, assertBESAdminAccess } from '../../permissions';
import { assertUserHasTaskPermissions } from '../tasks/assertTaskPermissions';
/**
* Handles POST endpoints:
* - /tasks/:parentRecordId/taskComments
*/

export class CreateTaskComment extends CreateHandler {
async assertUserHasAccess() {
const createPermissionChecker = accessPolicy =>
assertUserHasTaskPermissions(accessPolicy, this.models, this.parentRecordId);

await this.assertPermissions(
assertAnyPermissions([assertBESAdminAccess, createPermissionChecker]),
);
}

async createRecord() {
return this.models.wrapInTransaction(async transactingModels => {
const task = await transactingModels.task.findById(this.parentRecordId);
const { message, type } = this.newRecordData;
const newComment = await task.addComment(message, this.req.user.id, type);
return { id: newComment.id };
});
}
}
1 change: 1 addition & 0 deletions packages/central-server/src/apiV2/taskComments/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
*/

export { GETTaskComments } from './GETTaskComments';
export { CreateTaskComment } from './CreateTaskComment';
11 changes: 2 additions & 9 deletions packages/central-server/src/apiV2/tasks/EditTask.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,10 @@ export class EditTask extends EditHandler {
}

async editRecord() {
const { comment, ...updatedFields } = this.updatedFields;
return this.models.wrapInTransaction(async transactingModels => {
const originalTask = await transactingModels.task.findById(this.recordId);
let task = originalTask;
// Sometimes an update can just be a comment, so we don't want to update the task if there are no fields to update, because we would get an error
if (Object.keys(updatedFields).length > 0) {
task = await transactingModels.task.updateById(this.recordId, updatedFields);
}
if (comment) {
await originalTask.addComment(comment, this.req.user.id);
}
const task = await transactingModels.task.updateById(this.recordId, this.updatedFields);

await originalTask.addSystemCommentsOnUpdate(this.updatedFields, this.req.user.id);
return task;
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
/**
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/

import { expect } from 'chai';
import {
buildAndInsertSurveys,
findOrCreateDummyCountryEntity,
findOrCreateDummyRecord,
generateId,
} from '@tupaia/database';
import { TestableApp, resetTestData } from '../../testUtilities';
import { BES_ADMIN_PERMISSION_GROUP } from '../../../permissions';

describe('Permissions checker for CreateTaskComment', async () => {
const BES_ADMIN_POLICY = {
DL: [BES_ADMIN_PERMISSION_GROUP],
};

const DEFAULT_POLICY = {
DL: ['Donor'],
TO: ['Donor'],
};

const app = new TestableApp();
const { models } = app;
let tasks;

before(async () => {
const { country: tongaCountry } = await findOrCreateDummyCountryEntity(models, {
code: 'TO',
name: 'Tonga',
});

const { country: dlCountry } = await findOrCreateDummyCountryEntity(models, {
code: 'DL',
name: 'Demo Land',
});

const donorPermission = await findOrCreateDummyRecord(models.permissionGroup, {
name: 'Donor',
});
const BESAdminPermission = await findOrCreateDummyRecord(models.permissionGroup, {
name: 'Admin',
});

const facilities = [
{
id: generateId(),
code: 'TEST_FACILITY_1',
name: 'Test Facility 1',
country_code: tongaCountry.code,
},
{
id: generateId(),
code: 'TEST_FACILITY_2',
name: 'Test Facility 2',
country_code: dlCountry.code,
},
];

await Promise.all(facilities.map(facility => findOrCreateDummyRecord(models.entity, facility)));

const surveys = await buildAndInsertSurveys(models, [
{
code: 'TEST_SURVEY_1',
name: 'Test Survey 1',
permission_group_id: BESAdminPermission.id,
country_ids: [tongaCountry.id, dlCountry.id],
},
{
code: 'TEST_SURVEY_2',
name: 'Test Survey 2',
permission_group_id: donorPermission.id,
country_ids: [tongaCountry.id, dlCountry.id],
},
]);

const assignee = {
id: generateId(),
first_name: 'Minnie',
last_name: 'Mouse',
};
await findOrCreateDummyRecord(models.user, assignee);

const dueDate = new Date('2021-12-31');

tasks = [
{
id: generateId(),
survey_id: surveys[0].survey.id,
entity_id: facilities[0].id,
due_date: dueDate,
status: 'to_do',
repeat_schedule: null,
},
{
id: generateId(),
survey_id: surveys[1].survey.id,
entity_id: facilities[1].id,
assignee_id: assignee.id,
due_date: null,
repeat_schedule: '{}',
status: null,
},
];

await Promise.all(
tasks.map(task =>
findOrCreateDummyRecord(
models.task,
{
'task.id': task.id,
},
task,
),
),
);
});

afterEach(async () => {
await models.taskComment.delete({ task_id: tasks[0].id });
await models.taskComment.delete({ task_id: tasks[1].id });
app.revokeAccess();
});

after(async () => {
await resetTestData();
});

describe('POST /tasks/:id/taskComments', async () => {
it('Sufficient permissions: Successfully creates a task comment when the user has BES Admin permissions', async () => {
await app.grantAccess(BES_ADMIN_POLICY);
await app.post(`tasks/${tasks[0].id}/taskComments`, {
body: {
message: 'This is a test comment',
type: 'user',
},
});
const comment = await models.taskComment.findOne({ task_id: tasks[0].id });
expect(comment.message).to.equal('This is a test comment');
});

it('Sufficient permissions: Successfully creates a task comment when user has access to the task', async () => {
await app.grantAccess(DEFAULT_POLICY);
await app.post(`tasks/${tasks[1].id}/taskComments`, {
body: {
message: 'This is a test comment',
type: 'user',
},
});
const comment = await models.taskComment.findOne({ task_id: tasks[1].id });
expect(comment.message).to.equal('This is a test comment');
});

it('Insufficient permissions: throws an error if trying to create a comment for a task the user does not have permissions for', async () => {
await app.grantAccess(DEFAULT_POLICY);
const { body: result } = await app.post(`tasks/${tasks[0].id}/taskComments`, {
body: {
message: 'This is a test comment',
type: 'user',
},
});

expect(result).to.have.keys('error');
});
});
});
96 changes: 0 additions & 96 deletions packages/central-server/src/tests/apiV2/tasks/EditTask.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -210,55 +210,6 @@ describe('Permissions checker for EditTask', async () => {
});
});

describe('User generated comments', async () => {
it('Handles adding a comment when editing a task', async () => {
await app.grantAccess({
DL: ['Donor'],
TO: ['Donor'],
});
await app.put(`tasks/${tasks[1].id}`, {
body: {
survey_id: surveys[1].survey.id,
entity_id: facilities[1].id,
comment: 'This is a test comment',
},
});
const result = await models.task.find({
id: tasks[1].id,
});
expect(result[0].entity_id).to.equal(facilities[1].id);
expect(result[0].survey_id).to.equal(surveys[1].survey.id);

const comment = await models.taskComment.findOne({
task_id: tasks[1].id,
message: 'This is a test comment',
});
expect(comment).not.to.be.null;
});

it('Handles adding a comment when no other edits are made', async () => {
await app.grantAccess({
DL: ['Donor'],
TO: ['Donor'],
});
await app.put(`tasks/${tasks[1].id}`, {
body: {
comment: 'This is a test comment',
},
});
const result = await models.task.find({
id: tasks[1].id,
});
expect(result[0].entity_id).to.equal(tasks[1].entity_id);

const comment = await models.taskComment.findOne({
task_id: tasks[1].id,
message: 'This is a test comment',
});
expect(comment).not.to.be.null;
});
});

describe('System generated comments', () => {
it('Adds a comment when the due date changes on a task', async () => {
await app.grantAccess({
Expand Down Expand Up @@ -391,52 +342,5 @@ describe('Permissions checker for EditTask', async () => {
expect(comment).not.to.be.null;
});
});

it('Handles adding a comment when editing a task', async () => {
await app.grantAccess({
DL: ['Donor'],
TO: ['Donor'],
});
await app.put(`tasks/${tasks[1].id}`, {
body: {
survey_id: surveys[1].survey.id,
entity_id: facilities[1].id,
comment: 'This is a test comment',
},
});
const result = await models.task.find({
id: tasks[1].id,
});
expect(result[0].entity_id).to.equal(facilities[1].id);
expect(result[0].survey_id).to.equal(surveys[1].survey.id);

const comment = await models.taskComment.findOne({
task_id: tasks[1].id,
message: 'This is a test comment',
});
expect(comment).not.to.be.undefined;
});

it('Handles adding a comment when no other edits are made', async () => {
await app.grantAccess({
DL: ['Donor'],
TO: ['Donor'],
});
await app.put(`tasks/${tasks[1].id}`, {
body: {
comment: 'This is a test comment',
},
});
const result = await models.task.find({
id: tasks[1].id,
});
expect(result[0].entity_id).to.equal(tasks[1].entity_id);

const comment = await models.taskComment.findOne({
task_id: tasks[1].id,
message: 'This is a test comment',
});
expect(comment).not.to.be.undefined;
});
});
});
1 change: 1 addition & 0 deletions packages/datatrak-web/src/api/mutations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ export { useOneTimeLogin } from './useOneTimeLogin';
export * from './useExportSurveyResponses';
export { useTupaiaRedirect } from './useTupaiaRedirect';
export { useCreateTask } from './useCreateTask';
export { useCreateTaskComment } from './useCreateTaskComment';
33 changes: 33 additions & 0 deletions packages/datatrak-web/src/api/mutations/useCreateTaskComment.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Tupaia
* Copyright (c) 2017 - 2024 Beyond Essential Systems Pty Ltd
*/

import { useMutation, useQueryClient } from 'react-query';
import { Task, TaskCommentType } from '@tupaia/types';
import { post } from '../api';
import { successToast } from '../../utils';

export const useCreateTaskComment = (taskId?: Task['id'], onSuccess?: () => void) => {
const queryClient = useQueryClient();
return useMutation<any, Error, string, unknown>(
(comment: string) => {
return post(`tasks/${taskId}/taskComments`, {
data: {
message: comment,
type: TaskCommentType.user,
},
});
},
{
onSuccess: () => {
queryClient.invalidateQueries('tasks');
queryClient.invalidateQueries(['tasks', taskId]);
successToast('Comment added successfully');
if (onSuccess) {
onSuccess();
}
},
},
);
};
Loading