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

Added all select button in advanced search page #1375

Merged
merged 15 commits into from
Mar 10, 2025
Merged
Show file tree
Hide file tree
Changes from all 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: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@
## In development

### Added
* Added processing to be able to delete rest of Items as well as that are not checked
in the AdvancedPageResult page.
Contributed by @hinashi, @userlocalhost

### Changed

Expand Down
6 changes: 4 additions & 2 deletions airone/lib/acl.py
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import enum

from airone.lib.types import BaseIntEnum

__all__ = ["ACLType", "ACLObjType"]


@enum.unique
class ACLObjType(enum.IntEnum):
class ACLObjType(BaseIntEnum):
Entity = 1 << 0
EntityAttr = 1 << 1
Entry = 1 << 2
EntryAttr = 1 << 3
Category = 1 << 4


class ACLType(enum.IntEnum):
class ACLType(BaseIntEnum):
Nothing = 1 << 0
Readable = 1 << 1
Writable = 1 << 2
Expand Down
4 changes: 2 additions & 2 deletions airone/lib/elasticsearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

from airone.lib.acl import ACLType
from airone.lib.log import Logger
from airone.lib.types import AttrType
from airone.lib.types import AttrType, BaseIntEnum
from entity.models import Entity
from entry.settings import CONFIG
from user.models import User
Expand Down Expand Up @@ -42,7 +42,7 @@ class AdvancedSearchResults(BaseModel):


@enum.unique
class FilterKey(enum.IntEnum):
class FilterKey(BaseIntEnum):
CLEARED = 0
EMPTY = 1
NON_EMPTY = 2
Expand Down
8 changes: 7 additions & 1 deletion airone/lib/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,14 @@
from typing import Any


class BaseIntEnum(enum.IntEnum):
@classmethod
def isin(cls, v):
return v in cls.__members__.values()


@enum.unique
class AttrType(enum.IntEnum):
class AttrType(BaseIntEnum):
OBJECT = 1 << 0
STRING = 1 << 1
TEXT = 1 << 2
Expand Down
2 changes: 1 addition & 1 deletion apiclient/typescript-fetch/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dmm-com/airone-apiclient-typescript-fetch",
"version": "0.5.0",
"version": "0.7.1",
"description": "AirOne APIv2 client in TypeScript",
"main": "src/autogenerated/index.ts",
"scripts": {
Expand Down
61 changes: 60 additions & 1 deletion entry/api_v2/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import re
from collections import Counter
from copy import deepcopy
Expand Down Expand Up @@ -25,7 +26,12 @@
RequiredParameterError,
YAMLParser,
)
from airone.lib.elasticsearch import AdvancedSearchResultRecord, AdvancedSearchResults, AttrHint
from airone.lib.elasticsearch import (
AdvancedSearchResultRecord,
AdvancedSearchResults,
AttrHint,
FilterKey,
)
from airone.lib.types import AttrType
from api_v1.entry.serializer import EntrySearchChainSerializer
from entity.models import Entity, EntityAttr
Expand Down Expand Up @@ -836,15 +842,35 @@ class EntryAttributeValueRestoreAPI(generics.UpdateAPIView):
OpenApiParameter(
"ids", {"type": "array", "items": {"type": "number"}}, OpenApiParameter.QUERY
),
OpenApiParameter("isAll", OpenApiTypes.BOOL, OpenApiParameter.QUERY),
OpenApiParameter("attrinfo", OpenApiTypes.STR, OpenApiParameter.QUERY),
],
)
class EntryBulkDeleteAPI(generics.DestroyAPIView):
# (Execuse)
# Specifying serializer_class is necessary for passing processing
# of npm run generate
serializer_class = EntryUpdateSerializer
internal_limit = 10000

def _validate_attrinfo(self):
attrinfo_raw = self.request.query_params.get("attrinfo", "[]")
try:
json_loaded_value = json.loads(attrinfo_raw)
for info in json_loaded_value:
if not any(x in info for x in ["name", "filterKey", "keyword"]):
raise RequiredParameterError("(00)Invalid attrinfo was specified")
if not FilterKey.isin(int(info["filterKey"])):
raise RequiredParameterError("(01)Invalid attrinfo was specified")
except Exception as e:
raise RequiredParameterError(e)

return json_loaded_value

def delete(self, request: Request, *args, **kwargs) -> Response:
# validate "attrinfo" parameter and save it before deleting item processing
attrinfo = self._validate_attrinfo()

