Coverage for xplanung_light/views/beteiligungtoebnotification.py: 100%

156 statements  

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

1from django.views.generic import ListView, CreateView, DetailView 

2from xplanung_light.models import BPlan, BPlanBeteiligung, AdministrativeOrganization 

3from xplanung_light.models import FPlanBeteiligung, FPlan, ContactOrganization 

4from xplanung_light.models import ConsentOption, AdminOrgaUser, ToebUnit 

5from xplanung_light.models import BPlanBeteiligungToebNotification, FPlanBeteiligungToebNotification 

6from formset.views import FormViewMixin, FormCollectionView, EditCollectionView 

7from django_tables2 import SingleTableView 

8from xplanung_light.tables import BPlanBeteiligungToebNotificationTable, FPlanBeteiligungToebNotificationTable 

9from django.urls import reverse_lazy, reverse 

10from django.contrib.messages.views import SuccessMessageMixin 

11from xplanung_light.forms import BPlanBeteiligungCollection, FPlanBeteiligungCollection, BPlanBeteiligungToebNotificationCreateForm, FPlanBeteiligungToebNotificationCreateForm 

12from django.shortcuts import get_object_or_404 

13from django.core.exceptions import ValidationError 

14from django.http import JsonResponse 

15from django.db.models import Count 

16import json 

17from django.core.exceptions import PermissionDenied 

18from django.db.models import Subquery, OuterRef, Q 

19from django.http import HttpResponse 

20from django.shortcuts import redirect 

21from django.core.mail import send_mail, EmailMessage 

22from django.utils.timezone import datetime 

23from django.conf import settings 

24from django.template.loader import render_to_string 

25from django.core.mail import EmailMultiAlternatives 

26from django.db import transaction 

27from xplanung_light.views.user import ExtentUserOrgaInfo 

28from django.contrib.auth.mixins import UserPassesTestMixin 

29from django.utils import timezone 

30from django.contrib.auth.mixins import LoginRequiredMixin 

31from xplanung_light.views.mixins import GemeindeAdminRequiredMixin 

32 

33class BeteiligungToebNotificationListView(ExtentUserOrgaInfo, SingleTableView): 

34 """ 

35 ListView zur Anzeige der BeteiligungToebNotification-Records. Hier Die Klasse entscheidet je nach URL,  

36 um welchen Plantyp es sich handelt. 

37 """ 

38 # Default Werte für Initialiisierung - werden durch dispatch Funktion überschrieben 

39 model = BPlanBeteiligungToebNotification 

40 parent_model = BPlanBeteiligung 

41 reference_model = BPlan 

42 table_class = BPlanBeteiligungToebNotificationTable 

43 reference_model_name_lower = 'bplan' 

44 

45 def dispatch(self, request, *args, **kwargs): 

46 # Hier sind die Parameter aus der re_path verfügbar 

47 self.plantyp = kwargs.get('plantyp') 

48 if self.kwargs.get('plantyp') == 'bplan': 

49 self.model = BPlanBeteiligungToebNotification 

50 self.parent_model = BPlanBeteiligung 

51 self.reference_model = BPlan 

52 if self.kwargs.get('plantyp') == 'fplan': 

53 self.model = FPlanBeteiligungToebNotification 

54 self.parent_model = FPlanBeteiligung 

55 self.table_class = FPlanBeteiligungToebNotificationTable 

56 self.reference_model = FPlan 

57 self.planid = self.kwargs.get('planid') 

58 self.template_name = 'xplanung_light/beteiligungtoebnotification_list.html' 

59 self.beteiligungid = kwargs.get('beteiligungid') 

60 return super().dispatch(request, *args, **kwargs) 

61 

62 def get_queryset(self, **kwargs): 

63 """ 

64 Docstring for get_queryset 

65  

66 :param self: Description 

67 :param kwargs: Description 

68 """ 

