Coverage for src/history/views.py: 0%

190 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-04 10:23 +0000

1import json 

2from collections.abc import Callable 

3from typing import TYPE_CHECKING, Any 

4from urllib.parse import urlencode 

5 

6from django.core.paginator import Paginator 

7from django.db import transaction 

8from django.db.models import F 

9from django.http import HttpResponse, HttpResponseRedirect, JsonResponse 

10from django.http.response import HttpResponseBadRequest 

11from django.urls import reverse, reverse_lazy 

12from django.utils import timezone 

13from django.views import View 

14from django.views.generic import TemplateView 

15from django.views.generic.base import ContextMixin 

16from django.views.generic.detail import BaseDetailView 

17from django.views.generic.edit import DeleteView, UpdateView 

18from opentelemetry import trace 

19from ptf import views as ptf_views 

20from ptf.exceptions import ServerUnderMaintenance 

21from ptf.models.classes.article import Article 

22from ptf.models.classes.collection import Collection 

23from requests.exceptions import Timeout 

24 

25from history.model_data import HistoryEventDict, HistoryEventStatus, HistoryEventType 

26from history.models import HistoryEvent 

27from history.utils import ( 

28 get_history_error_warning_counts, 

29 get_history_last_event_by, 

30 insert_history_event, 

31) 

32 

33if TYPE_CHECKING: 

34 from django import http 

35 from ptf.models.classes.resource import Resource 

36 

37tracer = trace.get_tracer(__name__) 

38 

39 

40def manage_exceptions( 

41 event: HistoryEventDict, 

42 exception: BaseException, 

43): 

44 if type(exception).__name__ == "ServerUnderMaintenance": 

45 message = " - ".join([str(exception), "Please try again later"]) 

46 else: 

47 message = " ".join([str(exception)]) 

48 

49 event["message"] = message 

50 

51 insert_history_event(event) 

52 

53 

54class HistoryEventUpdateView(UpdateView): 

55 model = HistoryEvent 

56 fields = ["status", "message"] 

57 success_url = reverse_lazy("history") 

58 

59 

60def matching_decorator(func: Callable[[Any, str], str], is_article): 

61 def inner(*args, **kwargs): 

62 article: Article 

63 

64 if is_article: 

65 article = args[0] 

66 else: 

67 article = args[0].resource.cast() 

68 

69 event: HistoryEventDict = { 

70 "type": "matching", 

71 "pid": article.pid, 

72 "col": article.get_top_collection(), 

73 "status": HistoryEventStatus.OK, 

74 } 

75 # Merge matching ids (can be zbl, numdam...) 

76 try: 

77 id_value = func(*args, **kwargs) 

78 

79 insert_history_event(event) 

80 return id_value 

81 

82 except Timeout as exception: 

83 """ 

84 Exception caused by the requests module: store it as a warning 

85 """ 

86 event["status"] = HistoryEventStatus.WARNING 

87 manage_exceptions(event, exception) 

88 raise 

89 

90 except ServerUnderMaintenance as exception: 

91 event["status"] = HistoryEventStatus.ERROR 

92 event["type"] = "deploy" 

93 manage_exceptions(event, exception) 

94 raise 

95 

96 except Exception as exception: 

97 event["status"] = HistoryEventStatus.ERROR 

98 manage_exceptions(event, exception) 

99 raise 

100 

101 return inner 

102 

103 

104def execute_and_record_func( 

105 type: HistoryEventType, 

106 pid, 

107 colid, 

108 func, 

109 message="", 

110 record_error_only=False, 

111 user=None, 

112 type_error=None, 

113 *func_args, 

114 **func_kwargs, 

115): 

116 status = 200 

117 func_result = None 

118 collection = None 

119 if colid not in ["ALL", "numdam"]: 

120 collection = Collection.objects.get(pid=colid) 

121 event: HistoryEventDict = { 

122 "type": type, 

123 "pid": pid, 

124 "col": collection, 

125 "status": HistoryEventStatus.OK, 

126 "message": message, 

127 } 

128 

129 try: 

130 func_result = func(*func_args, **func_kwargs) 

131 

132 if type_error: 

133 event["type_error"] = type_error 

134 

135 if not record_error_only: 

136 insert_history_event(event) 

137 except Timeout as exception: 

138 """ 

139 Exception caused by the requests module: store it as a warning 

140 """ 

141 event["status"] = HistoryEventStatus.WARNING 

142 

143 event["message"] = message 

144 

145 manage_exceptions(event, exception) 

146 raise 

147 except Exception as exception: 

148 event["status"] = HistoryEventStatus.ERROR 

149 

150 event["message"] = message 

151 manage_exceptions(event, exception) 

152 raise 

153 return func_result, status, message 

154 

155 

156def edit_decorator(func): 

157 def inner(self, action, *args, **kwargs): 

158 resource_obj: Resource = self.resource.cast() 

159 pid = resource_obj.pid 

160 colid = resource_obj.get_top_collection().pid 

161 

162 message = "" 

163 if hasattr(self, "obj"): 

164 # Edit 1 item (ExtId or BibItemId) 

165 obj = self.obj 

166 if hasattr(self, "parent"): 

167 parent = self.parent 

168 if parent: 

169 message += "[" + str(parent.sequence) + "] " 

170 list_ = obj.id_type.split("-") 

171 id_type = obj.id_type if len(list_) == 0 else list_[0] 

172 message += id_type + ":" + obj.id_value + " " + action 

173 else: 

174 message += "All " + action 

175 

176 args = (self, action) + args 

177 