ids: list[str] = self.request.query_params.getlist("ids", [])
if len(ids) == 0 or not all([id.isdecimal() for id in ids]):
raise RequiredParameterError("some ids are invalid")
Expand All @@ -857,10 +883,43 @@ def delete(self, request: Request, *args, **kwargs) -> Response:
if not all([user.has_permission(e, ACLType.Writable) for e in entries]):
raise PermissionDenied("deleting some entries is not allowed")

# Run jobs that delete user specified Items
target_model = entries.first().schema if entries.first() else None
for entry in entries:
job: Job = Job.new_delete_entry_v2(user, entry)
job.run()

# Run jobs that delete rest of Items of same Model
isAll: bool = self.request.query_params.get("isAll", False)
if isinstance(isAll, str):
isAll = isAll.lower() == "true"

if isAll and target_model is not None:
results = AdvancedSearchService.search_entries(
request.user,
hint_entity_ids=list(set([e.schema.id for e in entries])),
hint_attrs=[
AttrHint(
**{
"name": x["name"],
"filter_key": FilterKey(int(x["filterKey"])),
"keyword": x["keyword"],
}
)
for x in attrinfo
],
limit=self.internal_limit,
)

entries = Entry.objects.filter(
id__in=[x.entry["id"] for x in results.ret_values],
schema=target_model,
is_active=True,
).exclude(id__in=ids)
for entry in entries:
another_job: Job = Job.new_delete_entry_v2(user, entry)
another_job.run()

return Response(status=status.HTTP_204_NO_CONTENT)


Expand Down
96 changes: 96 additions & 0 deletions entry/tests/test_api_v2.py
Original file line number Diff line number Diff line change
Expand Up @@ -4852,3 +4852,99 @@ def test_destroy_entries_notify(self, mock_task):
self.client.delete("/entry/api/v2/bulk_delete/?ids=%s" % entry.id, None, "application/json")

self.assertTrue(mock_task.called)

@patch("entry.tasks.delete_entry_v2.delay", Mock(side_effect=tasks.delete_entry_v2))
def test_delete_entries_without_all_parameter(self):
# create test Items that would be deleted in this test
items = [self.add_entry(self.user, "item-%d" % i, self.entity) for i in range(5)]

# send request to delete only items[0]
resp = self.client.delete(
"/entry/api/v2/bulk_delete/?ids=%s" % items[0].id, None, "application/json"
)
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content, b"")

# check only items[0] was deleted and rest of items are still alive.
[x.refresh_from_db() for x in items]
self.assertFalse(items[0].is_active)
self.assertTrue(all(x.is_active for x in items[1:]))

# send request to delete all items
resp = self.client.delete(
"/entry/api/v2/bulk_delete/?ids=%s&isAll=false" % items[1].id, None, "application/json"
)
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content, b"")

# check only items[0] and items[1] are delete, and rest of items are still alived
[x.refresh_from_db() for x in items]
self.assertFalse(all(x.is_active for x in items[:2]))
self.assertTrue(all(x.is_active for x in items[2:]))

@patch("entry.tasks.delete_entry_v2.delay", Mock(side_effect=tasks.delete_entry_v2))
def test_delete_entries_with_all_parameter(self):
# create test Items that would be deleted in this test
items = [self.add_entry(self.user, "item-%d" % i, self.entity) for i in range(5)]

# send request to delete only items[0]
resp = self.client.delete(
"/entry/api/v2/bulk_delete/?ids=%s" % items[0].id, None, "application/json"
)
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content, b"")

# check only items[0] was deleted and rest of items are still alive.
[x.refresh_from_db() for x in items]
self.assertFalse(items[0].is_active)
self.assertTrue(all(x.is_active for x in items[1:]))

# send request to delete all items
resp = self.client.delete(
"/entry/api/v2/bulk_delete/?ids=%s&isAll=true" % items[1].id, None, "application/json"
)
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content, b"")

# check all items were deleted.
[x.refresh_from_db() for x in items]
self.assertFalse(any(x.is_active for x in items))

@patch("entry.tasks.delete_entry_v2.delay", Mock(side_effect=tasks.delete_entry_v2))
def test_delete_entries_with_all_parameter_and_attrinfo(self):
# create test Items that would be deleted in this test
items = [
self.add_entry(
self.user,
"item-%d" % i,
self.entity,
values={
"val": "hoge" if i < 3 else "fuga",
},
)
for i in range(5)
]