69 qs = super().get_queryset().annotate( 

70 last_changed=Subquery( 

71 self.model.history.filter(id=OuterRef("pk")).order_by('-history_date').values('history_date')[:1] 

72 ) 

73 ) 

74 plan = self.reference_model.objects.get(pk=self.kwargs['planid']) 

75 # check ob Nutzer admin einer der Gemeinden des BPlans ist 

76 if self.request.user.is_superuser == False: 

77 for gemeinde in plan.gemeinde.all(): 

78 for user in gemeinde.admin_orga_users.all(): 

79 if user.user == self.request.user and user.is_admin: 

80 # Zugriff wird erteilt 

81 if self.plantyp == 'bplan': 

82 return qs.filter(bplanbeteiligung_id=self.kwargs['beteiligungid']).order_by('-last_changed') 

83 if self.plantyp == 'fplan': 

84 return qs.filter(fplanbeteiligung_id=self.kwargs['beteiligungid']).order_by('-last_changed') 

85 raise PermissionDenied("Nutzer hat keine Berechtigungen auf die angeforderten Objekte!") 

86 else: 

87 if self.plantyp == 'bplan': 

88 return qs.filter(bplanbeteiligung_id=self.kwargs['beteiligungid']).order_by('-last_changed') 

89 if self.plantyp == 'fplan': 

90 return qs.filter(fplanbeteiligung_id=self.kwargs['beteiligungid']).order_by('-last_changed') 

91 

92 

93 def get_context_data(self, **kwargs): 

94 """ 

95 Docstring for get_context_data 

96  

97 :param self: Description 

98 :param kwargs: Description 

99 """ 

100 #planid = self.kwargs['planid'] 

101 #beteiligungid = self.kwargs['beteiligungid'] 

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

103 context["plan"] = self.reference_model.objects.get(pk=self.planid) 

104 context["plantyp"] = self.plantyp 

105 context["beteiligung"] = self.parent_model.objects.get(pk=self.beteiligungid) 

106 if context["beteiligung"].bekanntmachung_datum <= timezone.now().date() and context["beteiligung"].end_datum >= timezone.now().date(): 

107 context["status"] = 1 

108 else: 

109 context["status"] = 0 

110 return context 

111 

112 

113class BeteiligungToebNotificationCreateView(LoginRequiredMixin, GemeindeAdminRequiredMixin, ExtentUserOrgaInfo, CreateView): 

114 """ 

115 View für Abbildung des kombinierten Fomulars über django-formsets EditCollectionView - das Formular ist nur für die Öffentlichkeit gedacht 

116 https://django-formset.fly.dev/model-collections/ 

117 

118 """ 

119 # Initialisierung der Attribute - werden in dispatch Funktion überschrieben! 

120 plantyp = None 

121 model = BPlanBeteiligungToebNotification 

122 form_class = BPlanBeteiligungToebNotificationCreateForm 

123 planmodel = None 

124 beteiligungid = None 

125 parent_model = BPlanBeteiligung 

126 template_name = 'xplanung_light/beteiligungtoebnotification_form.html' 

127 #success_url = reverse_lazy("beteiligungnotification-list", { plantyp='bplan', })  

128 

129 def dispatch(self, request, *args, **kwargs): 

130 # Hier sind die Parameter aus der re_path verfügbar: 

131 # WICHTIG: dieser Block liest nur URL-Kwargs und setzt Attribute - 

132 # er macht KEINEN DB-Zugriff und ruft KEINE Berechtigungsprüfung 

133 # auf. Genau das ist Voraussetzung dafür, dass er gefahrlos vor 

134 # super().dispatch() laufen darf: LoginRequiredMixin greift erst in 

135 # super().dispatch(), und GemeindeAdminRequiredMixin.check_gemeinde_admin() 

136 # wird bewusst NICHT hier, sondern erst in get_form_kwargs() aufgerufen - 

137 # also garantiert nach dem Login-Check. (Siehe die Anmerkungen zu 

138 # BeteiligungBeitragAnhangRedactedCreateView.dispatch() für ein 

