Skip to content

Commit

Permalink
Merge pull request #193 from Hexastack/190-request-add-bulk-delete-fu…
Browse files Browse the repository at this point in the history
…nctionality-to-nlu-values-list

feat: [NLP Value] add bulk delete
  • Loading branch information
marrouchi authored Oct 11, 2024
2 parents afefef2 + 6b57c57 commit 18378de
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 8 deletions.
34 changes: 33 additions & 1 deletion api/src/nlp/controllers/nlp-value.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
*/

import { NotFoundException } from '@nestjs/common';
import { BadRequestException, NotFoundException } from '@nestjs/common';
import { EventEmitter2 } from '@nestjs/event-emitter';
import { MongooseModule } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
Expand Down Expand Up @@ -40,6 +40,7 @@ describe('NlpValueController', () => {
let nlpEntityService: NlpEntityService;
let jhonNlpValue: NlpValue;
let positiveValue: NlpValue;
let negativeValue: NlpValue;

beforeAll(async () => {
const module: TestingModule = await Test.createTestingModule({
Expand Down Expand Up @@ -67,6 +68,7 @@ describe('NlpValueController', () => {
nlpEntityService = module.get<NlpEntityService>(NlpEntityService);
jhonNlpValue = await nlpValueService.findOne({ value: 'jhon' });
positiveValue = await nlpValueService.findOne({ value: 'positive' });
negativeValue = await nlpValueService.findOne({ value: 'negative' });
});
afterAll(async () => {
await closeInMongodConnection();
Expand Down Expand Up @@ -228,4 +230,34 @@ describe('NlpValueController', () => {
).rejects.toThrow(NotFoundException);
});
});
describe('deleteMany', () => {
it('should delete multiple nlp values', async () => {
const valuesToDelete = [positiveValue.id, negativeValue.id];

const result = await nlpValueController.deleteMany(valuesToDelete);

expect(result.deletedCount).toEqual(valuesToDelete.length);
const remainingValues = await nlpValueService.find({
_id: { $in: valuesToDelete },
});
expect(remainingValues.length).toBe(0);
});

it('should throw BadRequestException when no IDs are provided', async () => {
await expect(nlpValueController.deleteMany([])).rejects.toThrow(
BadRequestException,
);
});

it('should throw NotFoundException when provided IDs do not exist', async () => {
const nonExistentIds = [
'614c1b2f58f4f04c876d6b8d',
'614c1b2f58f4f04c876d6b8e',
];

await expect(
nlpValueController.deleteMany(nonExistentIds),
).rejects.toThrow(NotFoundException);
});
});
});
27 changes: 27 additions & 0 deletions api/src/nlp/controllers/nlp-value.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ import {
Query,
NotFoundException,
UseInterceptors,
BadRequestException,
} from '@nestjs/common';
import { CsrfCheck } from '@tekuconcept/nestjs-csrf';
import { TFilterQuery } from 'mongoose';

import { CsrfInterceptor } from '@/interceptors/csrf.interceptor';
import { LoggerService } from '@/logger/logger.service';
import { BaseController } from '@/utils/generics/base-controller';
import { DeleteResult } from '@/utils/generics/base-repository';
import { PageQueryDto } from '@/utils/pagination/pagination-query.dto';
import { PageQueryPipe } from '@/utils/pagination/pagination-query.pipe';
import { PopulatePipe } from '@/utils/pipes/populate.pipe';
Expand Down Expand Up @@ -193,4 +195,29 @@ export class NlpValueController extends BaseController<
}
return result;
}

/**
* Deletes multiple NLP values by their IDs.
* @param ids - IDs of NLP values to be deleted.
* @returns A Promise that resolves to the deletion result.
*/
@CsrfCheck(true)
@Delete('')
@HttpCode(204)
async deleteMany(@Body('ids') ids: string[]): Promise<DeleteResult> {
if (!ids || ids.length === 0) {
throw new BadRequestException('No IDs provided for deletion.');
}
const deleteResult = await this.nlpValueService.deleteMany({
_id: { $in: ids },
});

if (deleteResult.deletedCount === 0) {
this.logger.warn(`Unable to delete NLP values with provided IDs: ${ids}`);
throw new NotFoundException('NLP values with provided IDs not found');
}

this.logger.log(`Successfully deleted NLP values with IDs: ${ids}`);
return deleteResult;
}
}
2 changes: 1 addition & 1 deletion frontend/src/components/nlp/components/NlpSample.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