# send request to delete all items with attrinfo
attrinfo_as_str = json.dumps(
[
{"name": "ref", "keyword": "", "filterKey": "0"},
{"name": "val", "keyword": "hoge", "filterKey": "3"},
]
)
resp = self.client.delete(
"/entry/api/v2/bulk_delete/?ids=%s&isAll=true&attrinfo=%s"
% (
items[0].id,
attrinfo_as_str,
),
None,
"application/json",
)
self.assertEqual(resp.status_code, 204)
self.assertEqual(resp.content, b"")

# check only items, which are matched with "val=hoge", were deleted.
[x.refresh_from_db() for x in items]
self.assertFalse(any(x.is_active for x in items[:3]))
self.assertTrue(any(x.is_active for x in items[3:]))
14 changes: 13 additions & 1 deletion frontend/src/components/common/Confirmable.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
import { Box, Button, Dialog, DialogActions, DialogTitle } from "@mui/material";
import {
Box,
Button,
Dialog,
DialogActions,
DialogTitle,
DialogContent,
} from "@mui/material";
import React, { ReactElement, FC, SyntheticEvent, useState } from "react";

interface Props {
componentGenerator: (handleOpen: () => void) => ReactElement;
dialogTitle: string;
onClickYes: (e: SyntheticEvent) => void;
content?: ReactElement;
}

export const Confirmable: FC<Props> = ({
componentGenerator,
dialogTitle,
onClickYes,
content,
}) => {
const [open, setOpen] = useState(false);

Expand All @@ -37,6 +46,9 @@ export const Confirmable: FC<Props> = ({
aria-describedby="alert-dialog-description"
>
<DialogTitle id="alert-dialog-title">{dialogTitle}</DialogTitle>
<DialogContent>
<>{content}</>
</DialogContent>
<DialogActions>
<Button onClick={handleConfirmed} color="primary" autoFocus>
Yes
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/entry/SearchResults.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ test("should render a component with essential props", function () {
/* do nothing */
}}
bulkOperationEntryIds={[]}
handleChangeBulkOperationEntryId={() => {
setBulkOperationEntryIds={() => {
/* do nothing */
}}
hasReferral={false}
Expand Down
23 changes: 21 additions & 2 deletions frontend/src/components/entry/SearchResults.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ interface Props {
defaultReferralFilter?: string;
defaultAttrsFilter?: AttrsFilter;
bulkOperationEntryIds: Array<number>;
handleChangeBulkOperationEntryId: (id: number, checked: boolean) => void;
setBulkOperationEntryIds: (entryIds: Array<number>) => void;
entityIds: number[];
searchAllEntities: boolean;
joinAttrs: AdvancedSearchJoinAttrInfo[];
Expand All @@ -75,7 +75,7 @@ export const SearchResults: FC<Props> = ({
defaultReferralFilter,
defaultAttrsFilter = {},
bulkOperationEntryIds,
handleChangeBulkOperationEntryId,
setBulkOperationEntryIds,
entityIds,
searchAllEntities,
joinAttrs,
Expand All @@ -96,6 +96,22 @@ export const SearchResults: FC<Props> = ({
return [_attrNames, _attrTypes];
}, [defaultAttrsFilter, results.values]);

const handleChangeBulkOperationEntryId = (id: number, checked: boolean) => {
if (checked) {
setBulkOperationEntryIds([...bulkOperationEntryIds, id]);
} else {
setBulkOperationEntryIds(bulkOperationEntryIds.filter((i) => i !== id));
}
};

const handleChangeAllBulkOperationEntryIds = (checked: boolean) => {
if (checked) {
setBulkOperationEntryIds(results.values.map((v) => v.entry.id));
} else {
setBulkOperationEntryIds([]);
}
};

return (
<Box display="flex" flexDirection="column">
<StyledBox>
Expand All @@ -111,6 +127,9 @@ export const SearchResults: FC<Props> = ({
searchAllEntities={searchAllEntities}
joinAttrs={joinAttrs}
refreshSearchResults={setSearchResults}
handleChangeAllBulkOperationEntryIds={
handleChangeAllBulkOperationEntryIds
}
isReadonly={isReadonly}
/>
<TableBody>
Expand Down
Loading
Loading