from django.db.models.signals import post_save, pre_delete, m2m_changed, pre_save from django.contrib.auth.models import User, Group from django.dispatch import receiver from .models import Profile, Agency, AgencyGroup, AgencyNetworkPreperation from news.models import News from django.contrib.auth.models import Permission from notificsys.models import UserNotification from django.core.mail import send_mail from django.template.loader import render_to_string from tasks.models import Tasks from cloud.models import DataFile import os from django.conf import settings from django.utils import timezone from standards.models import Standards from django.contrib.auth.signals import user_logged_in from timemanagement.models import Workday, Breaks, AbsenceReason, FreeDays from datetime import date import datetime, json from django.utils import timezone import requests, csv, os from django.templatetags.static import static from django.conf import settings from datetime import date def loadingFreeDays(plz): # 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 row[1] == plz: land = row[6] break; if(land != False): # CALCULATE FREEDAYS AS JSON year = today = date.today().year 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 # CHECK SOMETHING WHEN USER LOGGED IN @receiver(signal=user_logged_in, sender=User) def checkForWorkDays(sender, user, request, **kwargs): today = date.today() wd = Workday.objects.filter(user=user, end=None, start__day__lte=today.day) for d in wd: d.end = datetime.datetime(d.start.year, d.start.month, d.start.day, 23, 59, 00) d.save() for b in d.breaks.all(): if(b.end == None): b.end = datetime.datetime(d.start.year, d.start.month, d.start.day, 23, 59, 00) b.save() # CHECK SOMETHING WHEN USER LOGGED IN @receiver(signal=user_logged_in, sender=User) def checkDefaultAbsenceReasons(sender, user, request, **kwargs): ar = AbsenceReason.objects.filter(agency=user.profile.agency) if(len(ar) == 0): new_ar_holidays = AbsenceReason(agency=user.profile.agency, name="Urlaub", need_confirm=True, need_rep=True, is_holiday=True) new_ar_holidays.save() new_ar_specialholidays = AbsenceReason(agency=user.profile.agency, name="Sonderurlaub", need_confirm=True, need_rep=True, is_holiday=False) new_ar_specialholidays.save() new_ar_ill = AbsenceReason(agency=user.profile.agency, name="Krankheit", need_confirm=False, need_rep=False, is_holiday=False) new_ar_ill.save() new_ar_school = AbsenceReason(agency=user.profile.agency, name="Berufsschule", need_confirm=False, need_rep=False, is_holiday=False) new_ar_school.save() @receiver(signal=user_logged_in, sender=User) def checkAllFreeDaysLoaded(sender, user, request, **kwargs): pass ''' allFreeDays = FreeDays.objects.filter(agency=user.profile.agency, year=date.today().year) # NO DAYS FOR THIS YEAR if(len(allFreeDays) == 0): tempdays = loadingFreeDays(user.profile.agency.plz) for k in tempdays.keys(): tempdate = tempdays[k]["datum"].split("-") FreeDays(agency=user.profile.agency, name=k, day=datetime.datetime(int(tempdate[0]),int(tempdate[1]),int(tempdate[2])), year=date.today().year).save() ''' # Deletes all Notifications added to to delete news @receiver(pre_delete, sender=News) def del_news_notifications(sender, instance, **kwargs): UserNotification.objects.filter(elementid=instance.pk).delete() # SIGNALS FOR USER ''' @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): print(instance) if created: Profile.objects.create(user=instance, agency=instance.agency, parent=instance.parent) #Wenn ein neuer Nutzer angelegt wird und dies der erste der Agentur ist, #erhält dieser automatisch alle verfügbaren Rechte! user_agency = User.objects.filter(profile__agency__pk=instance.agency.pk) if len(user_agency) == 1: tempuser = user_agency[0] temprof = Profile for ele in temprof._meta.permissions: tempperm = Permission.objects.get(codename=ele[0]) tempuser.user_permissions.add(tempperm) #tempuser.profile.func = 'lead' tempuser.save() ''' @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() # SIGNALS FOR GROUPS @receiver(signal=m2m_changed, sender=User.groups.through) def adjust_group_notifications(instance, action, reverse, model, pk_set, using, *args, **kwargs): # IF FALSE NO MAILS WILL BE SEND - IN PRODUCTIVITY CHANGE TO TRUE # GLOBALSENDMAILS = True # GROUPSETTINGS FOR SOME USER WAS CHANGED if isinstance(instance, Group): group_touched = AgencyGroup.objects.get(group=instance) userid = list(pk_set)[0] user_touched = User.objects.get(pk=userid) # PUSH NOTIFICATION FOR GROUOPCHANGES if(user_touched.profile.add_new_group_push): if(action == 'post_remove'): newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt.", notificationtype="groupchanges") newnotification.save() # A USER WAS ADDED TO A GROUP elif(action == 'post_add'): newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt.", notificationtype="groupchanges") newnotification.save() # E-MAILNOTIFICATIONS FOR GROUPCHANGES if(user_touched.profile.add_new_group_mail): notificationtext = "" if(action == 'post_remove'): notificationtext = "Sie wurden aus der Gruppe " + group_touched.agencygroupname + " entfernt." username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user_touched.email], html_message=msg_html, fail_silently=True ) # A USER WAS ADDED TO A GROUP elif(action == 'post_add'): notificationtext = "Sie wurden zur Gruppe " + group_touched.agencygroupname + " hinzugefügt." username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user_touched.email], html_message=msg_html, fail_silently=True ) # SIGNAL FOR STANDARDS POST SAVE @receiver(post_save, sender=Standards) def save_standard(sender, instance, **kwargs): GLOBALSENDMAILS = True # NEW STANDARD AND DIRECT PUBLIC if(kwargs["created"]): usersofagency = User.objects.filter(profile__agency__pk=instance.agency.pk) targeturl = settings.BASE_URL + "standards/standard/" + str(instance.pk) + "/single" if(instance.public): for user in usersofagency: if(user.profile.agency_new_standard_mail): notificationtext = "Neuer Agenturstandard: " + instance.name username = user.first_name + " " + user.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext, 'linktarget' : targeturl}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user.first_name + ' ' + user.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user.email], html_message=msg_html, fail_silently=True ) if(user.profile.agency_new_standard_push): newnotification = UserNotification(touser=user, notificationtext="Neuer Agenturstandard: " + instance.name, notificationtype="newstandard", elementid=instance.pk) newnotification.save() else: for user in usersofagency: if(user.has_perm("users.standardmanager")): newnotification = UserNotification(touser=user, notificationtext="Neuer unveröffentlichter Agenturstandard: " + instance.name, notificationtype="newstandard", elementid=instance.pk) newnotification.save() # SIGNAL FOR NEWS @receiver(post_save, sender=News) def save_news(sender, instance, **kwargs): GLOBALSENDMAILS = True if(kwargs["created"]): usersofagency = User.objects.filter(profile__agency__pk=instance.agency.pk) targeturl = settings.BASE_URL + "news/news/" + str(instance.pk) + "/single" if(instance.go_online_on < timezone.now() and instance.agnotify): for user in usersofagency: if(user.profile.news_mail): notificationtext = "Neue Agenturnews: " + instance.name username = user.first_name + " " + user.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext, 'linktarget' : targeturl}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user.first_name + ' ' + user.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user.email], html_message=msg_html, fail_silently=True ) if(user.profile.news_push): newnotification = UserNotification(touser=user, notificationtext="Neue Agenturnews: " + instance.name, notificationtype="agencynews", elementid=instance.pk) newnotification.save() else: instance.agnotify = False instance.save() # SIGNALS FOR TASK @receiver(signal=m2m_changed, sender=Tasks.usersfield.through) def adjust_group_notifications_task(instance, action, reverse, model, pk_set, using, *args, **kwargs): # IF FALSE NO MAILS WILL BE SEND - IN PRODUCTIVITY CHANGE TO TRUE # GLOBALSENDMAILS = True # A USER WAS TOUCHED ATT HIS TASKS user_touched = User.objects.get(pk=list(pk_set)[0]) taskname = instance.name # PUSH NOTIFICATION FOR GROUOPCHANGES if(user_touched.profile.add_task_push): if(action == 'post_remove'): newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden von der Tätigkeit " + taskname + " entfernt.", notificationtype="taskchange") newnotification.save() # A USER WAS ADDED TO A GROUP elif(action == 'post_add'): newnotification = UserNotification(touser=user_touched, notificationtext="Sie wurden der Tätigkeit " + taskname + " zugeordnet.", notificationtype="taskchange") newnotification.save() # E-MAILNOTIFICATIONS FOR GROUPCHANGES if(user_touched.profile.add_task_mail): notificationtext = "" if(action == 'post_remove'): notificationtext = "Sie wurden von der Tätigkeit " + taskname + " entfernt." username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user_touched.email], html_message=msg_html, fail_silently=True ) # A USER WAS ADDED TO A GROUP elif(action == 'post_add'): notificationtext = "Sie wurden der Tätigkeit " + taskname + " zugeordnet." username = user_touched.first_name + " " + user_touched.last_name msg_html = render_to_string('notificsys/notification_mail.html', {'username': username, 'notificationtext' : notificationtext}) if(GLOBALSENDMAILS): send_mail( 'Agentur-Benachrichtigung', 'Hallo ' + user_touched.first_name + ' ' + user_touched.last_name + '! ' + notificationtext, 'support@digitale-agentur.com', [user_touched.email], html_message=msg_html, fail_silently=True ) @receiver(signal=post_save, sender=AgencyNetworkPreperation) def save_agjoin_prep(sender, instance, **kwargs): newnotification = UserNotification(touser=instance.target_network.creator, notificationtext="Eine Agentur möchte Ihrem Verbund beitreten.", notificationtype="wantedag", elementid=instance.pk) newnotification.save()