import CircleIcon from "@mui/icons-material/Circle";
import DeleteIcon from "@mui/icons-material/Close";
import DeleteIcon from "@mui/icons-material/Delete";
import DownloadIcon from "@mui/icons-material/Download";
import UploadIcon from "@mui/icons-material/Upload";
import {
Expand Down
52 changes: 46 additions & 6 deletions frontend/src/components/nlp/components/NlpValues.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
import { faGraduationCap } from "@fortawesome/free-solid-svg-icons";
import AddIcon from "@mui/icons-material/Add";
import ArrowBackIcon from "@mui/icons-material/ArrowBack";
import { Box, Button, Chip, Grid, Slide } from "@mui/material";
import { GridColDef } from "@mui/x-data-grid";
import DeleteIcon from "@mui/icons-material/Delete";
import { Box, Button, ButtonGroup, Chip, Grid, Slide } from "@mui/material";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useRouter } from "next/router";
import { useEffect, useState } from "react";

Expand All @@ -23,6 +24,7 @@ import {
import { renderHeader } from "@/app-components/tables/columns/renderHeader";
import { DataGrid } from "@/app-components/tables/DataGrid";
import { useDelete } from "@/hooks/crud/useDelete";
import { useDeleteMany } from "@/hooks/crud/useDeleteMany";
import { useFind } from "@/hooks/crud/useFind";
import { useGet } from "@/hooks/crud/useGet";
import { useDialog } from "@/hooks/useDialog";
Expand Down Expand Up @@ -72,6 +74,17 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
refetchEntity();
},
});
const { mutateAsync: deleteNlpValues } = useDeleteMany(EntityType.NLP_VALUE, {
onError: (error) => {
toast.error(error);
},
onSuccess: () => {
deleteEntityDialogCtl.closeDialog();
setSelectedNlpValues([]);
toast.success(t("message.item_delete_success"));
},
});
const [selectedNlpValues, setSelectedNlpValues] = useState<string[]>([]);
const actionColumns = useActionColumns<INlpValue>(
EntityType.NLP_VALUE,
[
Expand Down Expand Up @@ -138,6 +151,9 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
}, []);

const canHaveSynonyms = nlpEntity?.lookups?.[0] === NlpLookups.keywords;
const handleSelectionChange = (selection: GridRowSelectionModel) => {
setSelectedNlpValues(selection as string[]);
};

return (
<Grid container gap={2} flexDirection="column">
Expand Down Expand Up @@ -174,7 +190,7 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
<Grid item>
<FilterTextfield onChange={onSearch} />
</Grid>
<Grid item>
<ButtonGroup sx={{ marginLeft: "auto" }}>
{hasPermission(
EntityType.NLP_VALUE,
PermissionAction.CREATE,
Expand All @@ -188,7 +204,21 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
{t("button.add")}
</Button>
) : null}
</Grid>
{selectedNlpValues.length > 0 && (
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() =>
deleteEntityDialogCtl.openDialog(undefined)
}
>
{t("button.delete")}
</Button>
</Grid>
)}
</ButtonGroup>
</Grid>
</PageHeader>
<NlpValueDialog
Expand All @@ -201,8 +231,13 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
<DeleteDialog
{...deleteEntityDialogCtl}
callback={() => {
if (deleteEntityDialogCtl.data)
if (selectedNlpValues.length > 0) {
deleteNlpValues(selectedNlpValues);
setSelectedNlpValues([]);
deleteEntityDialogCtl.closeDialog();
} else if (deleteEntityDialogCtl.data) {
deleteNlpValue(deleteEntityDialogCtl.data);
}
}}
/>
<NlpValueDialog
Expand All @@ -211,7 +246,12 @@ export const NlpValues = ({ entityId }: { entityId: string }) => {
callback={() => {}}
/>
<Grid padding={1} marginTop={2} container>
<DataGrid columns={columns} {...dataGridProps} />
<DataGrid
columns={columns}
{...dataGridProps}
checkboxSelection
onRowSelectionModelChange={handleSelectionChange}
/>
</Grid>
</Box>
</Grid>
Expand Down

0 comments on commit 18378de

Please sign in to comment.