Skip to content

Commit

Permalink
Merge pull request #164 from Hexastack/151-request-add-bulk-delete-fu…
Browse files Browse the repository at this point in the history
…nctionality-to-categories-list

feat: add bulk delete functionality
  • Loading branch information
marrouchi authored Oct 7, 2024
2 parents e70c705 + d7edfdf commit 0066e81
Show file tree
Hide file tree
Showing 6 changed files with 209 additions and 11 deletions.
40 changes: 39 additions & 1 deletion api/src/chat/controllers/category.contoller.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 } from '@nestjs/testing';
Expand Down Expand Up @@ -185,6 +185,44 @@ describe('CategoryController', () => {
});
});

describe('deleteMany', () => {
it('should delete multiple categories by ids', async () => {
const deleteResult = { acknowledged: true, deletedCount: 2 };
jest.spyOn(categoryService, 'deleteMany').mockResolvedValue(deleteResult);

const result = await categoryController.deleteMany([
category.id,
categoryToDelete.id,
]);

expect(categoryService.deleteMany).toHaveBeenCalledWith({
_id: { $in: [category.id, categoryToDelete.id] },
});
expect(result).toEqual(deleteResult);
});

it('should throw a NotFoundException when no categories are deleted', async () => {
const deleteResult = { acknowledged: true, deletedCount: 0 };
jest.spyOn(categoryService, 'deleteMany').mockResolvedValue(deleteResult);

await expect(
categoryController.deleteMany([category.id, categoryToDelete.id]),
).rejects.toThrow(
new NotFoundException('Categories with provided IDs not found'),
);

expect(categoryService.deleteMany).toHaveBeenCalledWith({
_id: { $in: [category.id, categoryToDelete.id] },
});
});

it('should throw a BadRequestException when no ids are provided', async () => {
await expect(categoryController.deleteMany([])).rejects.toThrow(
new BadRequestException('No IDs provided for deletion.'),
);
});
});