139 # Beispiel, wie diese Reihenfolge schiefgehen kann, wenn eine 

140 # Berechtigungsprüfung direkt in dispatch() vor super().dispatch() 

141 # steht.) 

142 self.plantyp = kwargs.get('plantyp') 

143 if self.kwargs.get('plantyp') == 'bplan': 

144 self.model = BPlanBeteiligungToebNotification 

145 self.planmodel = BPlan 

146 self.parent_model = BPlanBeteiligung 

147 #self.template_name = 'xplanung_light/beteiligungtoebnotification_form.html' 

148 if self.kwargs.get('plantyp') == 'fplan': 

149 self.model = FPlanBeteiligungToebNotification 

150 self.planmodel = FPlan 

151 self.parent_model = FPlanBeteiligung 

152 self.form_class = FPlanBeteiligungToebNotificationCreateForm 

153 #self.template_name = 'xplanung_light/beteiligungtoebnotification_form.html' 

154 #self.form_class = BeteiligungToebNotificationCreateForm 

155 self.planid = kwargs.get('planid') 

156 self.beteiligungid = kwargs.get('beteiligungid') 

157 return super().dispatch(request, *args, **kwargs) 

158 

159 #def get_queryset(self): 

160 # qs = super().get_queryset() 

161 # Check Zeitrahmen des Verfahrens 

162 # print(str(beteiligung.bekanntmachung_datum)) 

163 # beteiligung = self.parent_model.objects.get(pk=self.beteiligungid) 

164 # if not (beteiligung.bekanntmachung_datum <= timezone.now().date() and beteiligung.end_datum >= timezone.now().date()): 

165 # raise PermissionDenied("Benachrichtigungen außerhalb des Zeitrahmens sind nicht möglich!") 

166 # return qs 

167 

168 def get_form_kwargs(self): 

169 # get_form_kwargs() wird von Django sowohl für GET (Formular 

170 # anzeigen) als auch POST (Formular verarbeiten) aufgerufen - die 

171 # Berechtigungsprüfung hier deckt also beide Fälle ab, nicht nur 

172 # den POST. 

173 kwargs = super().get_form_kwargs() 

174 beteiligungmodel = ( 

175 BPlanBeteiligung if self.plantyp == 'bplan' else FPlanBeteiligung 

176 ) 

177 kwargs['beteiligung'] = get_object_or_404( 

178 beteiligungmodel, 

179 pk=self.beteiligungid 

180 ) 

181 plan = get_object_or_404(self.planmodel, pk=self.planid) 

182 self.check_gemeinde_admin(plan) 

183 if not (kwargs['beteiligung'].bekanntmachung_datum <= timezone.now().date() and kwargs['beteiligung'].end_datum >= timezone.now().date()): 

184 raise PermissionDenied("Benachrichtigungen außerhalb des Zeitrahmens sind nicht möglich!") 

185 return kwargs 

186 

187 def form_valid(self, form): 

188 if self.plantyp == 'bplan': 

189 form.instance.bplanbeteiligung_id = self.beteiligungid 

190 if self.plantyp == 'fplan': 

191 form.instance.fplanbeteiligung_id = self.beteiligungid 

192 beteiligungmodel = ( 

193 BPlanBeteiligung if self.plantyp == 'bplan' else FPlanBeteiligung 

194 ) 

195 beteiligung = get_object_or_404( 

196 beteiligungmodel, 

197 pk=self.beteiligungid 

198 ) 

199 form.instance.start = timezone.now() 

200 # send mail 

201 if self.plantyp == 'bplan': 

202 plan = BPlan.objects.get(id=self.planid) 

203 if self.plantyp == 'fplan': 

204 plan = FPlan.objects.get(id=self.planid) 

205 # Auslesen der Kontaktstellen Informationen 

206 contacts = ContactOrganization.objects.filter(gemeinde__id__in=plan.gemeinde.values_list('id', flat=True)).distinct() 

207 responsible_orgas = plan.gemeinde 

