-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathsaved_search.py
More file actions
246 lines (214 loc) · 8.61 KB
/
saved_search.py
File metadata and controls
246 lines (214 loc) · 8.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Saved Search API."""
# Standard Python Libraries
from datetime import datetime, timezone
import uuid
# Third-Party Libraries
from django.http import JsonResponse
from fastapi import HTTPException
from ..models import SavedSearch, User
def validate_name(value: str):
"""Validate name."""
name = value.strip()
if name == "":
raise HTTPException(status_code=400, detail="Name cannot be empty")
all_saved_searches = SavedSearch.objects.all()
for search in all_saved_searches:
if search.name.strip() == name:
raise HTTPException(status_code=400, detail="Name already exists")
def create_saved_search(request):
"""Create saved search."""
validate_name(request.get("name"))
try:
# Process filter values when selecting organizations
def process_filter_values(values):
processed_values = []
for value in values:
if isinstance(value, dict):
# Include only the required fields
processed_values.append(
{
"id": value.get("id"),
"name": value.get("name"),
"regionId": value.get("regionId"),
"rootDomains": value.get("rootDomains", []),
}
)
else:
processed_values.append(value)
return processed_values
filters = [
{
"type": f.type,
"field": f.field,
"values": process_filter_values(f.values),
}
for f in request.get("filters", [])
]
search = SavedSearch.objects.create(
name=request.get("name"),
count=request.get("count", 0), # Default to 0 if count does not exist
sortDirection=request.get("sortDirection", ""),
sortField=request.get("sortField", ""),
searchTerm=request.get("searchTerm", ""),
searchPath=request.get("searchPath", ""),
filters=filters,
createdById=request.get("createdById"),
)
response = {
"id": str(search.id),
"createdAt": search.createdAt,
"updatedAt": search.updatedAt,
"name": search.name,
"searchTerm": search.searchTerm,
"sortDirection": search.sortDirection,
"sortField": search.sortField,
"count": search.count,
"filters": search.filters,
"searchPath": search.searchPath,
"createdById": search.createdById.id,
}
search.save()
return response
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))
def list_saved_searches(user):
"""List all saved searches."""
try:
all_saved_searches = SavedSearch.objects.all()
saved_search_list = []
for search in all_saved_searches:
if search.createdById != user:
continue
response = {
"id": str(search.id),
"createdAt": search.createdAt,
"updatedAt": search.updatedAt,
"name": search.name,
"searchTerm": search.searchTerm,
"sortDirection": search.sortDirection,
"sortField": search.sortField,
"count": search.count,
"filters": search.filters,
"searchPath": search.searchPath,
"createdById": search.createdById.id,
}
saved_search_list.append(response)
return {
"result": list(saved_search_list),
"count": len(list(saved_search_list)),
}
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))
def get_saved_search(saved_search_id, user):
"""Get saved search."""
if user.userType == "globalView":
raise HTTPException(
status_code=404, detail="Global View users cannot retrieve saved searches."
)
if not uuid.UUID(saved_search_id):
raise HTTPException({"error": "Invalid UUID"})
try:
saved_search = SavedSearch.objects.get(id=saved_search_id)
if saved_search.createdById.id != user.id:
raise HTTPException(status_code=404, detail="Saved search not found")
response = {
"id": str(saved_search.id),
"createdAt": saved_search.createdAt,
"updatedAt": saved_search.updatedAt,
"name": saved_search.name,
"searchTerm": saved_search.searchTerm,
"sortDirection": saved_search.sortDirection,
"sortField": saved_search.sortField,
"count": saved_search.count,
"filters": saved_search.filters,
"searchPath": saved_search.searchPath,
"createdById": saved_search.createdById.id,
}
return response
except SavedSearch.DoesNotExist as dne:
raise HTTPException(status_code=404, detail=str(dne))
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))
def update_saved_search(request, user):
"""Update saved search."""
if not uuid.UUID(request["saved_search_id"]):
raise HTTPException(status_code=404, detail={"error": "Invalid UUID"})
try:
# Process filter values when selecting organizations
def process_filter_values(values):
processed_values = []
for value in values:
if isinstance(value, dict):
# Include only the required fields
processed_values.append(
{
"id": value.get("id"),
"name": value.get("name"),
"regionId": value.get("regionId"),
"rootDomains": value.get("rootDomains", []),
}
)
else:
processed_values.append(value)
return processed_values
filters = [
{
"type": f.type,
"field": f.field,
"values": process_filter_values(f.values),
}
for f in request.get("filters", [])
]
saved_search = SavedSearch.objects.get(id=request["saved_search_id"])
if saved_search.createdById.id != user.id:
raise HTTPException(status_code=404, detail="Saved search not found")
name = request["name"].strip()
if name == "":
raise HTTPException(status_code=400, detail="Name cannot be empty")
saved_search.name = request["name"]
saved_search.updatedAt = datetime.now(timezone.utc)
saved_search.searchTerm = request["searchTerm"]
saved_search.save()
response = {
"name": saved_search.name,
"searchTerm": saved_search.searchTerm,
"sortDirection": saved_search.sortDirection,
"sortField": saved_search.sortField,
"count": saved_search.count,
"filters": filters,
"searchPath": saved_search.searchPath,
}
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except SavedSearch.DoesNotExist as dne:
raise HTTPException(status_code=404, detail=str(dne))
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))
return response
def delete_saved_search(saved_search_id, user):
"""Delete saved search by id."""
if not uuid.UUID(saved_search_id):
raise HTTPException(status_code=404, detail={"error": "Invalid UUID"})
try:
search = SavedSearch.objects.get(id=saved_search_id)
if search.createdById.id != user.id:
raise HTTPException(status_code=404, detail="Saved search not found")
search.delete()
return JsonResponse(
{
"status": "success",
"message": "Saved search id:{} deleted.".format(saved_search_id),
}
)
except User.DoesNotExist:
raise HTTPException(status_code=404, detail="User not found")
except SavedSearch.DoesNotExist as dne:
raise HTTPException(status_code=404, detail=str(dne))
except Exception as e:
raise HTTPException(status_code=404, detail=str(e))