178 execute_and_record_func( 

179 "edit", pid, colid, func, message, False, None, None, *args, **kwargs 

180 ) 

181 

182 return inner 

183 

184 

185ptf_views.UpdateExtIdView.update_obj = edit_decorator(ptf_views.UpdateExtIdView.update_obj) 

186 

187 

188def getLastHistoryImport(pid): 

189 data = get_history_last_event_by(type="import", pid=pid) 

190 return data 

191 

192 

193class HistoryContextMixin(ContextMixin): 

194 def get_context_data(self, **kwargs): 

195 context = super().get_context_data(**kwargs) 

196 error_count, warning_count = get_history_error_warning_counts() 

197 context["warning_count"] = warning_count 

198 context["error_count"] = error_count 

199 

200 # if isinstance(last_clockss_event, datetime): 

201 # now = timezone.now() 

202 # td = now - last_clockss_event['created_on'] 

203 # context['last_clockss_event'] = td.days 

204 return context 

205 

206 

207class HistoryView(TemplateView, HistoryContextMixin): 

208 template_name = "history.html" 

209 accepted_params = ["type", "col", "status", "month"] 

210 

211 def get_context_data(self, **kwargs): 

212 context = super().get_context_data(**kwargs) 

213 

214 filters = {} 

215 

216 urlparams = {k: v[0] if isinstance(v, list) else v for k, v in self.request.GET.items()} 

217 urlparams.pop("page", None) 

218 urlparams.pop("search", None) 

219 

220 for filter in self.accepted_params: 

221 value = self.request.GET.get(filter, None) 

222 if value: 

223 filters[filter] = value 

224 

225 # Get current URL params without current filterurlpatterns 

226 _params = {**urlparams} 

227 _params.pop(filter, None) 

228 

229 context[filter + "_link"] = "?" + urlencode(_params) 

230 

231 # filter_by_month = False # Ignore months for Now 

232 # filters.setdefault("status", Q(status="ERROR") | Q(status="WARNING")) 

233 

234 # if filter_by_month: 

235 # today = datetime.datetime.today() 

236 # filters["created_on__year"] = today.year 

237 # filters["created_on__month"] = today.month 

238 if "col" in filters: 

239 filters["col__pid"] = filters["col"] 

240 del filters["col"] 

241 qs = HistoryEvent.objects.filter(**filters).order_by("-created_on") 

242 

243 paginator = Paginator(qs, 50) 

244 try: 

245 page = int(self.request.GET.get("page", 1)) 

246 except ValueError: 

247 page = 1 

248 

249 page = min(page, paginator.num_pages) 

250 

251 context["element_count"] = HistoryEvent.objects.all().count() 

252 context["page_obj"] = paginator.get_page(page) 

253 context["paginator"] = { 

254 "page_range": paginator.get_elided_page_range(number=page, on_each_side=2, on_ends=1), 

255 } 

256 

257 context["now"] = timezone.now() 

258 

259 filters.pop("col__pid", None) 

260 context["collections"] = ( 

261 HistoryEvent.objects.filter(col__isnull=False, **filters) 

262 .values(colid=F("col__pid"), name=F("col__title_html")) 

263 .distinct("col__title_html") 

264 .order_by("col__title_html") 

265 ) 

266 return context 

267 

268 

269class HistoryClearView(TemplateView): 

270 model = HistoryEvent 

271 http_method_names = ["post"] 

272 template_name = "blocks/history/historyevent_confirm_clear.html" 

273 success_url = reverse_lazy("history") 

274 

275 @transaction.atomic 

276 def post(self, *args): 

277 HistoryEvent.objects.all().delete() 

278 return HttpResponseRedirect(reverse("history")) 

279 

280 

281class HistoryEventDeleteView(DeleteView): 

282 model = HistoryEvent 

283 success_url = reverse_lazy("history") 

284 

285 

286class HistoryAPIView(BaseDetailView): 

287 model = HistoryEvent 

288 

289 http_method_names = ["get"] 

290 

291 @tracer.start_as_current_span("HistoryAPIView.get") 

292 def get(self, request: "http.HttpRequest", pk: int, datatype: str): 

293 object: HistoryEvent = self.get_object() 

294 if datatype == "message": 

295 return HttpResponse(object.message) 

296 if datatype == "table": 

297 data = [] 

298 for a in object.children.all().prefetch_related("resource"): 

299 entry = { 

300 "type": a.type, 

301 "status": a.status, 

302 "status_message": a.status_message, 

303 "message": a.message, 

304 "score": a.score, 

305 "url": a.url, 

306 } 

307 if a.resource: 

308 entry["resource_pid"] = a.resource.pid 

309 data.append(entry) 

310 return JsonResponse( 

311 { 

312 "data": data, 

313 "headers": [ 

314 "resource_pid", 

315 "type", 

316 "status", 

317 "status_message", 

318 "message", 

319 "score", 

320 "url", 

321 ], 

322 "source": object.source, 

323 "pid": object.pid, 

324 "col": object.col.pid if object.col else None, 

325 "date": object.created_on, 

326 } 

327 ) 

328 return HttpResponseBadRequest() 

329 

330 

331class HistoryEventInsert(View): 

332 def post(self, request: "http.HttpRequest"): 

333 # Todo : Sanitarization ? 

334 event = json.loads(request.body.decode("utf-8")) 

335 if "colid" in event: 

336 colid = event["colid"] 

337 del event["colid"] 

338 collection = Collection.objects.get(pid=colid) 

339 event["col"] = collection 

340 insert_history_event(event) 

341 response = HttpResponse() 

342 response.status_code = 201 

343 return response