208 cleaned_data = form.cleaned_data 

209 # Identifikation der EMail-Adressen der Sachbearbeiter 

210 toebs = cleaned_data.get("selected_toebs") 

211 if cleaned_data.get("message"): 

212 comment = cleaned_data.get("message") 

213 else: 

214 comment = None 

215 # Zusätzliche Speicherung in json - ggf. später als Protokoll 

216 #  

217 result = [] 

218 for toeb in toebs: 

219 result_toeb = {} 

220 result_toeb['name'] = str(toeb) 

221 result_toeb['email'] = [] 

222 # Eine EMail pro TOEB - es kann sein, dass ein User mehrere Mails bekommt, wenn er für mehrere TOEBs die Rolle Reporter hat! 

223 if settings.XPLANUNG_LIGHT_CONFIG['mapfile_force_online_resource_https']: 

224 direct_url = self.request.build_absolute_uri(reverse("beteiligungbeitrag-toeb-create", args=[self.plantyp, self.planid, beteiligung.id, toeb.id])).replace('http://', 'https://') 

225 else: 

226 direct_url = self.request.build_absolute_uri(reverse("beteiligungbeitrag-toeb-create", args=[self.plantyp, self.planid, beteiligung.id, toeb.id])) 

227 if settings.XPLANUNG_LIGHT_CONFIG['mapfile_force_online_resource_https']: 

228 list_url = self.request.build_absolute_uri(reverse("toebbeteiligungen-list")).replace('http://', 'https://') 

229 else: 

230 list_url = self.request.build_absolute_uri(reverse("toebbeteiligungen-list")) 

231 direct_link = f"{direct_url}" 

232 list_link = f"{list_url}" 

233 subject = str("Benachrichtigung zur " + beteiligung.get_typ_display() + " vom " + datetime.today().strftime('%Y-%m-%d') + " - Frist: " + str(beteiligung.end_datum) ) 

234 html_content = render_to_string("xplanung_light/email/toeb_benachrichtigung.html", context={"comment": comment, "plan": plan, "beteiligung": beteiligung, "direct_link": direct_link, "list_link": list_link, "contacts": contacts, "orgas": responsible_orgas, "toeb": toeb, "metadata_contact": settings.XPLANUNG_LIGHT_CONFIG['metadata_contact'],},) 

235 text_content = render_to_string("xplanung_light/email/toeb_benachrichtigung.txt", context={"comment": comment, "plan": plan, "beteiligung": beteiligung, "direct_link": direct_link, "list_link": list_link, "contacts": contacts, "orgas": responsible_orgas, "toeb": toeb, "metadata_contact": settings.XPLANUNG_LIGHT_CONFIG['metadata_contact'],},) 

236 for editor in toeb.editors.all(): 

237 if editor.user.email: 

238 result_toeb['email'].append(editor.user.email) 

239 email = EmailMultiAlternatives( 

240 subject=subject, 

241 body=text_content, 

242 from_email=settings.XPLANUNG_LIGHT_CONFIG['metadata_contact']['email'], 

243 to=[str(editor.user.email),], 

244 #bcc=[str(farmshop.contact_email),], 

245 reply_to=[settings.XPLANUNG_LIGHT_CONFIG['metadata_contact']['email'],] 

246 ) 

247 email.attach_alternative(html_content, "text/html") 

248 email.send(fail_silently=True) 

249 result.append(result_toeb) 

250 result_json = json.dumps(result) 

251 #print(result_json) 

252 form.instance.protocol = result 

253 form.instance.end = timezone.now() 

254 # ... 

255 return super().form_valid(form) 

256 

257 def get_success_url(self): 

258 """ 

259 Wenn das Versenden erfolgreich war, wird auf die Liste der Notifications 

260 weitergeleitet. 

261 """ 

262 return reverse_lazy("beteiligungnotification-list", kwargs={'plantyp': self.plantyp, 'planid': self.planid, 'beteiligungid': self.beteiligungid})