mirror of
https://github.com/hexastack/hexabot
synced 2025-04-10 15:55:55 +00:00
Merge pull request #791 from yassine-sallemi/701-issue---label-bulk-delete-v2
fix: add label bulk delete
This commit is contained in:
commit
07e2ea84f7
@ -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';
|
||||
@ -22,6 +22,7 @@ import { RoleModel } from '@/user/schemas/role.schema';
|
||||
import { UserModel } from '@/user/schemas/user.schema';
|
||||
import { RoleService } from '@/user/services/role.service';
|
||||
import { UserService } from '@/user/services/user.service';
|
||||
import { NOT_FOUND_ID } from '@/utils/constants/mock';
|
||||
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
|
||||
import { getUpdateOneError } from '@/utils/test/errors/messages';
|
||||
import { labelFixtures } from '@/utils/test/fixtures/label';
|
||||
@ -48,6 +49,7 @@ describe('LabelController', () => {
|
||||
let labelService: LabelService;
|
||||
let label: Label;
|
||||
let labelToDelete: Label;
|
||||
let secondLabelToDelete: Label;
|
||||
let subscriberService: SubscriberService;
|
||||
|
||||
beforeAll(async () => {
|
||||
@ -87,6 +89,9 @@ describe('LabelController', () => {
|
||||
labelToDelete = (await labelService.findOne({
|
||||
name: 'TEST_TITLE_2',
|
||||
})) as Label;
|
||||
secondLabelToDelete = (await labelService.findOne({
|
||||
name: 'TEST_TITLE_3',
|
||||
})) as Label;
|
||||
});
|
||||
|
||||
afterEach(jest.clearAllMocks);
|
||||
@ -230,4 +235,32 @@ describe('LabelController', () => {
|
||||
).rejects.toThrow(getUpdateOneError(Label.name, labelToDelete.id));
|
||||
});
|
||||
});
|
||||
|
||||
describe('deleteMany', () => {
|
||||
it('should delete multiple labels', async () => {
|
||||
const valuesToDelete = [label.id, secondLabelToDelete.id];
|
||||
|
||||
const result = await labelController.deleteMany(valuesToDelete);
|
||||
|
||||
expect(result.deletedCount).toEqual(valuesToDelete.length);
|
||||
const remainingValues = await labelService.find({
|
||||
_id: { $in: valuesToDelete },
|
||||
});
|
||||
expect(remainingValues.length).toBe(0);
|
||||
});
|
||||
|
||||
it('should throw BadRequestException when no IDs are provided', async () => {
|
||||
await expect(labelController.deleteMany([])).rejects.toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
});
|
||||
|
||||
it('should throw NotFoundException when provided IDs do not exist', async () => {
|
||||
const nonExistentIds = [NOT_FOUND_ID, NOT_FOUND_ID.replace(/9/g, '8')];
|
||||
|
||||
await expect(labelController.deleteMany(nonExistentIds)).rejects.toThrow(
|
||||
NotFoundException,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
@ -24,6 +25,7 @@ import { CsrfCheck } from '@tekuconcept/nestjs-csrf';
|
||||
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';
|
||||
@ -125,4 +127,29 @@ export class LabelController extends BaseController<
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes multiple Labels by their IDs.
|
||||
* @param ids - IDs of Labels 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.labelService.deleteMany({
|
||||
_id: { $in: ids },
|
||||
});
|
||||
|
||||
if (deleteResult.deletedCount === 0) {
|
||||
this.logger.warn(`Unable to delete Labels with provided IDs: ${ids}`);
|
||||
throw new NotFoundException('Labels with provided IDs not found');
|
||||
}
|
||||
|
||||
this.logger.log(`Successfully deleted Labels with IDs: ${ids}`);
|
||||
return deleteResult;
|
||||
}
|
||||
}
|
||||
|
@ -82,9 +82,13 @@ export class LabelRepository extends BaseRepository<
|
||||
>,
|
||||
_criteria: TFilterQuery<Label>,
|
||||
): Promise<void> {
|
||||
const labels = await this.find(
|
||||
typeof _criteria === 'string' ? { _id: _criteria } : _criteria,
|
||||
);
|
||||
const ids = Array.isArray(_criteria._id?.$in)
|
||||
? _criteria._id.$in
|
||||
: Array.isArray(_criteria._id)
|
||||
? _criteria._id
|
||||
: [_criteria._id];
|
||||
|
||||
const labels = await this.find({ _id: { $in: ids } });
|
||||
this.eventEmitter.emit('hook:label:delete', labels);
|
||||
}
|
||||
}
|
||||
|
@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { OnEvent } from '@nestjs/event-emitter';
|
||||
|
||||
import { AttachmentService } from '@/attachment/services/attachment.service';
|
||||
import EventWrapper from '@/channel/lib/EventWrapper';
|
||||
@ -25,6 +26,7 @@ import { getRandom } from '@/utils/helpers/safeRandom';
|
||||
import { BlockDto } from '../dto/block.dto';
|
||||
import { BlockRepository } from '../repositories/block.repository';
|
||||
import { Block, BlockFull, BlockPopulate } from '../schemas/block.schema';
|
||||
import { Label } from '../schemas/label.schema';
|
||||
import { Context } from '../schemas/types/context';
|
||||
import {
|
||||
BlockMessage,
|
||||
@ -604,4 +606,32 @@ export class BlockService extends BaseService<
|
||||
}
|
||||
throw new Error('Invalid message format.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `trigger_labels` and `assign_labels` fields of a block when a label is deleted.
|
||||
*
|
||||
*
|
||||
* This method removes the deleted label from the `trigger_labels` and `assign_labels` fields of all blocks that have the label.
|
||||
*
|
||||
* @param label The label that is being deleted.
|
||||
*/
|
||||
@OnEvent('hook:label:delete')
|
||||
async handleLabelDelete(labels: Label[]) {
|
||||
const blocks = await this.find({
|
||||
$or: [
|
||||
{ trigger_labels: { $in: labels.map((l) => l.id) } },
|
||||
{ assign_labels: { $in: labels.map((l) => l.id) } },
|
||||
],
|
||||
});
|
||||
|
||||
for (const block of blocks) {
|
||||
const trigger_labels = block.trigger_labels.filter(
|
||||
(labelId) => !labels.find((l) => l.id === labelId),
|
||||
);
|
||||
const assign_labels = block.assign_labels.filter(
|
||||
(labelId) => !labels.find((l) => l.id === labelId),
|
||||
);
|
||||
await this.updateOne(block.id, { trigger_labels, assign_labels });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -30,6 +30,7 @@ import { WebsocketGateway } from '@/websocket/websocket.gateway';
|
||||
|
||||
import { SubscriberDto, SubscriberUpdateDto } from '../dto/subscriber.dto';
|
||||
import { SubscriberRepository } from '../repositories/subscriber.repository';
|
||||
import { Label } from '../schemas/label.schema';
|
||||
import {
|
||||
Subscriber,
|
||||
SubscriberFull,
|
||||
@ -208,4 +209,24 @@ export class SubscriberService extends BaseService<
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the `labels` field of a subscriber when a label is deleted.
|
||||
*
|
||||
* This method removes the deleted label from the `labels` field of all subscribers that have the label.
|
||||
*
|
||||
* @param label The label that is being deleted.
|
||||
*/
|
||||
@OnEvent('hook:label:delete')
|
||||
async handleLabelDelete(labels: Label[]) {
|
||||
const subscribers = await this.find({
|
||||
labels: { $in: labels.map((l) => l.id) },
|
||||
});
|
||||
for (const subscriber of subscribers) {
|
||||
const updatedLabels = subscriber.labels.filter(
|
||||
(label) => !labels.find((l) => l.id === label),
|
||||
);
|
||||
await this.updateOne(subscriber.id, { labels: updatedLabels });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
11
api/src/utils/test/fixtures/label.ts
vendored
11
api/src/utils/test/fixtures/label.ts
vendored
@ -43,6 +43,17 @@ export const labels: TLabelFixtures['values'][] = [
|
||||
name: 'TEST_TITLE_2',
|
||||
title: 'test title 2',
|
||||
},
|
||||
{
|
||||
description: 'test description 3',
|
||||
label_id: {
|
||||
messenger: 'messenger',
|
||||
web: 'web',
|
||||
twitter: 'twitter',
|
||||
dimelo: 'dimelo',
|
||||
},
|
||||
name: 'TEST_TITLE_3',
|
||||
title: 'test title 3',
|
||||
},
|
||||
];
|
||||
|
||||
export const labelFixtures = getFixturesWithDefaultValues<
|
||||
|
@ -8,8 +8,10 @@
|
||||
|
||||
import { faTags } from "@fortawesome/free-solid-svg-icons";
|
||||
import AddIcon from "@mui/icons-material/Add";
|
||||
import DeleteIcon from "@mui/icons-material/Delete";
|
||||
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 { ConfirmDialogBody } from "@/app-components/dialogs";
|
||||
import { FilterTextfield } from "@/app-components/inputs/FilterTextfield";
|
||||
@ -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 { useDialogs } from "@/hooks/useDialogs";
|
||||
import { useHasPermission } from "@/hooks/useHasPermission";
|
||||
@ -48,14 +51,16 @@ export const Labels = () => {
|
||||
params: searchPayload,
|
||||
},
|
||||
);
|
||||
const { mutate: deleteLabel } = useDelete(EntityType.LABEL, {
|
||||
const options = {
|
||||
onError: () => {
|
||||
toast.error(t("message.internal_server_error"));
|
||||
},
|
||||
onSuccess() {
|
||||
toast.success(t("message.item_delete_success"));
|
||||
},
|
||||
});
|
||||
};
|
||||
const { mutate: deleteLabel } = useDelete(EntityType.LABEL, options);
|
||||
const { mutate: deleteLabels } = useDeleteMany(EntityType.LABEL, options);
|
||||
const actionColumns = useActionColumns<ILabel>(
|
||||
EntityType.LABEL,
|
||||
[
|
||||
@ -78,6 +83,7 @@ export const Labels = () => {
|
||||
],
|
||||
t("label.operations"),
|
||||
);
|
||||
const [selectedLabels, setSelectedLabels] = useState<string[]>([]);
|
||||
const columns: GridColDef<ILabel>[] = [
|
||||
{ field: "id", headerName: "ID" },
|
||||
{
|
||||
@ -123,7 +129,6 @@ export const Labels = () => {
|
||||
|
||||
headerAlign: "left",
|
||||
},
|
||||
|
||||
{
|
||||
minWidth: 140,
|
||||
field: "createdAt",
|
||||
@ -148,6 +153,9 @@ export const Labels = () => {
|
||||
},
|
||||
actionColumns,
|
||||
];
|
||||
const handleSelectionChange = (selection: GridRowSelectionModel) => {
|
||||
setSelectedLabels(selection as string[]);
|
||||
};
|
||||
|
||||
return (
|
||||
<Grid container gap={3} flexDirection="column">
|
||||
@ -175,12 +183,35 @@ export const Labels = () => {
|
||||
</Button>
|
||||
</Grid>
|
||||
) : null}
|
||||
<Button
|
||||
color="error"
|
||||
variant="contained"
|
||||
onClick={async () => {
|
||||
const isConfirmed = await dialogs.confirm(ConfirmDialogBody, {
|
||||
mode: "selection",
|
||||
count: selectedLabels.length,
|
||||
});
|
||||
|
||||
if (isConfirmed) {
|
||||
deleteLabels(selectedLabels);
|
||||
}
|
||||
}}
|
||||
disabled={!selectedLabels.length}
|
||||
startIcon={<DeleteIcon />}
|
||||
>
|
||||
{t("button.delete")}
|
||||
</Button>
|
||||
</Grid>
|
||||
</PageHeader>
|
||||
<Grid item xs={12}>
|
||||
<Paper sx={{ padding: 2 }}>
|
||||
<Grid>
|
||||
<DataGrid columns={columns} {...dataGridProps} />
|
||||
<DataGrid
|
||||
columns={columns}
|
||||
{...dataGridProps}
|
||||
checkboxSelection
|
||||
onRowSelectionModelChange={handleSelectionChange}
|
||||
/>
|
||||
</Grid>
|
||||
</Paper>
|
||||
</Grid>
|
||||
|
Loading…
Reference in New Issue
Block a user