2327 lines
87 KiB
Python
2327 lines
87 KiB
Python
from django.shortcuts import render, redirect
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.http import HttpResponseRedirect,HttpResponse, JsonResponse
|
|
from .forms import UsersSelfChangeForm, UsersNotificationFormStandard, AgencyGroupPerms, AgencyModulsForm, UserNewUserForm, UserProfileForm, AgencyNetworkForm, AgencyOrganigrammForm, UserTimeForm, AbsenceReasonForm, UsersNotificationFormNews, UsersNotificationFormFiles, UsersNotificationFormMessages ,UsersNotificationFormOrganizer, UsersNotificationFormChat, UsersNotificationFormAbTime, UsersNotificationFormGroups, UsersNotificationFormAgn, UsersNotificationFormTasks, AgencyBillMail, AgencyBillPlan, AgencyEndBillPlan
|
|
from django.contrib import messages
|
|
from django.contrib.auth import update_session_auth_hash
|
|
from django.contrib.auth.forms import PasswordChangeForm
|
|
from users.usersforms import AgencyUpdateForm
|
|
from users.models import AgencyJob, AgencyGroup, AgencyNetwork, Agency, AgencyNetworkPreperation, UserYearAbsenceInfo
|
|
from django.contrib.auth.models import User, Group, Permission
|
|
from users.models import UserTime, RegNotfallhilfe
|
|
import random
|
|
import string
|
|
from django.template.loader import render_to_string
|
|
from users.usersforms import UsersPermForm
|
|
from django.contrib.auth.mixins import LoginRequiredMixin
|
|
from django.views.generic import CreateView
|
|
from users.models import Profile, UserNotifications, UserTime, AgencyBills
|
|
from areas.models import Areas
|
|
from tasks.models import Tasks
|
|
import webcolors
|
|
import datetime
|
|
from datetime import date
|
|
from standards.models import Standards
|
|
from timemanagement.models import AbsenceReason, FreeDays, Workday, Absence
|
|
from django.core.mail import send_mail
|
|
from django.conf import settings
|
|
import re, os, csv, requests
|
|
from django.templatetags.static import static
|
|
from django.db.models import DateField
|
|
from django.views.generic import DeleteView, UpdateView
|
|
from timemanagement.forms import AddFreeDayForm
|
|
from django.urls import reverse_lazy
|
|
import re
|
|
import json
|
|
from django.conf import settings # import the settings file
|
|
from PIL import Image
|
|
from datetime import date, timedelta
|
|
''' MAIL '''
|
|
from django.core.mail import EmailMessage
|
|
from django.core.mail import EmailMultiAlternatives
|
|
import io as BytesIO
|
|
import base64
|
|
from django.http import HttpResponse
|
|
|
|
from django.db.models.signals import post_save
|
|
from users.signals import save_newabsence
|
|
|
|
def randomString(stringLength=10):
|
|
"""Generate a random string of fixed length """
|
|
letters = string.ascii_lowercase
|
|
return ''.join(random.choice(letters) for i in range(stringLength))
|
|
|
|
@login_required
|
|
def checkForGroupName(request, newgroupname):
|
|
stat = True
|
|
groupsagency = AgencyGroup.objects.filter(agency__pk=request.user.profile.agency.pk)
|
|
for group in groupsagency:
|
|
if group.agencygroupname.upper() == newgroupname.upper():
|
|
stat = False
|
|
return stat
|
|
|
|
@login_required
|
|
def getAllForms(request, context):
|
|
# USERFORMS
|
|
userform = UsersSelfChangeForm(instance=request.user)
|
|
passwordform = PasswordChangeForm(request.user)
|
|
context.update({'userform' : userform})
|
|
context.update({'passwordform' : passwordform})
|
|
|
|
# NOTIFICTAION FORMS
|
|
# STANDARDS
|
|
notificationforms_standard = UsersNotificationFormStandard(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_standard' : notificationforms_standard})
|
|
|
|
notificationforms_news = UsersNotificationFormNews(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_news' : notificationforms_news})
|
|
|
|
notificationforms_files = UsersNotificationFormFiles(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_files' : notificationforms_files})
|
|
|
|
notificationforms_organizer = UsersNotificationFormOrganizer(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_organizer' : notificationforms_organizer})
|
|
|
|
notificationforms_messages = UsersNotificationFormMessages(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_messages' : notificationforms_messages})
|
|
|
|
notificationforms_chat = UsersNotificationFormChat(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_chat' : notificationforms_chat})
|
|
|
|
notificationforms_abtime = UsersNotificationFormAbTime(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_abtime' : notificationforms_abtime})
|
|
|
|
notificationforms_groups = UsersNotificationFormGroups(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_groups' : notificationforms_groups})
|
|
|
|
notificationforms_agn = UsersNotificationFormAgn(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_agn' : notificationforms_agn})
|
|
|
|
notificationforms_task = UsersNotificationFormTasks(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_task' : notificationforms_task})
|
|
|
|
|
|
|
|
# AGENCY UPDATE FORMS
|
|
agencyform = AgencyUpdateForm(instance=request.user.profile.agency)
|
|
context.update({'agencyform' : agencyform})
|
|
|
|
#PERMS
|
|
perms = AgencyGroupPerms()
|
|
context.update({'perms' : perms})
|
|
|
|
#MODULFORMS
|
|
modulform = AgencyModulsForm(instance=request.user.profile.agency)
|
|
context.update({'modulform' : modulform})
|
|
|
|
#MODULSETTUNGS
|
|
#Modulsettings ORGANIGRAMM
|
|
modsettings_organigramm = AgencyOrganigrammForm(instance=request.user.profile.agency)
|
|
context.update({'modsettings_organigramm' : modsettings_organigramm})
|
|
|
|
#Modulsettings ABWESENHEIT- UND ZEITERFASSUNG
|
|
#modsettings_tm = AgencyTimeManagement(instance=request.user.profile.agency)
|
|
#context.update({'modsettings_tm' : modsettings_tm})
|
|
context.update({"modsettings_tm_abcat" : AbsenceReason.objects.filter(agency=request.user.profile.agency).order_by("name") })
|
|
|
|
|
|
# USER FOR USERTABLE
|
|
users = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk).order_by("last_name")
|
|
return context
|
|
|
|
|
|
'''
|
|
Lädt die Formulare für die einzelnen Einstellungen vollständig
|
|
'''
|
|
@login_required
|
|
def DASettings(request):
|
|
|
|
|
|
# CHECK FOR EVERY USER YEAR-DATA
|
|
uina = User.objects.filter(profile__agency=request.user.profile.agency)
|
|
today = date.today()
|
|
for u in uina:
|
|
|
|
# NO YEARS FOUND
|
|
if len(UserYearAbsenceInfo.objects.filter(agency=request.user.profile.agency, user=u)) == 0:
|
|
# CREATE DATA FOR EVERY USER
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=u, year=today.year).save()
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=u, year=today.year+1).save()
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=u, year=today.year+2).save()
|
|
|
|
# CREATE DATE FOR YEAR PLUS 2
|
|
#elif len(UserYearAbsenceInfo.objects.filter(agency=user.profile.agency, year=today.year+2)) == 0:
|
|
# uina = User.objects.filter(profile__agency=user.profile.agency)
|
|
#
|
|
# for u in uina:
|
|
# UserYearAbsenceInfo(agency=user.profile.agency, user=u, year=today.year+2).save()
|
|
|
|
|
|
|
|
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'baseurl' : settings.BASE_URL
|
|
}
|
|
context = getAllForms(request, context)
|
|
|
|
# USERS FOR MEMBERS AND GROUPCOUNTERS
|
|
usersofagency = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk).order_by("last_name")
|
|
context.update({"usersofagency" : usersofagency})
|
|
|
|
# LOAD AGENCYJOBS
|
|
context.update({"agencyjobs" : AgencyJob.objects.filter(agency__pk=request.user.profile.agency.pk).order_by("name")})
|
|
|
|
# LOAD GROUPS
|
|
if request.user.profile.agency.module_recoverdir:
|
|
agencygroups = AgencyGroup.objects.filter(agency__pk=request.user.profile.agency.pk).order_by("agencygroupname").order_by("-savefordel")
|
|
else:
|
|
agencygroups = AgencyGroup.objects.filter(agency__pk=request.user.profile.agency.pk).order_by("agencygroupname").order_by("-savefordel").exclude(agencygroupname="Notfallhilfe")
|
|
|
|
context.update({"agencygroups" : agencygroups})
|
|
|
|
# LOAD AREAS
|
|
agencyareas = Areas.objects.filter(agency__pk=request.user.profile.agency.pk).order_by('areaorder')
|
|
context.update({"agencyareas" : agencyareas})
|
|
|
|
# LOAD AGENCYNETWORKS
|
|
#agencynetworks = AgencyNetwork.objects.filter(creator_agency=request.user.profile.agency) | AgencyNetwork.objects.filter(adminagencys__in=[request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[request.user.profile.agency.pk])
|
|
|
|
#agencynetworks = AgencyNetwork.objects.filter(adminagencys__in=[request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(members__in=[request.user.profile.agency.pk]) | AgencyNetwork.objects.filter(sharemembers__in=[request.user.profile.agency.pk])
|
|
|
|
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)
|
|
|
|
context.update({"agencynetworks" : agencynetworks})
|
|
|
|
# LOAD TASKS
|
|
alltasks = Tasks.objects.filter(agency__pk=request.user.profile.agency.pk).order_by('name')
|
|
context.update({"alltasks" : alltasks})
|
|
|
|
if request.method == 'POST' and request.POST.get("settings_area") == "profil":
|
|
return SettingsProfilManagement(request, context)
|
|
elif request.method == 'POST' and request.POST.get("settings_area") == "agency":
|
|
return SettingsAgency(request, context)
|
|
elif request.method == 'POST' and request.POST.get("settings_area") == "moduls":
|
|
return SettingsAgencyModuls(request, context)
|
|
|
|
|
|
|
|
# Returning the data from database for normal-loading Settings
|
|
else:
|
|
# DEFAULT DATA FORM-INFOS
|
|
# Hier müssen alle Standard-Formulare rein, damit die Seite Settings
|
|
# generell geladen werden kann.
|
|
# PROFILE FORMS
|
|
userform = UsersSelfChangeForm(instance=request.user)
|
|
passwordform = PasswordChangeForm(request.user)
|
|
context.update({'userform' : userform})
|
|
context.update({'passwordform' : passwordform})
|
|
|
|
############################### NOTIFIFORMS START ##########################################
|
|
notificationforms_standard = UsersNotificationFormStandard(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_standard' : notificationforms_standard})
|
|
|
|
notificationforms_news = UsersNotificationFormNews(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_news' : notificationforms_news})
|
|
|
|
notificationforms_files = UsersNotificationFormFiles(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_files' : notificationforms_files})
|
|
|
|
notificationforms_organizer = UsersNotificationFormOrganizer(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_organizer' : notificationforms_organizer})
|
|
|
|
notificationforms_messages = UsersNotificationFormMessages(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_messages' : notificationforms_messages})
|
|
|
|
notificationforms_chat = UsersNotificationFormChat(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_chat' : notificationforms_chat})
|
|
|
|
notificationforms_abtime = UsersNotificationFormAbTime(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_abtime' : notificationforms_abtime})
|
|
|
|
notificationforms_groups = UsersNotificationFormGroups(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_groups' : notificationforms_groups})
|
|
|
|
notificationforms_agn = UsersNotificationFormAgn(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_agn' : notificationforms_agn})
|
|
|
|
notificationforms_task = UsersNotificationFormTasks(instance=request.user.usernotifications)
|
|
context.update({'notificationforms_task' : notificationforms_task})
|
|
############################### NOTIFIFORMS END ############################################
|
|
|
|
# AGENCY UPDATE FORMS
|
|
agencyform = AgencyUpdateForm(instance=request.user.profile.agency)
|
|
context.update({'agencyform' : agencyform})
|
|
|
|
# Abrechnung BILLS
|
|
|
|
lexdata = {}
|
|
|
|
# HEADERS CURL
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
#json_data = json.dumps(lexdata)
|
|
#r = requests.get("https://api.lexoffice.io/v1/invoices/"+AgencyBills.objects.filter(agency=request.user.profile.agency)[0].lexid, data=json_data, headers=headers)
|
|
#json.loads(r.text)
|
|
#print(r.text)
|
|
# Alle Rechnungen der Agentur abfragen
|
|
context.update({"bills" : AgencyBills.objects.filter(agency=request.user.profile.agency).order_by("-end")})
|
|
|
|
|
|
return render(request, 'dasettings/settings.html', context)
|
|
|
|
from django.http import FileResponse, Http404
|
|
|
|
@login_required
|
|
def GetBill(request, pk):
|
|
# HEADERS CURL
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
json_data = {}
|
|
|
|
r = requests.get("https://api.lexoffice.io/v1/invoices/"+AgencyBills.objects.get(pk=pk).lexid+"/document", data=json_data, headers=headers)
|
|
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'bill' : AgencyBills.objects.get(pk=pk),
|
|
'fileid' : json.loads(r.text)["documentFileId"]
|
|
}
|
|
|
|
return render(request, 'dasettings/bill_single.html', context)
|
|
|
|
import io as BytesIO
|
|
import base64
|
|
from django.http import HttpResponse
|
|
|
|
@login_required
|
|
def GetBillPDF(request, pk):
|
|
bill = AgencyBills.objects.get(pk=pk)
|
|
# Sicherheitscheck, ob der angefragte User zur Agentur gehört und das Recht hat, Agenturinfos zu bearbeiten
|
|
if ((bill.agency == request.user.profile.agency and request.user.has_perm("users.agencyinfo")) or request.user.is_staff):
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
lexdata = {
|
|
"renderType" : "pdf"
|
|
}
|
|
json_data = json.dumps(lexdata)
|
|
|
|
r = requests.get("https://api.lexoffice.io/v1/invoices/"+bill.lexid+"/document", data=json_data, headers=headers)
|
|
json.loads(r.text)
|
|
|
|
base64String = requests.get("https://api.lexoffice.io/v1/files/"+json.loads(r.text)["documentFileId"]+"/", data=json_data, headers=headers)
|
|
|
|
buffer = BytesIO.BytesIO()
|
|
content = base64.b64decode(base64String.text)
|
|
buffer.write(content)
|
|
|
|
response = HttpResponse(buffer.getvalue(),content_type="application/pdf")
|
|
response['Content-Disposition'] = 'inline;filename=some_file.pdf'
|
|
return response
|
|
else:
|
|
messages.warning(request, f'Diese Daten sind für Sie nicht einsehbar.')
|
|
return redirect("dasettings")
|
|
|
|
|
|
|
|
'''
|
|
|
|
AGENCY
|
|
|
|
Hier werden die Agenturinfos ink. Agenturcropper für das Agenturbild angepasst.
|
|
|
|
'''
|
|
@login_required
|
|
def SettingsAgency(request, context):
|
|
if request.POST.get("form_type") == "agencyform":
|
|
agencyform = AgencyUpdateForm(request.POST, instance=request.user.profile.agency)
|
|
if agencyform.is_valid():
|
|
|
|
agency = request.user.profile.agency
|
|
|
|
if 'agencypic' in request.FILES:
|
|
request.user.profile.agency.agencypic = request.FILES['agencypic']
|
|
agencyform.save()
|
|
else:
|
|
'''
|
|
SAVE ONLY AG-DATA
|
|
'''
|
|
agency.name = agencyform.cleaned_data.get('name')
|
|
agency.inhaber = agencyform.cleaned_data.get('inhaber')
|
|
agency.agency_email = agencyform.cleaned_data.get('agency_email')
|
|
agency.phone = agencyform.cleaned_data.get('phone')
|
|
agency.street = agencyform.cleaned_data.get('street')
|
|
agency.plz = agencyform.cleaned_data.get('plz')
|
|
agency.city = agencyform.cleaned_data.get('city')
|
|
agency.save()
|
|
#agencyform.save()
|
|
|
|
context['agencyform'] = AgencyUpdateForm(instance=request.user.profile.agency)
|
|
messages.success(request, f'Agenturdaten aktualisiert!')
|
|
return render(request, 'dasettings/settings.html', context)
|
|
else:
|
|
messages.success(request, f'Daten falsch eingegeben!')
|
|
context['agencyform'] = AgencyUpdateForm(instance=request.user.profile.agency)
|
|
return render(request, 'dasettings/settings.html', context)
|
|
|
|
from django.db.models import F, Func, Value
|
|
|
|
@login_required
|
|
def FreeDaysManagemenet(request, initload=0):
|
|
if(initload==1):
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'init_freedays' : True
|
|
}
|
|
return render(request, 'dasettings/freedays_management.html', context)
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'freedays' : FreeDays.objects.filter(agency=request.user.profile.agency).order_by("-day")
|
|
}
|
|
return render(request, 'dasettings/freedays_management.html', context)
|
|
|
|
@login_required
|
|
def FreeDayAdd(request):
|
|
if request.POST:
|
|
freedayform = AddFreeDayForm(request.POST, instance=request.user.profile.agency)
|
|
if freedayform.is_valid():
|
|
|
|
allfreedays = FreeDays.objects.filter(agency=request.user.profile.agency)
|
|
|
|
for day in allfreedays:
|
|
double = False
|
|
if day.day == freedayform.cleaned_data['day'] and day.year == freedayform.cleaned_data['day'].year:
|
|
double = True
|
|
|
|
|
|
if double == False:
|
|
fd = FreeDays(agency=request.user.profile.agency, day=freedayform.cleaned_data['day'], year=freedayform.cleaned_data['day'].year, name=freedayform.cleaned_data['name']).save()
|
|
|
|
messages.success(request, f'Freier Tag hinzugefügt')
|
|
else:
|
|
messages.warning(request, f'Am ' + str(freedayform.cleaned_data['day']) + " gibt es bereits einen Eintrag!")
|
|
|
|
context = {
|
|
"active_link" : "dasettings",
|
|
}
|
|
return redirect("tm-managemenetfreedays")
|
|
else:
|
|
messages.success(request, f'Fehler beim hinzufügen!')
|
|
return redirect("tm-managemenetfreedays")
|
|
else:
|
|
context = {
|
|
"active_link" : "dasettings",
|
|
"form" : AddFreeDayForm()
|
|
}
|
|
return render(request, 'dasettings/freedays_add.html', context)
|
|
|
|
|
|
class FreeDayDeleteView(LoginRequiredMixin, DeleteView):
|
|
model = FreeDays
|
|
success_url = reverse_lazy('tm-managemenetfreedays')
|
|
template_name = 'dasettings/freedays_confirm_delete.html'
|
|
|
|
def delete(self, request, *args, **kwargs):
|
|
response = super(FreeDayDeleteView, self).delete(request, *args, **kwargs)
|
|
messages.success(request, f'Freier Tag wurde gelöscht!')
|
|
return response
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super(FreeDayDeleteView, self).get_context_data(**kwargs)
|
|
context['active_link'] = 'dasettings'
|
|
return context
|
|
|
|
|
|
class AbsenceReasonDeleteView(LoginRequiredMixin, DeleteView):
|
|
model = AbsenceReason
|
|
success_url = reverse_lazy('dasettings')
|
|
template_name = 'dasettings/absencereason_confirm_delete.html'
|
|
|
|
def delete(self, request, *args, **kwargs):
|
|
try:
|
|
response = super(AbsenceReasonDeleteView, self).delete(request, *args, **kwargs)
|
|
messages.success(request, f'Abwesenheitskategorie wurde gelöscht!')
|
|
return response
|
|
except:
|
|
|
|
messages.success(request, f'Abwesenheitskategorie kann nicht gelöscht werden, da Abwesenheiten eingetragen wurden.')
|
|
return redirect('dasettings')
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super(AbsenceReasonDeleteView, self).get_context_data(**kwargs)
|
|
context['active_link'] = 'dasettings'
|
|
return context
|
|
|
|
class AbsenceReasonAddView(LoginRequiredMixin, CreateView):
|
|
model = AbsenceReason
|
|
success_url = reverse_lazy('dasettings')
|
|
form_class = AbsenceReasonForm
|
|
template_name = 'dasettings/absencereason_add.html'
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(**kwargs)
|
|
context.update({'active_link' : 'dasettings'})
|
|
return context
|
|
|
|
def form_valid(self, form):
|
|
# Send message to the site
|
|
messages.success(self.request, f'Abwesenheitskategorie angelegt!')
|
|
form.instance.color = form.cleaned_data["rgb_color"]
|
|
# SAVE OBJECTS TO SIGNALE!
|
|
form.instance.agency = self.request.user.profile.agency
|
|
return super().form_valid(form)
|
|
|
|
class AbsenceReasonUpdateView(LoginRequiredMixin, UpdateView):
|
|
model = AbsenceReason
|
|
template_name = 'dasettings/absencereason_update.html'
|
|
success_url = reverse_lazy('dasettings')
|
|
form_class = AbsenceReasonForm
|
|
|
|
def form_valid(self, form):
|
|
# Send message to the site
|
|
messages.success(self.request, f'Abwesenheitskategorie aktualisiert!')
|
|
self.object.color = form.cleaned_data["rgb_color"]
|
|
self.object.save()
|
|
return super().form_valid(form)
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super(AbsenceReasonUpdateView, self).get_context_data(**kwargs)
|
|
context['active_link'] = 'dasettings'
|
|
return context
|
|
|
|
@login_required
|
|
def SettingsAgencyModuls(request, context):
|
|
if request.POST.get("form_type") == "agencymodform":
|
|
agencymoduleform = AgencyModulsForm(request.POST, instance=request.user.profile.agency)
|
|
if agencymoduleform.is_valid():
|
|
|
|
agencymoduleform.save()
|
|
|
|
# Check, if Timemanagement is deactivate, to deactivate Zeiterfassung
|
|
if(request.user.profile.agency.module_timemanagement == False):
|
|
ag = request.user.profile.agency
|
|
#ag.module_timemanagement_ze = False
|
|
|
|
if(request.user.has_perm("users.modulesconfig")):
|
|
FreeDays.objects.filter(agency=request.user.profile.agency).delete()
|
|
|
|
ag.save()
|
|
|
|
temp_freedays = FreeDays.objects.filter(agency=request.user.profile.agency)
|
|
|
|
if(request.user.profile.agency.module_timemanagement and len(temp_freedays) == 0):
|
|
messages.success(request, f'Moduleinstellungen aktualisiert! Bitte prüfen Sie Ihre Feiertagseinstellungen')
|
|
return redirect('tm-initload', 1)
|
|
else:
|
|
context['modulform'] = AgencyModulsForm(instance=request.user.profile.agency)
|
|
messages.success(request, f'Moduleinstellungen aktualisiert!')
|
|
return render(request, 'dasettings/settings.html', context)
|
|
else:
|
|
context['modulform'] = AgencyModulsForm(instance=request.user.profile.agency)
|
|
messages.success(request, f'Fehler beim aktualisieren! Bitte wenden Sie sich an den Support.')
|
|
return render(request, 'dasettings/settings.html', context)
|
|
|
|
'''
|
|
|
|
Hier werden die Profilinfos des User zurückgesetzt; Parameter kommen von Settings()
|
|
|
|
- Email
|
|
- Passwort aktualisieren
|
|
|
|
'''
|
|
import requests
|
|
@login_required
|
|
def SettingsProfilManagement(request, context):
|
|
# Check, which form
|
|
# USERFORM
|
|
if request.POST.get("form_type") == "userform":
|
|
userform = UsersSelfChangeForm(request.POST, instance=request.user)
|
|
if userform.is_valid():
|
|
usert = User.objects.get(pk=request.user.pk)
|
|
userform.save()
|
|
usert.username = userform.cleaned_data.get("email")
|
|
usert.email = userform.cleaned_data.get("email")
|
|
usert.save()
|
|
messages.success(request, f'E-Mailadresse aktualisiert!')
|
|
passwordform = PasswordChangeForm(request.user)
|
|
context['userform'] = userform
|
|
context['passwordform'] = passwordform
|
|
return render(request, 'dasettings/settings.html', context)
|
|
else:
|
|
messages.success(request, f'Keine E-Mailadresse eingegeben oder E-Mail bereits vorhanden!')
|
|
passwordform = PasswordChangeForm(request.user)
|
|
userform = UsersSelfChangeForm(instance=request.user)
|
|
context['userform'] = userform
|
|
context['passwordform'] = passwordform
|
|
return render(request, 'dasettings/settings.html', context)
|
|
# PASSWORDFORM
|
|
elif request.POST.get("form_type") == "passwordform":
|
|
passwordform = PasswordChangeForm(request.user, request.POST)
|
|
if passwordform.is_valid():
|
|
passwordform.save()
|
|
update_session_auth_hash(request, request.user)
|
|
userform = UsersSelfChangeForm(instance=request.user)
|
|
context['userform'] = userform
|
|
context['passwordform'] = passwordform
|
|
messages.success(request, f'Passwort aktualisiert!')
|
|
return render(request, 'dasettings/settings.html', context)
|
|
else:
|
|
messages.success(request, f'Passwort falsch eingegeben!')
|
|
passwordform = PasswordChangeForm(request.user)
|
|
userform = UsersSelfChangeForm(instance=request.user)
|
|
context['userform'] = userform
|
|
context['passwordform'] = passwordform
|
|
return render(request, 'dasettings/settings.html', context)
|
|
|
|
def get_random_number(length = 6):
|
|
result_str = ''.join(random.choice("0123456789") for i in range(length))
|
|
return result_str
|
|
|
|
@login_required
|
|
def SettingsAjaxRouter(request):
|
|
success = False
|
|
data = {}
|
|
# UPDATE NOTIFICATIONS BY FIELDNAME AND NEW VALUE
|
|
'''
|
|
if request.method == 'GET' and request.GET['action'] == "update_notifications" :
|
|
success = False
|
|
new_stat = request.GET['new_stat']
|
|
field_to_change = getattr(request.user.profile, request.GET['fieldname'])
|
|
if(field_to_change or not field_to_change):
|
|
if(new_stat == "1"):
|
|
setattr(request.user.profile, request.GET['fieldname'], True)
|
|
else:
|
|
setattr(request.user.profile, request.GET['fieldname'], False)
|
|
request.user.profile.save()
|
|
success = True
|
|
'''
|
|
if request.method == 'GET' and request.GET['action'] == "update_notifications" :
|
|
success = False
|
|
new_stat = request.GET['new_stat']
|
|
field_to_change = getattr(request.user.usernotifications, request.GET['fieldname'])
|
|
if(field_to_change or not field_to_change):
|
|
if(new_stat == "1"):
|
|
setattr(request.user.usernotifications, request.GET['fieldname'], True)
|
|
else:
|
|
setattr(request.user.usernotifications, request.GET['fieldname'], False)
|
|
request.user.usernotifications.save()
|
|
success = True
|
|
# UPDATE TOOLTUP
|
|
elif request.method == 'GET' and request.GET['action'] == "change_showtooltips" :
|
|
newtooltipvalue = False
|
|
user = User.objects.get(pk=request.user.pk, profile__agency=request.user.profile.agency)
|
|
if(request.GET['newtoolvalue'] == "true"):
|
|
user.profile.showtooltips = True
|
|
newtooltipvalue = True
|
|
else:
|
|
user.profile.showtooltips = False
|
|
user.save()
|
|
success = True
|
|
data = {'newttvalue' : newtooltipvalue}
|
|
# UPDATE AGENCYJOB
|
|
elif request.method == 'GET' and request.GET['action'] == "update_agencyfunc" :
|
|
job_id = request.GET['id']
|
|
job_value = request.GET['newvalue']
|
|
tempjob = AgencyJob.objects.get(pk=job_id, agency=request.user.profile.agency)
|
|
tempjob.name = job_value
|
|
tempjob.save()
|
|
success = True
|
|
# DELETE AGENVY JOB FUNC - RETURN ONLY NAME FOR CONFIRM
|
|
elif request.method == 'GET' and request.GET['action'] == "get_agencyfunc" :
|
|
job_id = request.GET['id']
|
|
tempjob = AgencyJob.objects.get(pk=job_id, agency=request.user.profile.agency)
|
|
data = {"funcname" : tempjob.name}
|
|
success = True
|
|
# DELETE FINAL AGENCY JOB
|
|
elif request.method == 'GET' and request.GET['action'] == "delete_agencyfunc" :
|
|
job_id = request.GET['id']
|
|
tempjob = AgencyJob.objects.get(pk=job_id, agency=request.user.profile.agency)
|
|
tempjob.delete()
|
|
success = True
|
|
elif request.method == 'GET' and request.GET['action'] == "add_agencyfunc" :
|
|
tempjob = AgencyJob(name="", agency=request.user.profile.agency)
|
|
tempjob.save()
|
|
data = {"new_id" : tempjob.pk}
|
|
success = True
|
|
# GRUPPENAMEN AKTUALISIEREN
|
|
elif request.method == 'GET' and request.GET['action'] == "update_groupname" :
|
|
group = AgencyGroup.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
if(checkForGroupName(request, request.GET['newvalue'])):
|
|
group.agencygroupname = request.GET['newvalue']
|
|
group.save()
|
|
data = {"newvalue" : group.agencygroupname}
|
|
|
|
# Update Groupname in NC
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"groupid" : group.nc_name,
|
|
"newvalue" : request.GET['newvalue']
|
|
}
|
|
r = requests.post(settings.NEXTCLOUD_URL + "/apps/agency/updateagencygroup", data=data_nc, headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
|
|
success = True
|
|
else:
|
|
success = False
|
|
# GRUPPENNAMEN HOLEN
|
|
elif request.method == 'GET' and request.GET['action'] == "get_groupname" :
|
|
group = AgencyGroup.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
data = {"groupname" : group.agencygroupname}
|
|
success = True
|
|
# SAVE NEW GROUP ADD GROUP
|
|
elif request.method == 'GET' and request.GET['action'] == "add_group" :
|
|
if(checkForGroupName(request, request.GET['newvalue'])):
|
|
tempgroup = Group(name=str(request.user.profile.agency.pk) + "_" + randomString(8))
|
|
tempgroup.save()
|
|
tempgroup_ag = AgencyGroup(savefordel=False, group=tempgroup, agency=request.user.profile.agency, agencygroupname=request.GET['newvalue'])
|
|
|
|
success = True
|
|
data = {"group_id" : tempgroup_ag.pk, "group_name" : tempgroup_ag.agencygroupname}
|
|
nc_groupid = "agencymaingroupid_" + str(tempgroup_ag.agency.pk) + "_subgroup_" + get_random_number()
|
|
tempgroup_ag.nc_name = nc_groupid
|
|
tempgroup_ag.save()
|
|
|
|
# ADD group in NC
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"groupid" : nc_groupid,
|
|
}
|
|
r = requests.post(settings.NEXTCLOUD_URL + "ocs/v1.php/cloud/groups", data=data_nc, headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
|
|
# Group created, set display name in NC
|
|
data_nc = {
|
|
"name": tempgroup_ag.agencygroupname,
|
|
"id" : nc_groupid
|
|
}
|
|
|
|
r = requests.post(settings.NEXTCLOUD_URL + "apps/agency/regr", data=data_nc, headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
|
|
# Add current User to this Group
|
|
# TODO: Hier checken, ob das wirklich nötig ist...?
|
|
#data_nc = {
|
|
# "groupid" : nc_groupid
|
|
#}
|
|
|
|
#r = requests.post(settings.NEXTCLOUD_URL + "ocs/v1.php/cloud/users/" + request.user.username + "/groups", data=data_nc, headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
|
|
else:
|
|
success = False
|
|
# DELETE A GROUP
|
|
elif request.method == 'GET' and request.GET['action'] == "delete_group" :
|
|
groupag = AgencyGroup.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
|
|
# DELETE GROUP IN NC
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"groupid" : groupag.nc_name,
|
|
}
|
|
r = requests.request("DELETE", settings.NEXTCLOUD_URL + "/ocs/v1.php/cloud/groups/" + groupag.nc_name,headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
group_to_del = groupag.group
|
|
group_to_del.delete()
|
|
success = True
|
|
|
|
# PERMISSIONS ON GROUP!
|
|
elif request.method == 'GET' and request.GET['action'] == "change_perm_group" :
|
|
success = True
|
|
group_id = request.GET['id']
|
|
perm_name = request.GET['perm']
|
|
val = request.GET['val']
|
|
aggroup = AgencyGroup.objects.get(pk=group_id, agency=request.user.profile.agency)
|
|
# CHECK IF REQUESTED USER IS IN THIS AGENCY
|
|
if(request.user.profile.agency.pk == aggroup.agency.pk):
|
|
if(val == "true"):
|
|
tempperm = Permission.objects.get(codename=perm_name)
|
|
aggroup.group.permissions.add(tempperm)
|
|
else:
|
|
tempperm = Permission.objects.get(codename=perm_name)
|
|
aggroup.group.permissions.remove(tempperm)
|
|
else:
|
|
success = False
|
|
# REMOVE USER FROM GROUP
|
|
elif request.method == 'GET' and request.GET['action'] == "remove_user_from_group" :
|
|
success = True
|
|
groupid = request.GET['groupid']
|
|
userid = request.GET['userid']
|
|
aggroup = AgencyGroup.objects.get(pk=groupid, agency=request.user.profile.agency)
|
|
usertoremove = User.objects.get(pk=userid, profile__agency=request.user.profile.agency)
|
|
# CHECK IF REQUESTED USER IS IN THIS AGENCY
|
|
if(request.user.profile.agency.pk == aggroup.agency.pk):
|
|
if aggroup.group in usertoremove.groups.all():
|
|
aggroup.group.user_set.remove(usertoremove)
|
|
|
|
data = {"userid" : usertoremove.pk, "groupid" : aggroup.pk, "user_fname" : usertoremove.first_name, "user_lname" : usertoremove.last_name}
|
|
# User add
|
|
# NC ADD USER TO GROUP
|
|
# first_name and last_name CHANGE - Update in NC as DisplayName
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"groupid" : aggroup.nc_name,
|
|
}
|
|
r = requests.request("DELETE", settings.NEXTCLOUD_URL + "/ocs/v1.php/cloud/users/" + usertoremove.username + "/groups",headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API), data=data_nc)
|
|
else:
|
|
success = False
|
|
# ADD USER TO GROUP
|
|
elif request.method == 'GET' and request.GET['action'] == "add_user_to_group" :
|
|
success = True
|
|
groupid = request.GET['groupid']
|
|
userid = request.GET['userid']
|
|
aggroup = AgencyGroup.objects.get(pk=groupid, agency=request.user.profile.agency)
|
|
usertoadd = User.objects.get(pk=userid, profile__agency=request.user.profile.agency)
|
|
# CHECK IF REQUESTED USER IS IN THIS AGENCY
|
|
if(request.user.profile.agency.pk == aggroup.agency.pk):
|
|
aggroup.group.user_set.add(usertoadd)
|
|
data = {"userid" : usertoadd.pk, "groupid" : aggroup.pk, "user_fname" : usertoadd.first_name, "user_lname" : usertoadd.last_name}
|
|
|
|
# User add
|
|
# NC ADD USER TO GROUP
|
|
# first_name and last_name CHANGE - Update in NC as DisplayName
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"groupid" : aggroup.nc_name,
|
|
}
|
|
r = requests.post(settings.NEXTCLOUD_URL + "/ocs/v1.php/cloud/users/" + usertoadd.username + "/groups",headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API), data=data_nc)
|
|
|
|
else:
|
|
success = False
|
|
# AREA
|
|
# AREANAMEN HOLEN
|
|
elif request.method == 'GET' and request.GET['action'] == "get_areaname" :
|
|
area = Areas.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
data = {"areaname" : area.name, "areacolor" : area.color}
|
|
success = True
|
|
# ARENAMEN UPDATE
|
|
elif request.method == 'GET' and request.GET['action'] == "update_areaname" :
|
|
area = Areas.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
area.name = request.GET['newvalue']
|
|
area.color = request.GET['color']
|
|
area.save()
|
|
data = {"newvalue" : area.name, "color" : area.color}
|
|
success = True
|
|
# ADD AREA
|
|
elif request.method == 'GET' and request.GET['action'] == "add_area" :
|
|
area = Areas(created_area_by=request.user, agency=request.user.profile.agency, name=request.GET["newvalue"], color=request.GET['color'])
|
|
area.save()
|
|
success = True
|
|
# REMOVE AREA
|
|
elif request.method == 'GET' and request.GET['action'] == "remove_area" :
|
|
todelarea = Areas.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
# REMOVE STANDARDS AREA
|
|
tempstandards = Standards.objects.filter(agency=request.user.profile.agency, area=todelarea)
|
|
if(request.user.has_perm('users.standardmanager')):
|
|
for s in tempstandards:
|
|
s.area = None
|
|
s.task = None
|
|
s.public = False
|
|
s.save()
|
|
|
|
tasks = Tasks.objects.filter(agency=request.user.profile.agency, area=todelarea).delete()
|
|
todelarea.delete()
|
|
success = True
|
|
else:
|
|
success = False
|
|
|
|
# ADD TASK
|
|
elif request.method == 'GET' and request.GET['action'] == "add_task" :
|
|
task = Tasks(created_area_by=request.user, area=Areas.objects.get(pk=request.GET['areaid']), agency=request.user.profile.agency, name=request.GET["newvalue"])
|
|
task.save()
|
|
taskcreator_fullname = task.created_area_by.first_name + " " + task.created_area_by.last_name
|
|
data = {"name" : task.name, "newtaskid" : task.pk, "areaname" : task.area.name, "taskcreator_fullname" : taskcreator_fullname, "createdate" : task.created_area_date.strftime("%d. %B %Y")}
|
|
success = True
|
|
# TASKNAME VISIBLE UND USERS HOLEN
|
|
elif request.method == 'GET' and request.GET['action'] == "get_taskname" :
|
|
task = Tasks.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
# User still in Area
|
|
# Get all Users from same Agency which are NOT in context_added_users
|
|
added_users = task.usersfield.all()
|
|
addus = {}
|
|
posus = {}
|
|
i = 0
|
|
# GET ADDED USERS
|
|
for us in added_users:
|
|
addus.update({ i : {"fullname" : us.first_name + " " + us.last_name, "userid" : us.pk}})
|
|
i += 1
|
|
|
|
# GET POSSIBLE TO ADD USERS
|
|
k = 0
|
|
possible_users = User.objects.filter(profile__agency__pk=request.user.profile.agency.pk).exclude(pk__in=added_users)
|
|
for us in possible_users:
|
|
posus.update({ k : {"fullname" : us.first_name + " " + us.last_name, "userid" : us.pk}})
|
|
k += 1
|
|
data = {"taskname" : task.name, "visible" : task.visible, "added_users" : addus, "addedl" : i, "possl" : k, "possible_users" : posus, "taskarea" : task.area.pk}
|
|
success = True
|
|
# REMOVE Task
|
|
elif request.method == 'GET' and request.GET['action'] == "remove_task" :
|
|
|
|
todeltask = Tasks.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
# REMOVE STANDARDS AREA
|
|
tempstandards = Standards.objects.filter(agency=request.user.profile.agency, task=todeltask)
|
|
if(request.user.has_perm('users.standardmanager')):
|
|
for s in tempstandards:
|
|
s.task = None
|
|
s.public = False
|
|
s.save()
|
|
todeltask.delete()
|
|
success = True
|
|
else:
|
|
success = False
|
|
#success = True
|
|
# UPDATE TASK VISIBLE
|
|
elif request.method == 'GET' and request.GET['action'] == "update_visible_taskname" :
|
|
task = Tasks.objects.get(pk=request.GET['id'], agency=request.user.profile.agency)
|
|
if(task.visible):
|
|
task.visible = False;
|
|
else:
|
|
task.visible = True;
|
|
task.save()
|
|
success = True
|
|
# UPDATE TASKNAME
|
|
elif request.method == 'GET' and request.GET['action'] == "change_taskname" :
|
|
task = Tasks.objects.get(pk=request.GET['id'])
|
|
task.name = request.GET["newvalue"]
|
|
data = {"newvalue" : task.name}
|
|
newareaid = request.GET["newareaid"]
|
|
standardsmoved = False
|
|
if int(task.area.pk) != int(newareaid):
|
|
standardsmoved = True
|
|
newareaobj = Areas.objects.get(pk=newareaid, agency=request.user.profile.agency)
|
|
Standards.objects.filter(agency=request.user.profile.agency, area=task.area, task=task).update(area=newareaobj)
|
|
task.area = newareaobj
|
|
task.save()
|
|
data = {"newvalue" : task.name, "smoved" : standardsmoved}
|
|
success = True
|
|
# UPDATE USER MAIL
|
|
elif request.method == 'GET' and request.GET['action'] == "update_usermail" :
|
|
tempuser = User.objects.get(pk=request.GET['userid'])
|
|
if(request.user.profile.agency == tempuser.profile.agency and request.user.has_perm('users.usermanager')):
|
|
tempmail = tempuser.email
|
|
regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$'
|
|
if(re.search(regex,request.GET['newmail'])):
|
|
newmail = request.GET['newmail']
|
|
usertest = User.objects.filter(email=newmail)
|
|
if(len(usertest) > 0):
|
|
data = {"mail" : tempmail}
|
|
success = False
|
|
else:
|
|
tempuser.email = newmail
|
|
#tempuser.username = newmail
|
|
tempuser.save()
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"key" : "email",
|
|
"value" : newmail
|
|
}
|
|
print(data_nc)
|
|
r = requests.put(settings.NEXTCLOUD_URL + "/ocs/v1.php/cloud/users/" + tempuser.username,headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API), data=data_nc)
|
|
print(r.text)
|
|
success = True
|
|
else:
|
|
data = {"mail" : tempmail}
|
|
success = False
|
|
else:
|
|
success = False
|
|
# UPDATE USERNAME
|
|
elif request.method == 'GET' and request.GET['action'] == "update_usernames" :
|
|
tempuser = User.objects.get(pk=request.GET['userid'])
|
|
if(request.user.profile.agency == tempuser.profile.agency and request.user.has_perm('users.usermanager')):
|
|
regex = '^[a-zA-Z0-9_.-üöäÜÖÄ ]+$'
|
|
if(re.search(regex,request.GET['new_first_name']) and re.search(regex,request.GET['new_last_name'])):
|
|
tempuser.first_name = request.GET['new_first_name']
|
|
tempuser.last_name = request.GET['new_last_name']
|
|
tempuser.save()
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = True
|
|
|
|
# first_name and last_name CHANGE - Update in NC as DisplayName
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
data_nc = {
|
|
"key" : "displayname",
|
|
"value" : tempuser.first_name + " " + tempuser.last_name
|
|
}
|
|
r = requests.put(settings.NEXTCLOUD_URL + "/ocs/v1.php/cloud/users/" + tempuser.username,headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API), data=data_nc)
|
|
else:
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = False
|
|
else:
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = False
|
|
# UPDATE FREEDAYS
|
|
elif request.method == 'GET' and request.GET['action'] == "initloadfreedays" :
|
|
if(request.user.has_perm('users.modulesconfig')):
|
|
temp_freedays = FreeDays.objects.filter(agency=request.user.profile.agency)
|
|
|
|
if(len(temp_freedays) == 0):
|
|
tempdays_thisyear = loadingFreeDays(request.user.profile.agency.plz, date.today().year)
|
|
tempdays_lastyear = loadingFreeDays(request.user.profile.agency.plz, date.today().year - 1)
|
|
tempdays_nextyear = loadingFreeDays(request.user.profile.agency.plz, date.today().year + 1)
|
|
|
|
if(tempdays_thisyear != False):
|
|
|
|
for k in tempdays_lastyear.keys():
|
|
tempdate = tempdays_lastyear[k]["datum"].split("-")
|
|
FreeDays(agency=request.user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=date.today().year-1).save()
|
|
|
|
for k in tempdays_thisyear.keys():
|
|
tempdate = tempdays_thisyear[k]["datum"].split("-")
|
|
FreeDays(agency=request.user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=date.today().year).save()
|
|
|
|
for k in tempdays_nextyear.keys():
|
|
tempdate = tempdays_nextyear[k]["datum"].split("-")
|
|
FreeDays(agency=request.user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=date.today().year+1).save()
|
|
messages.success(request, f'Feiertage erfolgreich gespeichert!')
|
|
success = True
|
|
else:
|
|
success = False
|
|
else:
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = False
|
|
|
|
# LOAD MULTIPLE FREEDAYS
|
|
elif request.method == 'GET' and request.GET['action'] == "initloadfreedaysmulti" :
|
|
if(request.user.has_perm('users.modulesconfig')):
|
|
|
|
#tempdays_year = False
|
|
if(request.GET["land"] == "true"):
|
|
|
|
tempdays_year = loadingFreeDaysMulti(request.user.profile.agency.plz, request.GET["year"], True)
|
|
|
|
allfreedays = FreeDays.objects.filter(agency=request.user.profile.agency)
|
|
|
|
if(tempdays_year != False):
|
|
for k in tempdays_year.keys():
|
|
tempdate = tempdays_year[k].split("-")
|
|
|
|
double = False
|
|
|
|
for day in allfreedays:
|
|
if day.day == datetime.date(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])) and day.year == int(request.GET["year"]):
|
|
double = True
|
|
|
|
|
|
if double == False:
|
|
FreeDays(agency=request.user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=int(request.GET["year"])).save()
|
|
|
|
messages.success(request, f'Feiertage erfolgreich gespeichert!')
|
|
success = True
|
|
else:
|
|
success = False
|
|
|
|
else:
|
|
tempdays_year = loadingFreeDaysMulti(request.user.profile.agency.plz, request.GET["year"], False)
|
|
allfreedays = FreeDays.objects.filter(agency=request.user.profile.agency)
|
|
|
|
if(tempdays_year != False):
|
|
for k in tempdays_year.keys():
|
|
|
|
double = False
|
|
|
|
tempdate = tempdays_year[k]["datum"].split("-")
|
|
|
|
for day in allfreedays:
|
|
|
|
if day.day == datetime.date(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])) and day.year == int(request.GET["year"]):
|
|
double = True
|
|
if double == False:
|
|
FreeDays(agency=request.user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=int(request.GET["year"])).save()
|
|
|
|
messages.success(request, f'Feiertage erfolgreich gespeichert!')
|
|
success = True
|
|
else:
|
|
success = False
|
|
else:
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = False
|
|
|
|
# DELETE ALL FREE DAYS
|
|
elif request.method == 'GET' and request.GET['action'] == "delallfreedays" :
|
|
if(request.user.has_perm('users.modulesconfig')):
|
|
FreeDays.objects.filter(agency=request.user.profile.agency).delete()
|
|
messages.success(request, f'Feiertage erfolgreich entfernt!')
|
|
success = True
|
|
else:
|
|
data = {"userfullname" : tempuser.first_name + " " + tempuser.last_name}
|
|
success = False
|
|
#return render(request, 'dasettings/change_absence_yeardata.html', context)
|
|
|
|
# HOLIDAYS UPDATE
|
|
elif request.method == 'GET' and request.GET['action'] == "update_holidays" :
|
|
context = {
|
|
"user_years" : UserYearAbsenceInfo.objects.filter(user=User.objects.get(pk=request.GET["userid"])),
|
|
}
|
|
return render(request, 'dasettings/change_absence_yeardata.html', context)
|
|
# UPDATE HOLIDAYS SAVE
|
|
elif request.method == 'GET' and request.GET['action'] == "update_holidays_save" :
|
|
# GET ELEMENTS
|
|
newHolidayData = request.GET["new_data_info"].split("___")
|
|
# EVERY ELEMENT GET ID AND SAVE NEW DAY-INFO
|
|
user_to_recalculate = User.objects.get(pk=request.GET["userid"])
|
|
# DELETE ALL USED DAYS
|
|
absences = Absence.objects.filter(user=user_to_recalculate)
|
|
post_save.disconnect(save_newabsence, sender=Absence)
|
|
|
|
for ab in absences:
|
|
ab.holidays_normal = 0.0
|
|
ab.holidays_rest = 0.0
|
|
ab.holidays_normal_next = 0.0
|
|
ab.holidays_rest_next = 0.0
|
|
ab.save()
|
|
|
|
for ele in newHolidayData:
|
|
ele_elements = ele.split("__")
|
|
|
|
if(len(ele_elements) == 2):
|
|
ele_id = ele_elements[0].split("_")[3]
|
|
ele_type = ele_elements[0].split("_")[2]
|
|
temp_year = UserYearAbsenceInfo.objects.get(pk=ele_id, agency=request.user.profile.agency)
|
|
if(ele_type == "nor"):
|
|
temp_year.days = ele_elements[1]
|
|
|
|
elif(ele_type == "rest"):
|
|
temp_year.restdays = ele_elements[1]
|
|
|
|
temp_year.days_inuse = 0
|
|
temp_year.save()
|
|
|
|
context = {
|
|
"user_years" : UserYearAbsenceInfo.objects.filter(user=User.objects.get(pk=request.GET["userid"])),
|
|
}
|
|
|
|
|
|
absences = Absence.objects.filter(user=user_to_recalculate, reason__is_holiday=True).order_by("start")
|
|
|
|
ab_counter = 0
|
|
|
|
# RECALCULATE ALL ABSENCES
|
|
for ab in absences:
|
|
calculateNewAbsenceDate(ab)
|
|
ab_counter += 1
|
|
post_save.connect(save_newabsence, sender=Absence)
|
|
tomany = ""
|
|
# After Absence checking
|
|
for year in UserYearAbsenceInfo.objects.filter(user=User.objects.get(pk=request.GET["userid"])):
|
|
if year.days_inuse > year.days+year.restdays:
|
|
tomany = "Es sind mehr Abwesenheiten eingetragen als verfügbar. Bitte prüfen Sie die Abwesenheiten des Mitarbeiters."
|
|
|
|
context.update({"ab_counter" : ab_counter, "tomanyinfo" : tomany})
|
|
return render(request, 'dasettings/data_absence_yeardata.html', context)
|
|
# RESET TIMEMANAGEMENT
|
|
elif request.method == "GET" and request.GET['action'] == "del_tmdata" :
|
|
tempuser = User.objects.get(pk=request.GET['userid'])
|
|
if(request.user.has_perm('users.usermanager') and request.user.profile.agency == tempuser.profile.agency):
|
|
deluntildate = tempuser.usertime.usetime_start
|
|
delete_days = Workday.objects.filter(user=tempuser, start__lt=deluntildate).delete()
|
|
return JsonResponse({"success" : success, "data" : data})
|
|
# Change external Access
|
|
elif request.method == "GET" and request.GET['action'] == "changeexternalaccess" :
|
|
if(request.user.has_perm('users.absencemanager') and request.user.profile.agency.pk == int(request.GET['agency'])):
|
|
if(request.GET['newvalue'] == "true"):
|
|
request.user.profile.agency.agencycal_publicstatus = 1
|
|
|
|
if len(request.user.profile.agency.agencycalurl) == 0:
|
|
request.user.profile.agency.agencycalurl = randomStringNum(30)
|
|
request.user.profile.agency.agencycalurl_all = randomStringNum(30)
|
|
|
|
request.user.profile.agency.save()
|
|
else:
|
|
request.user.profile.agency.agencycal_publicstatus = 0
|
|
request.user.profile.agency.save()
|
|
else:
|
|
success = False
|
|
|
|
return JsonResponse({"success" : success, "data" : data})
|
|
else:
|
|
success = False
|
|
return JsonResponse({"success" : success, "data" : data})
|
|
|
|
|
|
''' BERECHNUNG URLAUBSTAGE USW. '''
|
|
def calculateNewAbsenceDate(instance):
|
|
|
|
newdata = getFinalHolidayData(instance)
|
|
|
|
abinfo = list(UserYearAbsenceInfo.objects.filter(user=instance.user, year=instance.start.year))[0]
|
|
abinfo_lastyear = ""
|
|
abinfo_nextyear = ""
|
|
|
|
is_lastyear = False
|
|
|
|
abinfo_lastyear = list(UserYearAbsenceInfo.objects.filter(user=instance.user, year=instance.start.year-1))
|
|
if(len(abinfo_lastyear) > 0):
|
|
is_lastyear = True
|
|
abinfo_lastyear = abinfo_lastyear[0]
|
|
|
|
is_nextyear = False
|
|
abinfo_nextyear = list(UserYearAbsenceInfo.objects.filter(user=instance.user, year=instance.start.year+1))
|
|
if(len(abinfo_nextyear) > 0):
|
|
is_nextyear = True
|
|
abinfo_nextyear = abinfo_nextyear[0]
|
|
|
|
multiple_info_needays = False
|
|
if(hasattr(newdata[3], "__len__")):
|
|
multiple_info_needays = True
|
|
|
|
# Gleiches Jahr MIT Rest
|
|
if(multiple_info_needays and newdata[3][2] == False):
|
|
# Rest ist positiv, daher bleibt rest übrig, rest wird in absence gespeichert und vom rest des Jahres-Restes abgezogen
|
|
# Rest ist positiv, damit bleibt Rest übrig
|
|
if(newdata[3][0] > 0):
|
|
instance.holidays_rest = abinfo.restdays - newdata[3][0]
|
|
instance.save()
|
|
abinfo.restdays = newdata[3][0]
|
|
abinfo.save()
|
|
# Rest ist negativ
|
|
elif(newdata[3][0] < 0):
|
|
instance.holidays_rest = (abinfo.restdays - newdata[3][0]) - newdata[3][0]*(-1)
|
|
instance.holidays_normal = newdata[3][0]*(-1)
|
|
instance.save()
|
|
abinfo.restdays = 0
|
|
abinfo.days_inuse = abinfo.days_inuse + newdata[3][0]*(-1)
|
|
abinfo.save()
|
|
# Rest ist Urlaubsdauer
|
|
else:
|
|
instance.holidays_rest = abinfo.restdays
|
|
instance.save()
|
|
#abinfo.days_inuse = abinfo.days_inuse + abinfo.restdays
|
|
abinfo.restdays = 0
|
|
abinfo.save()
|
|
# Gleiches Jahr ohne Rest
|
|
elif(not multiple_info_needays):
|
|
abinfo.days_inuse = abinfo.days_inuse + newdata[3]
|
|
abinfo.save()
|
|
instance.holidays_normal = newdata[3]
|
|
instance.save()
|
|
# Mehrere Jahre
|
|
elif(multiple_info_needays and newdata[3][2] == True):
|
|
|
|
abinfo.days_inuse = abinfo.days_inuse + newdata[3][0]
|
|
abinfo.save()
|
|
abinfo_nextyear.days_inuse = abinfo_nextyear.days_inuse + newdata[3][1]
|
|
abinfo_nextyear.restdays = abinfo_nextyear.restdays - newdata[3][3]
|
|
abinfo_nextyear.save()
|
|
|
|
# Hier werden alle benötigten Tage von Vor- und Nächstem Jahr gespeichert
|
|
instance.holidays_normal = newdata[3][0]
|
|
instance.holidays_rest = 0
|
|
instance.holidays_normal_next = newdata[3][1]
|
|
instance.holidays_rest_next = newdata[3][3]
|
|
instance.save()
|
|
|
|
''' AB HIER WIEDER RAUSNEHMEN '''
|
|
def getFinalHolidayData(abscence):
|
|
user = abscence.user
|
|
usertimedata = UserTime.objects.get(user=user)
|
|
today = date.today()
|
|
start_day_obj = abscence.start
|
|
end_day_obj = abscence.end
|
|
|
|
try:
|
|
holidayloose_date = datetime.date(start_day_obj.year, int(usertimedata.loose_holidedate.split(".")[1]), int(usertimedata.loose_holidedate.split(".")[0]))
|
|
except:
|
|
holidayloose_date = datetime.date(2020, int(usertimedata.loose_holidedate.split(".")[1]), int(usertimedata.loose_holidedate.split(".")[0]))
|
|
|
|
#start_half = abscence.start_ishalf
|
|
#end_half = abscence.end_ishalf
|
|
|
|
start_half = False
|
|
if abscence.startday_info == "1" or abscence.startday_info == "2":
|
|
start_half = True
|
|
|
|
end_half = False
|
|
if abscence.endday_info == "1" or abscence.endday_info == "2":
|
|
end_half = True
|
|
|
|
choosenyear = abscence.start.year
|
|
yeardata = list(UserYearAbsenceInfo.objects.filter(user=user, agency=user.profile.agency, year=choosenyear))[0]
|
|
|
|
holiday_thisyear = 0
|
|
holiday_lastyear = yeardata.restdays
|
|
holiday_nextyear = 0
|
|
|
|
|
|
|
|
try:
|
|
holiday_nextyear = list(UserYearAbsenceInfo.objects.filter(user=user, agency=user.profile.agency,
|
|
year=choosenyear+1))[0].days - list(UserYearAbsenceInfo.objects.filter(user=user, agency=user.profile.agency,
|
|
year=choosenyear+1))[0].days_inuse
|
|
holiday_nextyear_rest = list(UserYearAbsenceInfo.objects.filter(user=user, agency=user.profile.agency,
|
|
year=choosenyear+1))[0].restdays
|
|
except:
|
|
holiday_nextyear = yeardata.days
|
|
|
|
# Urlaub innerhalb eines Jahres inkl. Prüfung auf Resturlaubsanspruch
|
|
if(end_day_obj.year == start_day_obj.year):
|
|
# Startt des Urlaubs NACH Verfallsdatum - nur aktuelles JAhr und die Zahl interessiert
|
|
if(start_day_obj > holidayloose_date):
|
|
need_days = (calculateHolidays(user, start_day_obj, end_day_obj, start_half, end_half))*(-1)
|
|
holiday_thisyear = yeardata.days - yeardata.days_inuse - need_days
|
|
else:
|
|
need_days = (calculateHolidays(user, start_day_obj, end_day_obj, start_half, end_half))*(-1)
|
|
# Kein Resturlaub
|
|
if(yeardata.restdays == 0.0):
|
|
holiday_thisyear = yeardata.days - yeardata.days_inuse - need_days
|
|
# Resturlaub vorhanden, berechne mit Resturlaub
|
|
else:
|
|
holiday_lastyear = yeardata.restdays
|
|
holiday_thisyear = yeardata.days - yeardata.days_inuse
|
|
temp_holiday = holiday_lastyear - need_days
|
|
if(temp_holiday < 0):
|
|
holiday_lastyear = 0
|
|
holiday_thisyear = yeardata.days - yeardata.days_inuse + temp_holiday
|
|
need_days = [temp_holiday, holiday_thisyear, False]
|
|
else:
|
|
holiday_lastyear = yeardata.restdays - need_days
|
|
need_days = [temp_holiday, holiday_lastyear, False]
|
|
# Urlaub geht über das nächstes Jahr hinweg
|
|
else:
|
|
two_years = True
|
|
holiday_lastyear = yeardata.restdays
|
|
date_splitter = datetime.date(end_day_obj.year, 1, 1)
|
|
|
|
need_days_this = (calculateHolidays(user, start_day_obj, date_splitter, start_half, False))*(-1)
|
|
|
|
need_days_next = (calculateHolidays(user, date_splitter, end_day_obj, False, end_half))*(-1)
|
|
|
|
need_days = (calculateHolidays(user, start_day_obj, date_splitter, start_half, False))*(-1) + (calculateHolidays(user, date_splitter, end_day_obj, False, end_half))*(-1)
|
|
holiday_thisyear = yeardata.days - yeardata.days_inuse - need_days_this
|
|
days_nextyear_normal = 0
|
|
days_nextyear_rest = 0
|
|
# Urlaub nächstes Jahr MIT und OHNE Rest
|
|
if(holiday_nextyear_rest == 0.0):
|
|
holiday_nextyear = holiday_nextyear - (calculateHolidays(user, date_splitter, end_day_obj, False, end_half))*(-1)
|
|
else:
|
|
temprest = holiday_nextyear_rest - need_days_next
|
|
# Rest reicht!
|
|
if(temprest >= 0):
|
|
holiday_nextyear_rest = temprest
|
|
days_nextyear_normal = 0
|
|
days_nextyear_rest = need_days_next
|
|
# Rest reicht nicht
|
|
else:
|
|
holiday_nextyear_rest = 0
|
|
holiday_nextyear += temprest
|
|
days_nextyear_rest = need_days_next + temprest
|
|
days_nextyear_normal = temprest * -1
|
|
|
|
# TAGE NORMAL, TAGE NEXT NORMAL, TRUE für 2jahre, TAGE NEXT REST
|
|
need_days = [need_days_this, days_nextyear_normal, True, days_nextyear_rest]
|
|
|
|
data = [ holiday_thisyear, holiday_lastyear, holiday_nextyear, need_days ]
|
|
return data
|
|
|
|
|
|
def calculateHolidays(user, start, end, start_half, end_half):
|
|
restdays = 0
|
|
allfreedays = FreeDays.objects.filter(agency=user.profile.agency)
|
|
if(end == start):
|
|
if(start_half):
|
|
return restdays - 0.5
|
|
else:
|
|
return restdays - 1
|
|
else:
|
|
if(end < start):
|
|
return False
|
|
else:
|
|
counter = 0
|
|
if(start_half):
|
|
counter -= 0.5
|
|
if(end_half):
|
|
counter -= 0.5
|
|
|
|
weekdays = []
|
|
freedaycounter = 0
|
|
for dt in daterange(start, end):
|
|
day_found = False
|
|
if dt.isoweekday() not in weekdays:
|
|
counter += 1
|
|
for freeday in allfreedays.all():
|
|
if(dt == freeday.day):
|
|
freedaycounter += 1
|
|
day_found = True
|
|
if day_found == False:
|
|
if(dt.isoweekday() == 1):
|
|
if user.usertime.wd_mo == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 2):
|
|
if user.usertime.wd_tu == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 3):
|
|
if user.usertime.wd_we == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 4):
|
|
if user.usertime.wd_th == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 5):
|
|
if user.usertime.wd_fr == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 6):
|
|
if user.usertime.wd_sa == 0.0:
|
|
freedaycounter += 1
|
|
elif(dt.isoweekday() == 7):
|
|
if user.usertime.wd_so == 0.0:
|
|
freedaycounter += 1
|
|
|
|
return restdays - counter + freedaycounter
|
|
|
|
# Gibt die Woche als Wochentage zurück
|
|
def daterange(date1, date2):
|
|
for n in range(int ((date2 - date1).days)+1):
|
|
yield date1 + timedelta(n)
|
|
|
|
''' BERECHNUNG URLAUBSTAGE USW ENDE '''
|
|
|
|
|
|
def randomStringNum(stringLength=20):
|
|
"""Generate a random string of fixed length """
|
|
lettersAndNumbers = string.ascii_lowercase + string.digits + string.ascii_uppercase
|
|
return ''.join(random.choice(lettersAndNumbers) for i in range(stringLength))
|
|
|
|
|
|
def loadingFreeDays(plz, year):
|
|
# Getting land
|
|
file_path = os.path.join(settings.STATIC_ROOT, 'users/extra/plz_short.csv')
|
|
|
|
land = False
|
|
|
|
with open(file_path, 'rt') as csvfile:
|
|
filecsv = csv.reader(csvfile, delimiter=';')
|
|
for row in filecsv:
|
|
|
|
if str(row[1]) == str(plz):
|
|
land = row[6]
|
|
break;
|
|
|
|
|
|
|
|
if(land != False):
|
|
URL = "https://feiertage-api.de/api/"
|
|
PARAMS = {'jahr':year,'nur_land':land}
|
|
r = requests.get(url = URL, params = PARAMS)
|
|
return r.json()
|
|
else:
|
|
return False
|
|
|
|
|
|
def loadingFreeDaysMulti(plz, year, onlyland):
|
|
# Getting land
|
|
file_path = os.path.join(settings.STATIC_ROOT, 'users/extra/plz_short.csv')
|
|
|
|
if(onlyland == False):
|
|
|
|
land = False
|
|
|
|
with open(file_path, 'rt') as csvfile:
|
|
filecsv = csv.reader(csvfile, delimiter=';')
|
|
for row in filecsv:
|
|
|
|
if str(row[1]) == str(plz):
|
|
land = row[6]
|
|
break;
|
|
|
|
URL = "https://feiertage-api.de/api/"
|
|
PARAMS = {'jahr':year,'nur_land':land}
|
|
r = requests.get(url = URL, params = PARAMS)
|
|
return r.json()
|
|
elif(onlyland == True):
|
|
URL = "https://feiertage-api.de/api/"
|
|
PARAMS = {'jahr':year,'nur_daten':1}
|
|
r = requests.get(url = URL, params = PARAMS)
|
|
return r.json()
|
|
else:
|
|
return False
|
|
|
|
'''
|
|
UserProfileUpdate
|
|
|
|
unterscheidet zwischen newuser=0 --> PROFIL AKTUALISIEREN
|
|
und newuser=1 --> PROFIL Neu speichern
|
|
|
|
'''
|
|
@login_required
|
|
def UserProfileUpdate(request, pk, newuser=0):
|
|
usertochange = User.objects.get(pk=pk)
|
|
user_fullname = usertochange.first_name + " " + usertochange.last_name
|
|
parentuser = ""
|
|
if(usertochange.profile.parent != None):
|
|
parentuser = usertochange.profile.parent.pk
|
|
|
|
if request.method == 'POST':
|
|
if 'image' in request.FILES:
|
|
usertochange.profile.image = request.FILES['image']
|
|
formtosave = False
|
|
|
|
if(request.POST["form_type"] == "profileform"):
|
|
|
|
formtosave = UserProfileForm(request.POST, instance=usertochange.profile)
|
|
|
|
if formtosave.is_valid():
|
|
try:
|
|
usertochange.profile.parent = User.objects.get(pk=request.POST['usertoparent'], profile__agency=request.user.profile.agency)
|
|
usertochange.save()
|
|
except Exception as e:
|
|
usertochange.profile.parent = None
|
|
usertochange.save()
|
|
|
|
formtosave.save()
|
|
messages.success(request, f'Profil gespeichert!')
|
|
return redirect('dasettings')
|
|
else:
|
|
messages.success(request, f'Fehlerhafte Eingabe!')
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'first_name' : usertochange.first_name,
|
|
'last_name' : usertochange.last_name,
|
|
'usertime_form' : UserTimeForm(instance=UserTime.objects.get(user=usertochange)),
|
|
'user_years' : UserYearAbsenceInfo.objects.filter(user=usertochange),
|
|
'newuser' : newuser,
|
|
'usertochangefull' : usertochange,
|
|
'vieweduser' : usertochange.pk,
|
|
'parentuser' : parentuser,
|
|
'mail' : usertochange.email,
|
|
'imagelink' : usertochange.profile.get_photo_url,
|
|
'profileform' : UserProfileForm(instance=usertochange.profile),
|
|
'usertoparent' : User.objects.filter(profile__agency__pk=usertochange.profile.agency.pk, profile__visible=True)
|
|
}
|
|
return render(request, 'dasettings/user_usprof.html', context)
|
|
elif(request.POST["form_type"] == "contract"):
|
|
|
|
formtosave = UserTimeForm(request.POST, instance=UserTime.objects.get(user=usertochange))
|
|
if(formtosave.is_valid()):
|
|
# CHECK IF HOLIDAYS_LOOSE IS CORRECT
|
|
if(not re.match(r"^([1-9]{1}|0[0-9]{1}|1[0-9]{1}|2[0-9]{1}|3[0-1]{1}).([1-9]{1}|0[0-9]{1}|1[0-2]{1}).$", formtosave.cleaned_data["loose_holidedate"])):
|
|
messages.success(request, f'Fehlerhafte Eingabe! Das Verfallsdatum der Urlaubstage ist ungültig oder das Format wurde nicht beachtet (TAG.MONAT.).')
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'first_name' : usertochange.first_name,
|
|
'last_name' : usertochange.last_name,
|
|
'usertime_form' : UserTimeForm(instance=UserTime.objects.get(user=usertochange)),
|
|
'user_years' : UserYearAbsenceInfo.objects.filter(user=usertochange),
|
|
'newuser' : newuser,
|
|
'usertochangefull' : usertochange,
|
|
'vieweduser' : usertochange.pk,
|
|
'parentuser' : parentuser,
|
|
'mail' : usertochange.email,
|
|
'imagelink' : usertochange.profile.get_photo_url,
|
|
'profileform' : UserProfileForm(instance=usertochange.profile),
|
|
'usertoparent' : User.objects.filter(profile__agency__pk=usertochange.profile.agency.pk, profile__visible=True)
|
|
}
|
|
return render(request, 'dasettings/user_usprof.html', context)
|
|
else:
|
|
# TRY TO CREATE DATE
|
|
date = formtosave.cleaned_data["loose_holidedate"].split(".")
|
|
try:
|
|
datetime.date(int(2020), int(date[1]), int(date[0]))
|
|
messages.success(request, f'Vertragsdaten gespeichert!')
|
|
formtosave.save()
|
|
return redirect('dasettings')
|
|
except:
|
|
messages.success(request, f'Fehlerhafte Eingabe! Das Verfallsdatum der Urlaubstage ist ungültig!')
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'first_name' : usertochange.first_name,
|
|
'last_name' : usertochange.last_name,
|
|
'usertime_form' : UserTimeForm(instance=UserTime.objects.get(user=usertochange)),
|
|
'user_years' : UserYearAbsenceInfo.objects.filter(user=usertochange),
|
|
'newuser' : newuser,
|
|
'vieweduser' : usertochange.pk,
|
|
'parentuser' : parentuser,
|
|
'usertochangefull' : usertochange,
|
|
'mail' : usertochange.email,
|
|
'imagelink' : usertochange.profile.get_photo_url,
|
|
'profileform' : UserProfileForm(instance=usertochange.profile),
|
|
'usertoparent' : User.objects.filter(profile__agency__pk=usertochange.profile.agency.pk, profile__visible=True)
|
|
}
|
|
return render(request, 'dasettings/user_usprof.html', context)
|
|
else:
|
|
messages.success(request, f'Fehlerhafte Eingabe! Das Verfallsdatum muss im Format TAG.MONAT. sein und existieren!')
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'usertochangefull' : usertochange,
|
|
'user_fullname' : user_fullname,
|
|
'first_name' : usertochange.first_name,
|
|
'last_name' : usertochange.last_name,
|
|
'usertime_form' : UserTimeForm(instance=UserTime.objects.get(user=usertochange)),
|
|
'user_years' : UserYearAbsenceInfo.objects.filter(user=usertochange),
|
|
'newuser' : newuser,
|
|
'vieweduser' : usertochange.pk,
|
|
'parentuser' : parentuser,
|
|
'mail' : usertochange.email,
|
|
'imagelink' : usertochange.profile.get_photo_url,
|
|
'profileform' : UserProfileForm(instance=usertochange.profile),
|
|
'usertoparent' : User.objects.filter(profile__agency__pk=usertochange.profile.agency.pk, profile__visible=True)
|
|
}
|
|
return render(request, 'dasettings/user_usprof.html', context)
|
|
|
|
else:
|
|
usertime = ""
|
|
try:
|
|
usertime = UserTimeForm(instance=UserTime.objects.get(user=usertochange))
|
|
except:
|
|
usertime = UserTime(user=usertochange)
|
|
usertime.save()
|
|
usertime = UserTimeForm(instance=UserTime.objects.get(user=usertochange))
|
|
|
|
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'usertime_form' : UserTimeForm(instance=UserTime.objects.get(user=usertochange)),
|
|
'user_years' : UserYearAbsenceInfo.objects.filter(user=usertochange),
|
|
'first_name' : usertochange.first_name,
|
|
'last_name' : usertochange.last_name,
|
|
'newuser' : newuser,
|
|
'mail' : usertochange.email,
|
|
'vieweduser' : usertochange.pk,
|
|
'usertochangefull' : usertochange,
|
|
'imagelink' : usertochange.profile.get_photo_url,
|
|
'profileform' : UserProfileForm(instance=usertochange.profile),
|
|
'parentuser' : parentuser,
|
|
'usertoparent' : User.objects.filter(profile__agency__pk=usertochange.profile.agency.pk, profile__visible=True),
|
|
'agencygroups' : AgencyGroup.objects.filter(agency__pk=usertochange.profile.agency.pk).order_by("agencygroupname")
|
|
}
|
|
return render(request, 'dasettings/user_usprof.html', context)
|
|
|
|
# View zur Veränderung der Stammdaten des Benutzers
|
|
@login_required
|
|
def UserChangeMain(request, pk):
|
|
usertochange = User.objects.get(pk=pk, profile__agency=request.user.profile.agency)
|
|
user_fullname = usertochange.first_name + " " + usertochange.last_name
|
|
if request.method == 'POST':
|
|
formtosave = UserNewUserForm(request.POST, instance=usertochange)
|
|
if formtosave.is_valid():
|
|
formtosave.save()
|
|
formtosave.save()
|
|
messages.success(request, f'Stammdaten aktualisiert!')
|
|
return redirect('dasettings')
|
|
else:
|
|
messages.success(request, f'Fehlerhafte Eingabe! Mailadresse bereits vorhanden!')
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'userform' : UserNewUserForm(request.POST, instance=usertochange),
|
|
}
|
|
return render(request, 'dasettings/user_changemaindata.html', context)
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'user_fullname' : user_fullname,
|
|
'userform' : UserNewUserForm(instance=usertochange),
|
|
}
|
|
return render(request, 'dasettings/user_changemaindata.html', context)
|
|
|
|
# Method for first User-Creation-Step - NEW USER
|
|
@login_required
|
|
def NewUserFirstStep(request):
|
|
context = {
|
|
'active_link' : 'dasettings'
|
|
}
|
|
if request.method == 'POST':
|
|
newuserform = UserNewUserForm(request.POST)
|
|
if newuserform.is_valid():
|
|
#if(request.POST.get("sendmailnewuser")):
|
|
# msg_html = render_to_string('users/newusers_email.html', {'username': newuserform.cleaned_data.get('first_name') + " " + newuserform.cleaned_data.get('last_name')})
|
|
# send_mail(request.user.profile.agency.name + ' Account', 'Hallo ' + newuserform.cleaned_data.get('first_name') + ' ' + newuserform.cleaned_data.get('last_name') + '! Bitte setzen sie sich auf https://app.digitale-agentur.com/password-reset/ ein Passwort.','noreply@digitale-agentur.com',[newuserform.cleaned_data.get('email')],html_message=msg_html,fail_silently=True)
|
|
newuser = newuserform.save(commit=False)
|
|
newuser.username = newuser.email
|
|
newprofile = Profile(agency=request.user.profile.agency, parent=None)
|
|
newprofile.save()
|
|
newuser.profile = newprofile
|
|
newuser.save()
|
|
|
|
# NEW USER IN DJANGO - ADD USER TO NC
|
|
# Data for the new User
|
|
try:
|
|
data_nc = {
|
|
"userid": newuser.username,
|
|
"password": "",
|
|
"displayName": newuser.first_name + " " + newuser.last_name,
|
|
"email": newuser.email,
|
|
"groups[]": "agencymaingroupid_" + str(request.user.profile.agency.pk)
|
|
}
|
|
|
|
headers = {
|
|
'Accept' : 'application/json',
|
|
'Access-Control-Allow-Headers' : 'OCS-APIRequest',
|
|
'OCS-APIRequest' : 'true'
|
|
}
|
|
|
|
# Request for adding the new User
|
|
r = requests.post(settings.NEXTCLOUD_URL + "ocs/v1.php/cloud/users", data=data_nc, headers=headers, auth=(settings.NEXTCLOUD_USER_API, settings.NEXTCLOUD_PW_API))
|
|
except:
|
|
pass
|
|
|
|
# USERTIME
|
|
user_time = UserTime(user=newuser)
|
|
user_time.save()
|
|
# USER NOTIFICATIONS
|
|
#user_notifications = UserNotifications.objects.create(user=newuser)
|
|
#user_notifications.save()
|
|
|
|
newuser.usernotifications = user_notifications
|
|
newuser.usertime = user_time
|
|
|
|
|
|
newuser_id = newuser.id
|
|
messages.success(request, f'Benutzer angelegt!')
|
|
today = date.today()
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=newuser, year=today.year).save()
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=newuser, year=today.year+1).save()
|
|
UserYearAbsenceInfo(agency=request.user.profile.agency, user=newuser, year=today.year+2).save()
|
|
|
|
getadmingroup = AgencyGroup.objects.filter(savefordel=True, is_admin=False, agency=request.user.profile.agency).exclude(agencygroupname="Notfallhilfe")
|
|
for g in getadmingroup:
|
|
g.group.user_set.add(newuser)
|
|
return redirect('/dasettings/usprof/'+str(newuser_id)+'/1')
|
|
else:
|
|
messages.success(request, f'Daten falsch eingegeben!')
|
|
context['newuserform'] = UserNewUserForm(request.POST)
|
|
return render(request, 'dasettings/user_newuser_step1.html', context)
|
|
|
|
# Returning the data from database for normal-loading Settings
|
|
else:
|
|
newuserform = UserNewUserForm()
|
|
context.update({'newuserform' : newuserform})
|
|
return render(request, 'dasettings/user_newuser_step1.html', context)
|
|
|
|
|
|
# NEUER AGENTURVERBUND
|
|
@login_required
|
|
def AddAgencyNetwork(request):
|
|
if request.method == 'POST':
|
|
newagn = AgencyNetworkForm(request.POST)
|
|
if(newagn.is_valid()):
|
|
newagn_object = AgencyNetwork(name=newagn.cleaned_data.get("name"), publicjoin=newagn.cleaned_data.get("publicjoin"), creator=request.user, creator_agency=request.user.profile.agency, networkid=randomString(20))
|
|
newagn_object.save()
|
|
newagn_object.adminagencys.add(request.user.profile.agency)
|
|
messages.success(request, f'Agenturverbund ' + newagn_object.name + ' angelegt!')
|
|
return redirect('dasettings')
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'form' : AgencyNetworkForm(),
|
|
}
|
|
return render(request, 'dasettings/addagencynetwork_content.html', context)
|
|
|
|
@login_required
|
|
def UpdateAgencyNetwork(request, pk):
|
|
if request.method == 'POST':
|
|
agn = AgencyNetwork.objects.get(pk=pk)
|
|
formdata = AgencyNetworkForm(request.POST)
|
|
if(formdata.is_valid()):
|
|
agn.name = formdata.cleaned_data.get("name")
|
|
agn.publicjoin= formdata.cleaned_data.get("publicjoin")
|
|
agn.save()
|
|
#newagn_object.adminagencys.add(request.user.profile.agency)
|
|
messages.success(request, f'Agenturverbund ' + agn.name + ' aktualisiert!')
|
|
return redirect('dasettings')
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'form' : AgencyNetworkForm(instance=AgencyNetwork.objects.get(pk=pk)),
|
|
}
|
|
return render(request, 'dasettings/addagencynetwork_content.html', context)
|
|
|
|
@login_required
|
|
def DelAgencyNetwork(request, pk):
|
|
agn = AgencyNetwork.objects.get(pk=pk)
|
|
if request.method == 'POST':
|
|
if request.user.profile.agency in agn.adminagencys.all():
|
|
agn.delete()
|
|
messages.success(request, f'Agenturverbund erfolgreich gelöscht!')
|
|
return redirect('dasettings')
|
|
else:
|
|
messages.success(request, f'Sie dürfen diesen Agenturverbund nicht löschen!')
|
|
return redirect('dasettings')
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'agn' : agn
|
|
}
|
|
return render(request, 'dasettings/delagencynetwork_content.html', context)
|
|
|
|
@login_required
|
|
def AddMyAgencyToAgn(request, networkid):
|
|
agn = AgencyNetwork.objects.filter(networkid=networkid)
|
|
|
|
if len(agn) == 0:
|
|
messages.info(request, f'Agenturverbund nicht gefunden!')
|
|
return redirect('dasettings')
|
|
else:
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'agn' : list(agn)[0]
|
|
}
|
|
return render(request, 'dasettings/joinagn_first.html', context)
|
|
|
|
|
|
def IsAgencyInAgNetwork(agencyid, agnetworkid):
|
|
is_in = False
|
|
|
|
agn = AgencyNetwork.objects.get(pk=agnetworkid)
|
|
agency = Agency.objects.get(pk=agencyid)
|
|
|
|
if agency in agn.adminagencys.all():
|
|
is_in = True
|
|
|
|
if agency in agn.members.all():
|
|
is_in = True
|
|
|
|
if agency in agn.sharemembers.all():
|
|
is_in = True
|
|
|
|
return is_in
|
|
|
|
|
|
@login_required
|
|
def JoinAGN(request, pk):
|
|
if IsAgencyInAgNetwork(request.user.profile.agency.pk, pk):
|
|
messages.success(request, f'Ihre Agentur ist bereits in diesem Verbund!')
|
|
else:
|
|
agn = AgencyNetwork.objects.get(pk=pk)
|
|
if(agn.publicjoin):
|
|
messages.success(request, f'Verbund erfolgreich beigetreten!')
|
|
agn.members.add(request.user.profile.agency)
|
|
|
|
# Benachrichtigung senden, dass eine neue Agentur dem Verbund beitreten will. DIe Info geht an alle administrativen Agenturen.
|
|
for adminagencys in agn.adminagencys.all():
|
|
usersofagency = Users.objects.filter(profile__agency=adminagencys)
|
|
|
|
for u in usersofagency:
|
|
if u.has_perm('users.agencynetwork') and u.has_perm('users.agencynetwork'):
|
|
if u.usernotifications.agn_own_change_mail:
|
|
notificationtext = " eine neue Agentur ist dem Verbund " + agn.name + " beigetreten."
|
|
sendMailNoti(notificationtext, u)
|
|
|
|
if u.usernotifications.agn_own_change_push:
|
|
newnotification = UserNotification(touser=u, notificationtext=" eine neue Agentur ist dem Verbund " + agn.name + " beigetreten.", 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 | Eine neue Agentur ist dem Verbund " + agn.name + " beigetreten."})
|
|
else:
|
|
|
|
# STATUS
|
|
# 1 WANTED AG ASKED TO TARGET NETWORK
|
|
agnp = AgencyNetworkPreperation(target_network=AgencyNetwork.objects.get(pk=pk), wanted_agency=request.user.profile.agency, status=1)
|
|
agnp.save()
|
|
|
|
# Benachrichtigung senden, dass eine neue Agentur dem Verbund beitreten will. DIe Info geht an alle administrativen Agenturen.
|
|
for adminagencys in agn.adminagencys.all():
|
|
usersofagency = Users.objects.filter(profile__agency=adminagencys)
|
|
|
|
for u in usersofagency:
|
|
if u.has_perm('users.agencynetwork') and u.has_perm('users.agencynetwork'):
|
|
if u.usernotifications.agn_own_change_mail:
|
|
notificationtext = " eine neue Agentur möchte dem Verbund " + agn.name + " beitreten."
|
|
sendMailNoti(notificationtext, u)
|
|
|
|
if u.usernotifications.agn_own_change_push:
|
|
newnotification = UserNotification(touser=u, notificationtext=" eine neue Agentur möchte dem Verbund " + agn.name + " beitreten.", 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 | Eine neue Agentur möchte dem Verbund " + agn.name + " beitreten."})
|
|
|
|
messages.success(request, f'Ihre Anfrage zum Beitritt wurde versendet. Sie erhalten eine Information, wenn die Anfrage angenommen wurde!')
|
|
|
|
|
|
return redirect('dasettings')
|
|
|
|
@login_required
|
|
def ManageAgInAgn(request, pk):
|
|
agn = AgencyNetwork.objects.filter(pk=pk)
|
|
|
|
if len(agn) == 0:
|
|
messages.info(request, f'Agenturverband nicht gefunden!')
|
|
return redirect('dasettings')
|
|
else:
|
|
|
|
network = list(agn)[0]
|
|
|
|
allagofagn = []
|
|
for a in network.members.all():
|
|
allagofagn.append(a)
|
|
|
|
for a in network.sharemembers.all():
|
|
allagofagn.append(a)
|
|
|
|
for a in network.adminagencys.all():
|
|
allagofagn.append(a)
|
|
|
|
context = {
|
|
'active_link' : 'dasettings',
|
|
'agn' : list(agn)[0],
|
|
'outstanding': AgencyNetworkPreperation.objects.filter(target_network=list(agn)[0]) ,
|
|
'allagofagn' : allagofagn
|
|
}
|
|
return render(request, 'dasettings/agencynetwork_agmanagement_content.html', context)
|
|
|
|
@login_required
|
|
def AddAgToNetwork(request, network, targetag, aginvpk):
|
|
|
|
if IsAgencyInAgNetwork(Agency.objects.get(pk=targetag).pk, network):
|
|
messages.info(request, f'Sie sind bereits im Agenturverbund!')
|
|
return redirect('dasettings')
|
|
else:
|
|
|
|
messages.info(request, f'Einladung angenommen!')
|
|
agn = AgencyNetwork.objects.get(pk=network)
|
|
|
|
agn.members.add(Agency.objects.get(pk=targetag))
|
|
AgencyNetworkPreperation.objects.get(pk=aginvpk).delete()
|
|
|
|
return redirect('managagn', network)
|
|
|
|
@login_required
|
|
def DelAgInv(request, pk):
|
|
AgencyNetworkPreperation.objects.get(pk=pk).delete()
|
|
messages.info(request, f'Einladung abgelehnt!')
|
|
return redirect('dasettings')
|
|
|
|
@login_required
|
|
def DelFromAgn(request, agn, ag):
|
|
return redirect('managagn', agn)
|
|
|
|
@login_required
|
|
def AgencyNetworkAjaxSettings(request):
|
|
success = False
|
|
data = {}
|
|
if request.method == 'GET' and request.GET['action'] == "remove_ag_from_agn":
|
|
agency = Agency.objects.get(pk=request.GET['agid'])
|
|
agencynetwork = AgencyNetwork.objects.get(pk=request.GET['agnid'])
|
|
|
|
if(agency != None and agencynetwork != None):
|
|
agencynetwork.members.remove(agency)
|
|
agencynetwork.adminagencys.remove(agency)
|
|
agencynetwork.sharemembers.remove(agency)
|
|
success = True
|
|
|
|
# Benachrichtigung senden, dass eine neue Agentur dem Verbund beitreten will. DIe Info geht an alle administrativen Agenturen.
|
|
usersofagency = Users.objects.filter(profile__agency=agency)
|
|
for u in usersofagency:
|
|
if u.has_perm('users.agencynetwork') and u.has_perm('users.agencynetwork'):
|
|
if u.usernotifications.agn_other_change_mail:
|
|
notificationtext = " ihre Agentur wurde aus dem Verbund " + agencynetwork.name + " entfernt."
|
|
sendMailNoti(notificationtext, u)
|
|
|
|
if u.usernotifications.agn_other_change_push:
|
|
newnotification = UserNotification(touser=u, notificationtext=" ihre Agentur wurde aus dem Verbund " + agencynetwork.name + " entfernt.", 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 | Ihre Agentur wurde aus dem Verbund " + agencynetwork.name + " entfernt."})
|
|
|
|
elif request.method == 'GET' and request.GET['action'] == "removeinv":
|
|
AgencyNetworkPreperation.objects.get(pk=request.GET['agn_inv']).delete()
|
|
success = True
|
|
elif request.method == 'GET' and request.GET['action'] == "changeagrights":
|
|
agency = Agency.objects.get(pk=request.GET['agency'])
|
|
agn = AgencyNetwork.objects.get(pk=request.GET['agnid'])
|
|
if(agency != None and agn != None):
|
|
agn.members.remove(agency)
|
|
agn.adminagencys.remove(agency)
|
|
agn.sharemembers.remove(agency)
|
|
if (request.GET['newstatus'] == "0"):
|
|
agn.members.add(agency)
|
|
elif (request.GET['newstatus'] == "1"):
|
|
agn.sharemembers.add(agency)
|
|
elif (request.GET['newstatus'] == "2"):
|
|
agn.adminagencys.add(agency)
|
|
success = True
|
|
|
|
usersofagency = Users.objects.filter(profile__agency=agency)
|
|
for u in usersofagency:
|
|
if u.has_perm('users.agencynetwork') and u.has_perm('users.agencynetwork'):
|
|
if u.usernotifications.agn_other_change_mail:
|
|
notificationtext = " ihre Agentur hat im Verbund " + agn.name + " andere Rechte erhalten."
|
|
sendMailNoti(notificationtext, u)
|
|
|
|
if u.usernotifications.agn_other_change_push:
|
|
newnotification = UserNotification(touser=u, notificationtext=" ihre Agentur hat im Verbund " + agn.name + " andere Rechte erhalten.", 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 | Ihre Agentur hat im Verbund " + agn.name + " andere Rechte erhalten."})
|
|
else:
|
|
success = False
|
|
return JsonResponse(data)
|
|
|
|
@login_required
|
|
def ModSettingsOrga(request):
|
|
if request.method == 'GET' and request.user.has_perm("users.modulesconfig"):
|
|
if(request.GET['dynorga'] == "true"):
|
|
ag = request.user.profile.agency
|
|
ag.dynamicprofile = True
|
|
ag.save()
|
|
else:
|
|
ag = request.user.profile.agency
|
|
ag.dynamicprofile = False
|
|
ag.save()
|
|
return JsonResponse({})
|
|
else:
|
|
return JsonResponse({})
|
|
|
|
|
|
@login_required
|
|
def ModSettingsTm(request):
|
|
return JsonResponse({})
|
|
'''
|
|
if request.method == 'GET' and request.user.has_perm("users.modulesconfig"):
|
|
if(request.GET['aze'] == "true"):
|
|
ag = request.user.profile.agency
|
|
ag.module_timemanagement_ze = True
|
|
ag.save()
|
|
else:
|
|
ag = request.user.profile.agency
|
|
ag.module_timemanagement_ze = False
|
|
ag.save()
|
|
return JsonResponse({})
|
|
else:
|
|
return JsonResponse({})
|
|
'''
|
|
|
|
########## ABRECHNUNG ##########
|
|
class BillMailUpdate(UpdateView):
|
|
model = Agency
|
|
success_url = reverse_lazy('dasettings')
|
|
form_class = AgencyBillMail
|
|
template_name = "dasettings/dasettings_billmail.html"
|
|
|
|
def form_valid(self, form):
|
|
messages.success(self.request, f"E-Mailadresse erfolgreich aktualisiert!")
|
|
return super().form_valid(form)
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(**kwargs)
|
|
context.update({'active_link' : 'dasettings'})
|
|
return context
|
|
'''
|
|
def getBill(request, billid):
|
|
if(request.method == "GET"):
|
|
Bill = AgencyBills.objects.get(billid=billid)
|
|
|
|
response = HttpResponse(content_type='text/pdf')
|
|
response['Content-Disposition'] = 'attachment; filename="RechnungPLATZHALTER.pdf"'
|
|
|
|
|
|
return response
|
|
else:
|
|
pass
|
|
'''
|
|
class BillPlanEnd(UpdateView):
|
|
model = Agency
|
|
success_url = reverse_lazy('dasettings')
|
|
form_class = AgencyEndBillPlan
|
|
template_name = "dasettings/bill_removepayplan.html"
|
|
|
|
def form_valid(self, form):
|
|
self.object.paymentplan = 0
|
|
messages.success(self.request, f"Abonnement gekündigt!")
|
|
|
|
return super().form_valid(form)
|
|
|
|
from dateutil.relativedelta import *
|
|
class BillPlanUpdate(UpdateView):
|
|
model = Agency
|
|
success_url = reverse_lazy('dasettings')
|
|
form_class = AgencyBillPlan
|
|
template_name = "dasettings/dasettings_billplan.html"
|
|
|
|
# LexOffice Verbindung
|
|
def form_valid(self, form):
|
|
# Form einmal speichern, damit die Adressdaten usw. übernommen werden
|
|
form.save()
|
|
agency = self.request.user.profile.agency
|
|
month = agency.registerdate
|
|
|
|
# Notfallhilfe soll mitbestellt werden
|
|
if form.cleaned_data.get("recoverdir") == True:
|
|
rd = RegNotfallhilfe()
|
|
rd.mail = form.cleaned_data.get('agency_email')
|
|
rd.name = form.cleaned_data.get('inhaber')
|
|
rd.persnumber = "n.v."
|
|
rd.mitgliedsnummer = form.cleaned_data.get("vve")
|
|
rd.plz = form.cleaned_data.get("plz")
|
|
rd.stadt = form.cleaned_data.get("city")
|
|
rd.street = form.cleaned_data.get("street")
|
|
rd.data_to_vh = True
|
|
rd.rabatt = True
|
|
rd.save()
|
|
|
|
# Wenn die Agentur noch KEINE Lexoffice-ID hat, dann ist der Freimonat noch nicht durch.
|
|
if agency.lexofficeid == "":
|
|
month = month + relativedelta(months=1)
|
|
else:
|
|
month = AgencyBills.objects.filter(agency=self.request.user.profile.agency).order_by("-end")[0].end
|
|
|
|
next_month = month + relativedelta(months=1)
|
|
|
|
voucher_date = next_month.strftime("%Y-%m-%d")
|
|
|
|
# USERCOUNT BERECHNEN
|
|
usercount = len(User.objects.filter(profile__agency=agency))
|
|
|
|
if(usercount < 4):
|
|
usercount = 0
|
|
else:
|
|
usercount = usercount - 3
|
|
|
|
# HEADERS CURL
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
plan = 1
|
|
|
|
'''
|
|
start_date = month
|
|
start_date_string = month.strftime("%d.%m.%Y")
|
|
end_date = month + relativedelta(months=1)
|
|
end_date = end_date - relativedelta(days=1)
|
|
end_date_string= end_date.strftime("%d.%m.%Y")
|
|
'''
|
|
start_date = month + relativedelta(days=1)
|
|
start_date_string = start_date.strftime("%d.%m.%Y")
|
|
# Einen Monat weiter und dann wieder einen Tag zurück
|
|
end_date = month + relativedelta(months=1)
|
|
#end_date = end_date - relativedelta(days=1)
|
|
end_date_string= end_date.strftime("%d.%m.%Y")
|
|
|
|
voucher_date_today = date.today().strftime("%Y-%m-%d")
|
|
# TASK: Was passiert bei Änderungen der Agenturdaten?
|
|
|
|
# DataJSON
|
|
monthword = "Monate"
|
|
if form.cleaned_data['paymentplan'] == "1":
|
|
monthword = "Monat"
|
|
|
|
lexdata = {
|
|
"voucherDate": voucher_date_today + "T00:00:00.000+00:00",
|
|
"address" : {
|
|
"name" : agency.name,
|
|
"street": agency.street,
|
|
"zip": agency.plz,
|
|
"city": agency.city,
|
|
"countryCode" : "DE"
|
|
},
|
|
"totalPrice" : {
|
|
"currency" : "EUR",
|
|
},
|
|
"lineItems" : [
|
|
{
|
|
"type" : "custom",
|
|
"name" : "Digitale Agentur: Grundbetrag für " + str(plan) + " " + monthword,
|
|
"quantity" : 1,
|
|
"unitName" : "Stück",
|
|
"description" : "Zeitraum " + start_date_string + " - " + end_date_string,
|
|
"unitPrice" :
|
|
{
|
|
"currency" : "EUR",
|
|
"netAmount" : 21.00,
|
|
"taxRatePercentage" : 19
|
|
},
|
|
},
|
|
{
|
|
"type" : "custom",
|
|
"name" : "Digitale Agentur: Zusätzliche Nutzer",
|
|
"description" : "Zeitraum " + start_date_string + " - " + end_date_string,
|
|
"quantity" : usercount,
|
|
"unitName" : "Stück",
|
|
"unitPrice" :
|
|
{
|
|
"currency" : "EUR",
|
|
"netAmount" : 3,
|
|
"taxRatePercentage" : 19
|
|
},
|
|
}
|
|
],
|
|
"taxConditions": {
|
|
"taxType": "net"
|
|
},
|
|
#"paymentConditions": {
|
|
# "paymentTermLabel": "Bitte zahlen Sie innerhalb von 14 Tagen.",
|
|
# "paymentTermDuration": 14,
|
|
#},
|
|
"shippingConditions": {
|
|
#"shippingDate": voucher_date_today + "T00:00:00.000+00:00",
|
|
"shippingType": "none"
|
|
}
|
|
}
|
|
json_data = json.dumps(lexdata)
|
|
|
|
self.object = form.save(commit=False)
|
|
|
|
|
|
r = requests.post("https://api.lexoffice.io/v1/invoices/?finalize=true", data=json_data, headers=headers)
|
|
# Als ENTWURF Rechnung anlegen
|
|
#r = requests.post("https://api.lexoffice.io/v1/invoices/", data=json_data, headers=headers)
|
|
|
|
if(r.status_code == 201):
|
|
messages.success(self.request, f"Rechnung erstellt!")
|
|
# Response in JSON umwandeln
|
|
response_text = json.loads(r.text)
|
|
# Rechnungsidee speichern
|
|
|
|
|
|
# HEADERS CURL
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
json_data = json.dumps(lexdata)
|
|
newbill_id = response_text["id"]
|
|
|
|
# OrganizationId berechnen, wenn noch nicht gesetzt
|
|
r = requests.get("https://api.lexoffice.io/v1/invoices/" + response_text["id"], data=json_data, headers=headers)
|
|
|
|
response_text = json.loads(r.text)
|
|
if len(agency.lexofficeid) == 0:
|
|
self.object.lexofficeid = response_text["organizationId"]
|
|
|
|
newbill = AgencyBills(agency=agency, lexid=newbill_id, billtype="invoice", billnumber=response_text["voucherNumber"], billstatus=response_text["voucherStatus"], start=start_date, end=end_date, plan=plan, usercount=usercount)
|
|
newbill.save()
|
|
self.object.save()
|
|
|
|
mail_to_send = ""
|
|
if(self.request.user.profile.agency.payment_address == None):
|
|
mail_to_send = self.request.user.profile.agency.agency_email
|
|
else:
|
|
mail_to_send = self.request.user.profile.agency.payment_address
|
|
|
|
msg_html = render_to_string('users/newbill_mail.html', {})
|
|
# BCC Mail with Object - NICHT DEN IMPORT VERGESSEN!!!
|
|
email = EmailMultiAlternatives(
|
|
'Digitale Agentur | Rechnung ' + str(response_text["voucherNumber"]),
|
|
'Sehr geehrte Nutzer, hiermit erhalten Sie eine neue Rechnung für die Digitale Agentur. Ihr Team der Digitalen Agentur',
|
|
'noreply@digitale-agentur.com',
|
|
[mail_to_send],
|
|
['info@digitale-agentur.com'],
|
|
headers={},
|
|
)
|
|
|
|
headers = {
|
|
'Authorization': 'Bearer ' + settings.LEX_API,
|
|
'Content-Type': 'application/json',
|
|
'Accept': 'application/json',
|
|
}
|
|
|
|
lexdata = {
|
|
"renderType" : "pdf"
|
|
}
|
|
|
|
r_final = requests.get("https://api.lexoffice.io/v1/invoices/"+newbill_id+"/document", data=json_data, headers=headers)
|
|
json.loads(r_final.text)
|
|
|
|
base64String = requests.get("https://api.lexoffice.io/v1/files/"+json.loads(r_final.text)["documentFileId"]+"/", data=json_data, headers=headers)
|
|
|
|
content = base64.b64decode(base64String.text)
|
|
|
|
msg_html = render_to_string('users/newbill_mail.html', {})
|
|
email.attach_alternative(msg_html, "text/html")
|
|
email.attach('Rechnung_' + str(response_text["voucherNumber"]) + '.pdf', content, "application/pdf")
|
|
email.send()
|
|
|
|
#send_mail('Digitale Agentur | Rechnung', 'Sehr geehrte Nutzer, es wurde eine Rechnung für Ihre digitale Agentur erstellt. Diese können Sie unter Einstellungen, Abrechnung einsehen.','noreply@digitale-agentur.com',[mail_to_send],html_message=msg_html,fail_silently=True)
|
|
|
|
else:
|
|
messages.warning(self.request, f"Fehlercode "+str(r.status_code)+". Es wurde keine Rechnung erstellt. Bitte wenden Sie sich an den Support!")
|
|
|
|
return super().form_valid(form)
|
|
|
|
|
|
def get_context_data(self, **kwargs):
|
|
context = super().get_context_data(**kwargs)
|
|
|
|
# Rechnungsbegin setzen
|
|
agency = self.request.user.profile.agency
|
|
|
|
|
|
if len(AgencyBills.objects.filter(agency=self.request.user.profile.agency)) == 0:
|
|
month = self.request.user.profile.agency.registerdate + relativedelta(months=1)
|
|
else:
|
|
month = AgencyBills.objects.filter(agency=self.request.user.profile.agency).order_by("-end")[0].end
|
|
|
|
# Wenn die Agentur noch KEINE Lexoffice-ID hat, dann ist der Freimonat noch nicht durch.
|
|
if agency.lexofficeid == "":
|
|
month = month + relativedelta(months=1)
|
|
|
|
|
|
context.update({'active_link' : 'dasettings', 'end' : month})
|
|
|
|
return context
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|