from django.shortcuts import render, redirect from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.views.generic import CreateView, ListView, UpdateView, DetailView, DeleteView, View from .models import Standards, StandardComments, StandardCommentRate from django.contrib import messages from django.http import HttpResponse, JsonResponse from .forms import StandardAddStandard, StandardAddStandardEditor, StandardUpdateStandard, StandardUpdateStandardEditor from django.contrib.auth.decorators import login_required from tasks.models import Tasks from areas.models import Areas from datetime import datetime from users.models import AgencyGroup, AgencyNetwork from cloud.models import DataFile, DataDir from django.contrib.auth.decorators import login_required import re from django.template import defaultfilters from organizer.models import QuickLinks, AGContacts, AGPassword import channels.layers from asgiref.sync import async_to_sync from django.template.loader import render_to_string from notificsys.models import UserNotification from django.core.mail import send_mail # ALLE STANDARDS EINER AGENTUR class StandardsManagement(LoginRequiredMixin, ListView): model = Standards # Adding active_link # Loading only user same agency # Change context and return for template-data def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # # Get all Users of the Same Agency as logged user areas = Areas.objects.filter(agency__pk=self.request.user.profile.agency.pk).order_by("areaorder") standards_of_user = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, created_standard_by=self.request.user.pk) #standards_of_agency = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, public=True) unpubstandards_of_user = Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, public=False) #tasks = Tasks.objects.filter(agency__pk=self.request.user.profile.agency.pk) standardcontent = [] for a in areas: standardcontent.append({"area" : a, "tasks" : []}) tasks_in_area = Tasks.objects.filter(agency__pk=self.request.user.profile.agency.pk, area__pk=a.pk).order_by("name") for t in tasks_in_area: standardcontent[len(standardcontent)-1]['tasks'].append({"task" : t, "standards" : Standards.objects.filter(agency__pk=self.request.user.profile.agency.pk, area__pk=a.pk, task = t.pk, area = a.pk, public=True).order_by("-created_standard_date")}) #context.update({'active_link' : 'standards', 'tasks': tasks, 'unpubstandards_of_user' : unpubstandards_of_user, 'standards_of_agency' : standards_of_agency, 'areas' : areas, 'standards_of_user' : standards_of_user, 'standardcontent' : standardcontent}) #agencynetworks = AgencyNetwork.objects.filter(creator_agency=self.request.user.profile.agency) | AgencyNetwork.objects.filter(adminagencys__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[self.request.user.profile.agency.pk]) #agencynetworks = AgencyNetwork.objects.filter(adminagencys__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[self.request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[self.request.user.profile.agency.pk]) agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if self.request.user.profile.agency in a.adminagencys.all() or self.request.user.profile.agency in a.members.all() or self.request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) allagencynetworkstandards = [] for agn in agencynetworks: for agn_s in agn.standards.all(): allagencynetworkstandards.append(agn_s) allagencynetworkstandards.sort(key=lambda x: x.agencynetworkcounter, reverse=True) # Beliebte Standards famestandards = [] famecounter = 0 for s in allagencynetworkstandards: if famecounter < 10 and s not in famestandards: famestandards.append(s) famecounter += 1 context.update({'active_link' : 'standards', 'unpubstandards_of_user' : unpubstandards_of_user, 'areas' : areas, 'standards_of_user' : standards_of_user, 'standardcontent' : standardcontent, "agencynetworks" : agencynetworks, "allagencynetworkstandards" : allagencynetworkstandards, 'famestandards' : famestandards}) return context @login_required def checkUserDirRights(request, startdir, userid): canview = True user = User.objects.get(pk=userid) usergroups=list(user.groups.all()) grouptomach = [] singleObj = DataDir.objects.get(pk=startdir.pk) # AGENCYCHECK if(singleObj.agency.pk == user.profile.agency.pk): # Get dirs to check while( singleObj.is_root != True and canview == True): for g in singleObj.visibleby.all(): grouptomach.append(g.group) if(len(grouptomach) == 0): canview = True else: if(len(set(usergroups).intersection(grouptomach)) > 0): canview = True else: canview = False grouptomach = [] singleObj = DataDir.objects.get(pk=singleObj.parent.pk) else: canview = False return canview @login_required def StandardAdd(request, id=False): # NEW STANDARD if(id == False): if request.method == 'POST': normalForm = StandardAddStandard(request.POST, instance=request.user) editorForm = StandardAddStandardEditor(request.POST, instance=request.user) if editorForm.is_valid() and normalForm.is_valid(): normalForm.agency = request.user.profile.agency normalForm.created_standard_by = request.user normalForm.created_standard_date = datetime.now() normalForm.published_by = request.user normalForm.last_modifed_by = request.user normalForm.save() editorForm.save() new_standard = Standards() new_standard.agency = request.user.profile.agency new_standard.created_standard_by = request.user new_standard.published_by = request.user new_standard.last_modified_by = request.user new_standard.created_standard_date = datetime.now() new_standard.last_modified_on = datetime.now() new_standard.task = normalForm.cleaned_data['task'] new_standard.area = normalForm.cleaned_data['area'] new_standard.name = normalForm.cleaned_data['name'] new_standard.content = editorForm.cleaned_data['content'] new_standard.public = normalForm.cleaned_data['public'] new_standard.freefield_content = normalForm.cleaned_data['freefield_content'] new_standard.freefield_title = normalForm.cleaned_data['freefield_title'] new_standard.save() #new_standard.representative.set(normalForm.cleaned_data['representative']) #new_standard.executor.set(normalForm.cleaned_data['executor']) #new_standard.authority.set(normalForm.cleaned_data['authority']) # USERS # REPRESENTATIV verant = normalForm.cleaned_data['us_verant'].split(",") for v in verant: if(v.isdigit()): new_standard.authority.add(User.objects.get(pk=v)) # EXECUTORS ex = normalForm.cleaned_data['us_ex'].split(",") for v in ex: if(v.isdigit()): new_standard.executor.add(User.objects.get(pk=v)) # AUTHORITY ver = normalForm.cleaned_data['us_ver'].split(",") for v in ver: if(v.isdigit()): new_standard.representative.add(User.objects.get(pk=v)) # GROUPS BEI PERSONEN # verant_group = normalForm.cleaned_data['group_verant'].split(",") for v in verant_group: if(v.isdigit()): new_standard.authority_group.add(AgencyGroup.objects.get(pk=v)) # EXECUTORS ex_group = normalForm.cleaned_data['group_ex'].split(",") for v in ex_group: if(v.isdigit()): new_standard.executor_group.add(AgencyGroup.objects.get(pk=v)) # AUTHORITY ver_group = normalForm.cleaned_data['group_ver'].split(",") for v in ver_group: if(v.isdigit()): new_standard.representative_group.add(AgencyGroup.objects.get(pk=v)) # ADD GROUPS groups = normalForm.cleaned_data['checked_groups'].split(",") for g in groups: if(g.isdigit()): new_standard.visibleby.add(AgencyGroup.objects.get(pk=g)) # ADD STANDARDS standards = normalForm.cleaned_data['added_standards'].split(",") for s in standards: if(s.isdigit()): new_standard.linked_standards.add(Standards.objects.get(pk=s)) # ADD FILES files = normalForm.cleaned_data['added_files'].split(",") for f in files: if(f.isdigit()): new_standard.addedfiles.add(DataFile.objects.get(pk=f)) # ADD QUICKLINKS quicklinks = normalForm.cleaned_data['added_quicklinks'].split(",") for f in quicklinks: if(f.isdigit()): new_standard.addedquicklinks.add(QuickLinks.objects.get(pk=f)) # ADD PASSWORDS addedpasswords = normalForm.cleaned_data['added_passwords'].split(",") for f in addedpasswords: if(f.isdigit()): new_standard.addedpasswords.add(AGPassword.objects.get(pk=f)) # ADD CONTACTS contacts = normalForm.cleaned_data['added_contacts'].split(",") for f in contacts: if(f.isdigit()): new_standard.addedcontacts.add(AGContacts.objects.get(pk=f)) tempstandardname = normalForm.cleaned_data['name'] if(new_standard.public and request.user.has_perm('users.standardmanager')): messages.success(request, f'Standard {tempstandardname} hinzugefügt und veröffentlicht.') else: new_standard.public = False new_standard.save() messages.success(request, f'Standard {tempstandardname} hinzugefügt! Dieser muss noch veröffentlicht werden.') return redirect('standards') else: normalForm = StandardAddStandard(instance=request.user) editorForm = StandardAddStandardEditor(instance=request.user) possibleFilesByVisible = [] allfiles = DataFile.objects.filter(agency=request.user.profile.agency) for f in allfiles: actParent = DataDir.objects.get(pk=f.parent.pk) if actParent.is_root: possibleFilesByVisible.append(f) else: if(checkUserDirRights(request, actParent, request.user.pk)): possibleFilesByVisible.append(f) context = { 'normalForm' : normalForm, 'editorForm' : editorForm, 'active_link' : 'standards', 'agencygroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), 'usersofagency' : User.objects.filter(profile__agency=request.user.profile.agency), 'files' : possibleFilesByVisible, 'parentid' : list(DataDir.objects.filter(agency=request.user.profile.agency, is_root=True))[0].pk, 'standards' : Standards.objects.filter(agency=request.user.profile.agency, public=True), 'quicklinks' : QuickLinks.objects.filter(agency=request.user.profile.agency), 'contacts' : AGContacts.objects.filter(agency=request.user.profile.agency), 'passwords' : AGPassword.objects.filter(agency=request.user.profile.agency), 'aggroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), } return render(request, 'standards/standards_add.html', context) # UPDATE A STANDARD else: standard = Standards.objects.get(pk=id, agency=request.user.profile.agency) # SAVE UPDATED STANDARD if request.method == 'POST': normalForm = StandardUpdateStandard(request.POST, instance=standard) editorForm = StandardUpdateStandardEditor(request.POST, instance=standard) if editorForm.is_valid() and normalForm.is_valid(): standard.last_modified_by = request.user standard.last_modified_on = datetime.now() standard.task = normalForm.cleaned_data['task'] standard.area = normalForm.cleaned_data['area'] standard.name = normalForm.cleaned_data['name'] standard.public = normalForm.cleaned_data['public'] standard.content = editorForm.cleaned_data['content'] standard.freefield_content = normalForm.cleaned_data['freefield_content'] standard.freefield_title = normalForm.cleaned_data['freefield_title'] # Clear Users, will set again next step standard.authority.clear() standard.executor.clear() standard.representative.clear() # GROUPS standard.authority_group.clear() standard.executor_group.clear() standard.representative_group.clear() standard.visibleby.clear() standard.linked_standards.clear() standard.addedfiles.clear() standard.addedquicklinks.clear() standard.addedpasswords.clear() standard.addedcontacts.clear() # ADD NEW INFOS # REPRESENTATIV verant = normalForm.cleaned_data['us_verant'].split(",") for v in verant: if(v.isdigit()): standard.authority.add(User.objects.get(pk=v)) # EXECUTORS ex = normalForm.cleaned_data['us_ex'].split(",") for v in ex: if(v.isdigit()): standard.executor.add(User.objects.get(pk=v)) # AUTHORITY ver = normalForm.cleaned_data['us_ver'].split(",") for v in ver: if(v.isdigit()): standard.representative.add(User.objects.get(pk=v)) verant_group = normalForm.cleaned_data['group_verant'].split(",") for v in verant_group: if(v.isdigit()): standard.authority_group.add(AgencyGroup.objects.get(pk=v)) # EXECUTORS ex_group = normalForm.cleaned_data['group_ex'].split(",") for v in ex_group: if(v.isdigit()): standard.executor_group.add(AgencyGroup.objects.get(pk=v)) # AUTHORITY ver_group = normalForm.cleaned_data['group_ver'].split(",") for v in ver_group: if(v.isdigit()): standard.representative_group.add(AgencyGroup.objects.get(pk=v)) # ADD GROUPS groups = normalForm.cleaned_data['checked_groups'].split(",") for g in groups: if(g.isdigit()): standard.visibleby.add(AgencyGroup.objects.get(pk=g)) # ADD STANDARDS standards = normalForm.cleaned_data['added_standards'].split(",") for s in standards: if(s.isdigit()): standard.linked_standards.add(Standards.objects.get(pk=s)) # ADD FILES files = normalForm.cleaned_data['added_files'].split(",") for f in files: if(f.isdigit()): standard.addedfiles.add(DataFile.objects.get(pk=f)) # ADD QUICKLINKS quicklinks = normalForm.cleaned_data['added_quicklinks'].split(",") for f in quicklinks: if(f.isdigit()): standard.addedquicklinks.add(QuickLinks.objects.get(pk=f)) # ADD PASSWORDS addedpasswords = normalForm.cleaned_data['added_passwords'].split(",") for f in addedpasswords: if(f.isdigit()): standard.addedpasswords.add(AGPassword.objects.get(pk=f)) # ADD CONTACTS contacts = normalForm.cleaned_data['added_contacts'].split(",") for f in contacts: if(f.isdigit()): standard.addedcontacts.add(AGContacts.objects.get(pk=f)) # ADD TO NETWORKS networks = normalForm.cleaned_data['checked_networks'].split(",") ''' Alle Agenturverbunde laden, in denen die Agentur drin ist. ''' agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if request.user.profile.agency in a.adminagencys.all() or request.user.profile.agency in a.members.all() or request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) agencynetworks_standard_in = [] # Agenturverbünde, in denen der Standard drin sein soll for f in networks: if(f.isdigit()): tempnetwork = AgencyNetwork.objects.get(pk=f) #tempnetwork.standards.add(standard) agencynetworks_standard_in.append(tempnetwork) #print(agencynetworks_standard_in) # Wenn Standard im gewünschten Verbund, dann rein, ansonsten raus for a in agencynetworks: if a in agencynetworks_standard_in and standard not in a.standards.all(): a.standards.add(standard) elif a not in agencynetworks_standard_in: a.standards.remove(standard) ''' Info an die Agenturen über einen neuen Standard ''' agency_send = [] for agencynetwork_single in agencynetworks_standard_in: for agn_admin in agencynetwork_single.adminagencys.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) for agn_admin in agencynetwork_single.members.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) for agn_admin in agencynetwork_single.sharemembers.all(): if(agn_admin not in agency_send): agency_send.append(agn_admin) if agn_admin != request.user.profile.agency: users_of_other_ag = User.objects.filter(profile__agency=agn_admin) for u in users_of_other_ag: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_created_mail: notificationtext = "im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_created_push: newnotification = UserNotification(touser=u, notificationtext="im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name, notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Im Agenturverbund " + agencynetwork_single.name + " wurde ein neuer Standard geteilt: " + standard.name}) # Clear sended Agencys for multiple Networks agency_send = [] if request.user.has_perm('users.standardmanager'): messages.success(request, f'Standard {standard.name} aktualisiert!') else: if standard.public: standard.public = False messages.warning(request, f'Standard {standard.name} aktualisiert und ist nicht mehr öffentlich, damit Änderungen geprüft werden können.') else: messages.success(request, f'Standard {standard.name} aktualisiert!') standard.save() return redirect('/standards') # SHOW EXISTING STANDARD else: normalForm = StandardUpdateStandard(instance=standard) editorForm = StandardUpdateStandardEditor(instance=standard) # GET ALL DATAS FROM STANDARD # FILES possibleFilesByVisible = [] allfiles = DataFile.objects.filter(agency=request.user.profile.agency) # Get all files by view for f in allfiles: actParent = DataDir.objects.get(pk=f.parent.pk) if actParent.is_root: possibleFilesByVisible.append(f) else: if(checkUserDirRights(request, actParent, request.user.pk)): possibleFilesByVisible.append(f) # Remove files which are in standard for f in possibleFilesByVisible: if f in standard.addedfiles.all(): possibleFilesByVisible.remove(f) # STANDARDS possible_standards = [] allstandards = Standards.objects.filter(agency=request.user.profile.agency, public=True) for s in allstandards: if s not in standard.linked_standards.all(): possible_standards.append(s) # USERS VER AUTH EX possible_verant = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_verant_final = [] for pv in possible_verant: if pv not in standard.authority.all(): possible_verant_final.append(pv) possible_ex = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_ex_final = [] for pv in possible_ex: if pv not in standard.executor.all(): possible_ex_final.append(pv) possible_ver = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk) possible_ver_final = [] for pv in possible_ver: if pv not in standard.representative.all(): possible_ver_final.append(pv) # GROUPS VER AUTH EX #possible_verant_group_final #possible_ex_group_final #possible_ver_group_final possible_verant_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_verant_group_final = [] for g in possible_verant_group: if g not in standard.authority_group.all(): possible_verant_group_final.append(g) possible_ex_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_ex_group_final = [] for g in possible_ex_group: if g not in standard.executor_group.all(): possible_ex_group_final.append(g) possible_ver_group = AgencyGroup.objects.filter(agency=request.user.profile.agency) possible_ver_group_final = [] for g in possible_ver_group: if g not in standard.representative_group.all(): possible_ver_group_final.append(g) # QUICKLINKS possible_quicklinks = [] quicklinks = QuickLinks.objects.filter(agency=request.user.profile.agency) for q in quicklinks: if q not in standard.addedquicklinks.all(): possible_quicklinks.append(q) # CONTACTS possible_contacts = [] contacts = AGContacts.objects.filter(agency=request.user.profile.agency) for q in contacts: if q not in standard.addedcontacts.all(): possible_contacts.append(q) # PASSWORDS possible_passwords = [] contacts = AGPassword.objects.filter(agency=request.user.profile.agency) for q in contacts: if q not in standard.addedpasswords.all(): possible_passwords.append(q) # AGENCYNETWORKS agencynetworks_all = AgencyNetwork.objects.all() agencynetworks = [] for a in agencynetworks_all: if request.user.profile.agency in a.adminagencys.all() or request.user.profile.agency in a.members.all() or request.user.profile.agency in a.sharemembers.all(): agencynetworks.append(a) # GROUPS # Nicht nötig, da alles über agencygroups und direkt im Standard gemacht wird context = { 'normalForm' : normalForm, 'editorForm' : editorForm, 'standard' : standard, 'files' : possibleFilesByVisible, 'standard_possible' : possible_standards, 'poss_verant' : possible_verant_final, 'poss_ex' : possible_ex_final, 'poss_ver' : possible_ver_final, 'possgroup_verant' : possible_verant_group_final, 'possgroup_ex' : possible_ex_group_final, 'possgroup_ver' : possible_ver_group_final, 'possible_quicklinks' : possible_quicklinks, 'possible_passwords' : possible_passwords, 'possible_contacts' : possible_contacts, 'agencynetworks' : agencynetworks, 'agencygroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency), 'parentid' : list(DataDir.objects.filter(agency=request.user.profile.agency, is_root=True))[0].pk, 'active_link' : 'standards', 'update' : True, 'aggroups' : AgencyGroup.objects.filter(agency=request.user.profile.agency) } return render(request, 'standards/standards_add.html', context) ''' Gibt die Daten der Agenturgruppen zurück, welche in diesem Standard sind. ''' @login_required def LoadAGGroupMembers(request): if request.method == "GET": aggroupid = request.GET['aggroup'] try: aggroup = AgencyGroup.objects.get(pk=aggroupid) except: return JsonResponse({"status" : "err", "message" : "Fehler! Diese Gruppe gibt es nicht."}) members_string = "" if request.user.profile.agency == aggroup.agency: members = User.objects.filter(groups__name=aggroup.group.name) counter = 0 for member in members: members_string += member.get_full_name() counter += 1 if counter+1 <= len(members): members_string += ", " if counter == 0: members_string = "Gruppe hat keine Mitglieder." else: return JsonResponse({"status" : "err", "message" : "Sie haben auf diese Gruppe keinen Zugriff!"}) return JsonResponse({"status" : "ok", "aggroupname" : aggroup.agencygroupname, "members" : members_string}) else: return JsonResponse({"status" : "err", "message" : "Allgemeiner Fehler."}) # Funktion zum versenden einer Mail inkl. TEmplate def sendMailNoti(notificationtext, user_touched, linktarget=""): username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext, 'linktarget' : linktarget}) send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'noreply@digitale-agentur.com', [user_touched.email], html_message=msg_html, fail_silently=True ) @login_required def load_tasks(request): areaid = request.GET.get('areaid') tasks = Tasks.objects.filter(area__id=areaid, agency=request.user.profile.agency).order_by('name') return render(request, 'standards/standards_tasklist.html', {'tasks': tasks}) class StandardDeleteView(LoginRequiredMixin, DeleteView): model = Standards success_url = '/standards' template_name = 'standards/standard_confirm_delete.html' def delete(self, request, *args, **kwargs): standard = Standards.objects.get(pk=kwargs['pk'], agency=request.user.profile.agency) response = super(StandardDeleteView, self).delete(request, *args, **kwargs) names = standard.name messages.success(request, f'Standard ' +names+ ' wurde gelöscht!') return response def get_context_data(self, **kwargs): context = super(StandardDeleteView, self).get_context_data(**kwargs) context['active_link'] = 'standards' return context @login_required def StandardChangePublic(request, pk): standard = Standards.objects.get(pk=pk) if standard.public: standard.public = False messages.warning(request, f'Standard {standard.name} ist nicht mehr öffentlich!') else: standard.public = True messages.success(request, f'Standard {standard.name} wurde veröffentlicht und ist innerhalb der Agentur sichtbar!') standard.save() return redirect('standards') @login_required def StandardSingle(request, pk): # CHECK IF USER HAS RIGHTS TO SEE THIS DIR groupsofstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: standard = Standards.objects.get(pk=pk) context = { 'active_link':'standards', 'standard' : standard } return render(request, 'standards/standards_single.html', context) else: context = { 'active_link':'standards' } return render(request, 'standards/standards_noentrie.html', context) @login_required def CopyStandard(request, pk): #SANDARD COPY sc = Standards.objects.get(pk=pk) sc.agencynetworkcounter = sc.agencynetworkcounter+1 sc.save() area = list(Areas.objects.filter(agency=request.user.profile.agency))[0] task = list(Tasks.objects.filter(agency=request.user.profile.agency))[0] new_standard = Standards() new_standard.agency = request.user.profile.agency new_standard.created_standard_by = request.user new_standard.published_by = request.user new_standard.last_modified_by = request.user new_standard.created_standard_date = datetime.now() new_standard.last_modified_on = datetime.now() new_standard.task = None new_standard.area = None new_standard.name = sc.name new_standard.content = sc.content new_standard.public = False new_standard.freefield_content = sc.freefield_content new_standard.freefield_title = sc.freefield_title new_standard.parent_standard = sc new_standard.shared_on = datetime.now() new_standard.save() datadir_parentid = list(DataDir.objects.filter(is_defaultstandard=True, agency__pk=request.user.profile.agency.pk))[0] for f in sc.addedfiles.all(): tempdatafile = DataFile(file=f.file, name=f.name, owner=request.user, parent=datadir_parentid, agency=request.user.profile.agency) tempdatafile.save() new_standard.addedfiles.add(tempdatafile) # TASK: Hier das kopieren der Dateien auf dem Server noch einfügen # Sende Info, dass ein Standard übernommen wurde, an die Erstelleragentur usersofagency = User.objects.filter(profile__agency=sc.agency) for u in usersofagency: if u.has_perm('users.standardmanager') and u.has_perm('users.agencynetwork'): if u.usernotifications.agn_standard_copied_mail: notificationtext = "der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen." sendMailNoti(notificationtext, u) if u.usernotifications.agn_standard_copied_push: newnotification = UserNotification(touser=u, notificationtext="der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen.", notificationtype="") newnotification.save() channel_layer = channels.layers.get_channel_layer() async_to_sync(channel_layer.group_send)("user_" + str(u.pk), {'type' : 'pushhandler', 'pushtext' : "pushnotification__Agenturverbund | Der Standard " + sc.name + " wurde von der Agentur " + request.user.profile.agency.name + " übernommen."}) return redirect('standard-add', new_standard.pk) @login_required def StandardArea(request, pk): standards = Standards.objects.filter(agency__pk=request.user.profile.agency.pk).exclude(area=None).exclude(task=None).filter(area__pk=pk) area = Areas.objects.get(pk=pk, agency=request.user.profile.agency) context = { 'active_link':'standards', 'standards_of_agency_area' : standards, 'areaid' : pk, 'areaname' : area.name } return render(request, 'standards/standard_area.html', context) @login_required def StandardTask(request, pk): standards = Standards.objects.filter(agency__pk=request.user.profile.agency.pk).exclude(area=None).exclude(task=None).filter(task__pk=pk) task = Tasks.objects.get(pk=pk, agency=request.user.profile.agency) area = Areas.objects.get(pk=task.area.pk, agency=request.user.profile.agency) context = { 'active_link':'standards', 'standards_of_agency_task' : standards, 'taskid' : pk, 'taskname' : task.name, 'areaid' : area.pk, 'areaname' : area.name } return render(request, 'standards/standard_task.html', context) # AJAX Standard @login_required def updatesbyajax(request, pk): if(request.method == "GET"): success = True workingstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) # Check for correct user and userrights if(request.user.profile.agency == workingstandard.agency and request.user.has_perm("users.standardmanager")): # CHANGE GROUP # ADD if(request.GET["action"] == "s_addgroup"): workingstandard.visibleby.add(AgencyGroup.objects.get(pk=request.GET["groupid"], agency=request.user.profile.agency)) # REMOVE elif(request.GET["action"] == "s_remgroup"): workingstandard.visibleby.remove(AgencyGroup.objects.get(pk=request.GET["groupid"], agency=request.user.profile.agency)) # FILES # REMOVE elif(request.GET["action"] == "s_remfile"): workingstandard.addedfiles.remove(DataFile.objects.get(pk=request.GET["fileid"], agency=request.user.profile.agency)) # ADD elif(request.GET["action"] == "s_addfile"): workingstandard.addedfiles.add(DataFile.objects.get(pk=request.GET["fileid"], agency=request.user.profile.agency)) # STANDARD # REMOVE elif(request.GET["action"] == "s_remstandard"): workingstandard.linked_standards.remove(Standards.objects.get(pk=request.GET["standardid"], agency=request.user.profile.agency)) # ADD elif(request.GET["action"] == "s_addstandard"): workingstandard.linked_standards.add(Standards.objects.get(pk=request.GET["standardid"], agency=request.user.profile.agency)) # VERANTWORTLICHER / AUTHORITY # REMOVE elif(request.GET["action"] == "s_remverant"): workingstandard.authority.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addverant"): workingstandard.authority.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # ASUFÜRHENDER / EXECUTOR # REMOVE elif(request.GET["action"] == "s_remex"): workingstandard.executor.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addex"): workingstandard.executor.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # VERTRETER / REPRESENETATIVE # REMOVE elif(request.GET["action"] == "s_remver"): workingstandard.representative.remove(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) elif(request.GET["action"] == "s_addver"): workingstandard.representative.add(User.objects.get(pk=request.GET["userid"], profile__agency=request.user.profile.agency)) # ADD STANDARD TO AGENCYNETWORK elif(request.GET["action"] == "s_addtonetwork"): if workingstandard.public and request.user.profile.agency == workingstandard.agency: agn = AgencyNetwork.objects.get(pk=request.GET["agn_id"]) if(request.GET["newstat"] == "true"): agn.standards.add(workingstandard) else: agn.standards.remove(workingstandard) agn.lastactivity = datetime.now() agn.save() else: success = False return JsonResponse({"success" : success}) # CREATE PDF FROM STANDARD from io import BytesIO from xhtml2pdf import pisa # Utility function def convert_html_to_pdf(source_html, output_filename): result = BytesIO() pdf = pisa.pisaDocument(BytesIO(source_html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None @login_required def getStandardPDF(request, pk): standard = Standards.objects.get(pk=pk) # CHECK IF USER HAS RIGHTS TO SEE THIS Standard groupsofstandard = Standards.objects.get(pk=pk, agency=request.user.profile.agency) userisingroup = False if len(groupsofstandard.visibleby.all()) == 0: userisingroup = True else: for ag in groupsofstandard.visibleby.all(): if ag.group in request.user.groups.all(): userisingroup = True if userisingroup: pdf = convert_html_to_pdf("