describe('updateOne', () => {
const categoryUpdateDto: CategoryUpdateDto = {
builtin: false,
Expand Down
26 changes: 26 additions & 0 deletions api/src/chat/controllers/category.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
*/

import {
BadRequestException,
Body,
Controller,
Delete,
Expand Down Expand Up @@ -137,4 +138,29 @@ export class CategoryController extends BaseController<Category> {
}
return result;
}

/**
* Deletes multiple categories by their IDs.
* @param ids - IDs of categories 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.categoryService.deleteMany({
_id: { $in: ids },
});

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

this.logger.log(`Successfully deleted categories with IDs: ${ids}`);
return deleteResult;
}
}
19 changes: 13 additions & 6 deletions api/src/chat/repositories/category.repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export class CategoryRepository extends BaseRepository<Category> {
* @param criteria - The filter criteria for finding blocks to delete.
*/
async preDelete(
_query: Query<
query: Query<
DeleteResult,
Document<Category, any, any>,
unknown,
Expand All @@ -46,11 +46,18 @@ export class CategoryRepository extends BaseRepository<Category> {
>,
criteria: TFilterQuery<Category>,
) {
const associatedBlocks = await this.blockService.findOne({
category: criteria._id,
});
if (associatedBlocks) {
throw new ForbiddenException(`Category have blocks associated to it`);
criteria = query.getQuery();
const ids = Array.isArray(criteria._id) ? criteria._id : [criteria._id];

for (const id of ids) {
const associatedBlocks = await this.blockService.findOne({
category: id,
});
if (associatedBlocks) {
throw new ForbiddenException(
`Category ${id} has blocks associated with it`,
);
}
}
}
}
52 changes: 48 additions & 4 deletions frontend/src/components/categories/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@
*/

import AddIcon from "@mui/icons-material/Add";
import DeleteIcon from "@mui/icons-material/Delete";
import FolderIcon from "@mui/icons-material/Folder";
import { Button, Grid, Paper } from "@mui/material";
import { GridColDef } from "@mui/x-data-grid";
import { GridColDef, GridRowSelectionModel } from "@mui/x-data-grid";
import { useState } from "react";

import { DeleteDialog } from "@/app-components/dialogs/DeleteDialog";
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
Expand All @@ -20,6 +22,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 { getDisplayDialogs, useDialog } from "@/hooks/useDialog";
import { useHasPermission } from "@/hooks/useHasPermission";
Expand Down Expand Up @@ -56,9 +59,21 @@ export const Categories = () => {
},
onSuccess: () => {
deleteDialogCtl.closeDialog();
setSelectedCategories([]);
toast.success(t("message.item_delete_success"));
},
});
const { mutateAsync: deleteCategories } = useDeleteMany(EntityType.CATEGORY, {
onError: (error) => {
toast.error(error.message || t("message.internal_server_error"));
},
onSuccess: () => {
deleteDialogCtl.closeDialog();
setSelectedCategories([]);
toast.success(t("message.item_delete_success"));
},
});
const [selectedCategories, setSelectedCategories] = useState<string[]>([]);
const actionColumns = useActionColumns<ICategory>(
EntityType.CATEGORY,
[
Expand Down Expand Up @@ -109,15 +124,27 @@ export const Categories = () => {
},
actionColumns,
];
const handleSelectionChange = (selection: GridRowSelectionModel) => {
setSelectedCategories(selection as string[]);
};

return (
<Grid container gap={3} flexDirection="column">
<CategoryDialog {...getDisplayDialogs(addDialogCtl)} />
<CategoryDialog {...getDisplayDialogs(editDialogCtl)} />
<DeleteDialog
{...deleteDialogCtl}
callback={() => {
if (deleteDialogCtl?.data) deleteCategory(deleteDialogCtl.data);
callback={async () => {
if (selectedCategories.length > 0) {
deleteCategories(selectedCategories), setSelectedCategories([]);
deleteDialogCtl.closeDialog();
}
if (deleteDialogCtl?.data) {
{
deleteCategory(deleteDialogCtl.data);
deleteDialogCtl.closeDialog();
}
}
}}
/>
<Grid>
Expand Down Expand Up @@ -145,13 +172,30 @@ export const Categories = () => {
</Button>
</Grid>
) : null}
{selectedCategories.length > 0 && (
<Grid item>
<Button
startIcon={<DeleteIcon />}
variant="contained"
color="error"
onClick={() => deleteDialogCtl.openDialog(undefined)}
>
{t("button.delete")}
</Button>
</Grid>
)}
</Grid>
</PageHeader>
</Grid>
<Grid item xs={12}>
<Paper sx={{ padding: 2 }}>
<Grid>
<DataGrid columns={columns} {...dataGridProps} />
<DataGrid
columns={columns}
{...dataGridProps}
checkboxSelection
onRowSelectionModelChange={handleSelectionChange}
/>
</Grid>
</Paper>
</Grid>
Expand Down
68 changes: 68 additions & 0 deletions frontend/src/hooks/crud/useDeleteMany.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Copyright © 2024 Hexastack. All rights reserved.
*
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
* 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 { useMutation, useQueryClient } from "react-query";

import { QueryType, TMutationOptions } from "@/services/types";
import { IBaseSchema, IDynamicProps, TType } from "@/types/base.types";

import { isSameEntity } from "./helpers";
import { useEntityApiClient } from "../useApiClient";

export const useDeleteMany = <
TEntity extends IDynamicProps["entity"],
TAttr = TType<TEntity>["attributes"],
TBasic extends IBaseSchema = TType<TEntity>["basic"],
TFull extends IBaseSchema = TType<TEntity>["full"],
>(
entity: TEntity,
options?: Omit<
TMutationOptions<string, Error, string[], TBasic>,
"mutationFn" | "mutationKey"
> & {
invalidate?: boolean;
},
) => {
const api = useEntityApiClient<TAttr, TBasic, TFull>(entity);
const queryClient = useQueryClient();
const { invalidate = true, ...otherOptions } = options || {};

return useMutation({
mutationFn: async (ids: string[]) => {
const result = await api.deleteMany(ids);

queryClient.removeQueries({
predicate: ({ queryKey }) => {
const [qType, qEntity, qId] = queryKey;

return (
qType === QueryType.item &&
isSameEntity(qEntity, entity) &&
ids.includes(qId as string)
);
},
});

if (invalidate) {
queryClient.invalidateQueries({
predicate: ({ queryKey }) => {
const [qType, qEntity] = queryKey;

return (
(qType === QueryType.count || qType === QueryType.collection) &&
isSameEntity(qEntity, entity)
);
},
});
}

return result;
},
...otherOptions,
});
};
15 changes: 15 additions & 0 deletions frontend/src/services/api.class.ts
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,21 @@ export class EntityApiClient<TAttr, TBasic, TFull> extends ApiClient {
return data;
}

/**
* Bulk Delete entries.
*/
async deleteMany(ids: string[]) {
const { _csrf } = await this.getCsrf();
const { data } = await this.request.delete<string>(`${ROUTES[this.type]}`, {
data: {
_csrf,
ids,
},
});

return data;
}

/**
* Count elements.
*/
Expand Down

0 comments on commit 0066e81

Please sign in to comment.