def activate_account(request, uidb64, token): uid = urlsafe_base64_decode(uidb64).decode() user = get_object_or_404(User, id=uid) #Önceden aktive edildiyse 404 verelim if user.profile.email_verified == True: return HttpResponseNotFound('<h1>No Page Here</h1>') if user is not None and not account_activation_token.check_token( user, token): return HttpResponseRedirect('/') #Email verification in database profile = user.profile profile.email_verified = True profile.save() #Giving permissions permission1 = Permission.objects.get(name='Can add new photos?') permission2 = Permission.objects.get(name='Can vote photos?') user.user_permissions.add(permission1) user.user_permissions.add(permission2) #Creating a notification for letting the user know he verified. verified = Notification( user=user, msg= "You have successfully verified your account. You can now upload photos to a contest as well as vote the photos of others." ) verified.save() login(request, user, backend='django.contrib.auth.backends.ModelBackend') return render(request, 'user/verification_done.html')
def home(request): if request.method == "POST": text = request.POST.get('text') img = request.FILES.get('post_image') post = Post(user=request.user, text=text, picture=img) post.save() mess = f"{request.user.first_name} {request.user.last_name} added a Post." for usr in request.user.profile.followers.all(): noti = Notification(user=usr, message=mess, link=f"/#post{post.id}") noti.save() return redirect('home') following_users = list(request.user.profile.following.all()) following_users.append(request.user) posts = Post.objects.filter( user__in=following_users).order_by('-created_at') all_post = Paginator(posts, 10) page = request.GET.get('page') try: posts = all_post.page(page) except PageNotAnInteger: posts = all_post.page(1) except EmptyPage: posts = all_post.page(all_post.num_pages) parms = { 'non_followed_user': request.user.profile.non_followed_user, 'posts': posts, } return render(request, 'main/home.html', parms)
def add_notification(self, name, data): Notification.objects.filter(name=name, user_id=self.id).delete() n = Notification(name=name, payload_json=json.dumps(data), user_id=self.id) n.save() return n
def like_an_item(itemconx_id, user): itemconx = get_object_or_404(ItemConnection, pk=itemconx_id) try: ItemLike.objects.get(user=user, item_conx=itemconx) except: user_to_notify = itemconx.board.user new_like = ItemLike.objects.create( user=user, item_conx=itemconx, ) Notification.create_itemlike_notify(user, user_to_notify, itemconx_id)
def like_a_board(board_id, user): board = get_object_or_404(Board, pk=board_id) try: BoardLike.objects.get(user=user, board=board) except: user_to_notify = board.user new_like = BoardLike.objects.create( user=user, board=board, ) Notification.create_boardlike_notify(user, user_to_notify, board_id)
def notePostSave(sender, instance, *args, **kwargs): new = 'emritem_ptr' in instance.changed_fields if hasattr_s(instance, 'patient'): patient = instance.patient link = 'emr:vemri,{0}'.format(instance.pk) if new: Notification.push(patient.user, "Note added to your EMR", "", link) else: Notification.push(patient.user, "A note in your EMR was updated", "", link)
def emrprofilePostSave(sender, instance, *args, **kwargs): if hasattr_s(instance, 'patient.doctor'): Notification.push(instance.patient.user, "Your Basic Medical Info has been updated", "", 'emr:vemr,{0}'.format(instance.patient.pk)) Notification.push( instance.patient.doctor.user, "{0}'s Medical Info has been updated".format( instance.patient.user.get_full_name()), "", 'emr:vemr,{0}'.format(instance.patient.pk))
def follow(request): if request.method == "POST": usrname = request.POST.get('user') following = get_object_or_404(User, username=usrname) following.profile.followers.add(request.user) request.user.profile.following.add(following) mess = f"{request.user.first_name} {request.user.last_name} started following you." noti = Notification(user=following, message=mess, link=f"/user/{request.user.username}") noti.save() return HttpResponse(True) raise Http404()
def vitalsPostSave(sender, instance, *args, **kwargs): new = 'emritem_ptr' in instance.changed_fields emritem = instance.emritem patient = emritem.patient Notification.push( patient.user, "Your {0}'s have been updated in the emr".format(instance.getTitle()), "", 'emr:vemri,{0}'.format(instance.pk)) Notification.push( patient.doctor.user, "New {0}'s your patient, {1}".format(instance.getTitle(), patient.user.get_full_name()), "", 'emr:vemri,{0}'.format(instance.pk))
def emradmitPostSave(sender, instance, *args, **kwargs): new = 'emritem_ptr' in instance.changed_fields emritem = instance.emritem patient = emritem.patient status = "" status = "Discharged From" if instance.admit: status = "Admitted to" Notification.push( patient.doctor.user, "Your patient {0}, has been {1} {2}".format(instance.getTitle(), status, instance.hospital), "", 'emr:vemri,{0}'.format(instance.pk))
def prescriptionPostSave(sender, instance, *args, **kwargs): new = 'emritem_ptr' in instance.changed_fields emritem = instance.emritem patient = emritem.patient med = "Medication: {0}".format(instance.medication) Notification.push( patient.user, "You have a new {0} from DR {1}".format( instance.getTitle(), instance.provider.user.get_full_name()), med, 'emr:vemri,{0}'.format(instance.pk)) if instance.provider != patient.doctor: Notification.push( patient.user, "{0} has written a prescription for you Patient {1}".format( instance.provider.user.get_full_name(), instance.emrpatient), med, 'emr:vemri,{0}'.format(instance.pk))
def reject_flow(request, *args, **kwargs): logger = logging.getLogger('flows') obj = FluxInstance.objects.filter(id=kwargs['pk']) if not obj: raise Http404() obj = obj.first() obj.status = 2 obj.save() msg = request.POST.get('msg') if msg: n = Notification(to_user=obj.initiated_by, from_user=request.user, flux=obj, message="Fluxul {} a fost refuzat! Motiv: {}".format( obj.flux_parent.title, msg)) n.save() logger.info('User {} rejected Flow {}'.format(request.user, obj.flux_parent.title)) return redirect('current_tasks')
def accept_flow(request, *args, **kwargs): logger = logging.getLogger('flows') obj = FluxInstance.objects.filter(id=kwargs['pk']) if not obj: logger.error('User {} encountered error. Could not find flux'.format( request.user)) raise Http404() obj = obj.first() obj.accepted_by.add(request.user) obj.save() if set(obj.flux_parent.acceptance_criteria.all()).issubset( obj.accepted_by.all()): obj.status = 1 obj.save() n = Notification(to_user=obj.initiated_by, flux=obj, from_user=request.user, message="Fluxul {} a fost acceptat de {}!".format( obj.flux_parent.title, request.user.username)) n.save() logger.info('User {} accepted Flow {}'.format(request.user, obj.flux_parent.title)) return redirect('current_tasks')
def send_message(recipient): current_user = session['id'] user_recipient = User.query.filter_by(id=recipient).first_or_404() form = MessageForm() if form.validate_on_submit(): print("data:", form.message.data) print("data type:", type(form.message.data)) print("data end") print("user_recipient:", user_recipient) msg = Message(sender_id=current_user, recipient_id=user_recipient.id, body=form.message.data) db.session.add(msg) db.session.commit() notifMsg = "New Message from " + form.physician_name.data newNotif = Notification(user_recipient.id, current_user, notifMsg, "MESSAGE") db.session.add(newNotif) db.session.commit() flash(('Your message has been sent.')) return redirect(url_for('patient_app.patient_home')) return render_template('user/send_message.html', title= ('Send Message'), form=form, recipient=recipient)
def admin_approval(request, pk): if request.method == "POST": if 'deliver_order' in request.POST: order = Order.objects.get(id=pk) print(order.user) order.delivered = True order.save() messages.success(request, "order delivered") new = Notification(user=order.user, text=str(order.product.name), success=True, seen=False) new.save() return redirect('admin_page') elif 'cancel_order' in request.POST: order = Order.objects.get(id=pk) new = Notification(user=order.user, text=str(order.product.name), success=False, seen=False) new.save() order.delete() messages.success(request, "order canceled") return redirect('admin_page')
def emrtestPostSave(sender, instance, *args, **kwargs): new = 'emritem_ptr' in instance.changed_fields emritem = instance.emritem patient = emritem.patient link = 'emr:vemri,{0}'.format(instance.pk) if new: Notification.push( patient.user, "A {0} was added to your emr".format(instance.getTitle()), "", link) else: Notification.push( patient.user, "A {0} was updated in your emr".format(instance.getTitle()), "", link) if not instance.released: Notification.push( patient.doctor.user, "Test Results for {0} require your approval".format( patient.user.get_full_name()), "", link)
def new_flux(request, pk=None): if request.method == 'POST': obj = FluxInstance.objects.get(id=pk) if 'cancel' in request.POST and request.POST['cancel'] == 'true': for step in obj.steps.all(): step.delete() obj.delete() return HttpResponseRedirect(reverse_lazy('init_tasks')) for i, step in enumerate(obj.steps.all()): new_doc_id = request.POST['doc_choice_{}'.format(i)] step_id = request.POST['orig_id_{}'.format(i)] s = Step.objects.get(id=step_id) s.document = Document.objects.get(id=new_doc_id) s.save() for user in obj.flux_parent.acceptance_criteria.all(): n = Notification( to_user=user, flux=obj, from_user=obj.initiated_by, message="Fluxul {} pornit de {} asteapta sa fie revizuit". format(obj.flux_parent.title, request.user.username)) n.save() return HttpResponseRedirect(reverse_lazy('init_tasks')) else: flux_model = FluxModel.objects.filter( pk=request.GET['flux_model_select']).first() obj = FluxInstance(flux_parent=FluxModel.objects.filter( id=request.GET['flux_model_select']).first(), initiated_by=request.user) obj.save() user_choices = list( Document.objects.filter(author=request.user, status__in=[1, 2]).values_list( 'id', 'filename', 'version')) user_choices = [(idx, filename + ": version %.2f" % version) for idx, filename, version in user_choices] fields = { "numsteps": IntegerField(widget=HiddenInput(), initial=len(list(flux_model.steps.all()))) } links = {} for i, step in enumerate(flux_model.steps.all()): if (step.template_file): links.update({i: (step.name, step.template_file.id)}) else: links.update({i: (step.name, None)}) step.id = None step.save() obj.steps.add(Step.objects.latest('id')) fields.update({ 'doc_choice_{}'.format(i): ChoiceField(choices=user_choices, label=links[i]) }) fields.update({ 'orig_id_{}'.format(i): IntegerField(widget=HiddenInput(), initial=step.id) }) MyForm = type('DocChoice', (BaseForm, ), {'base_fields': fields}) form = MyForm() print(request.GET['flux_model_select']) print(obj.flux_parent) return render(request, "new_task.html", { 'obj': obj, 'form': form, 'links': links })
def create_notification(self, user_giving, pseudoUser, type): Notification(id_giving=user_giving, id_receiving=CustomUser.objects.get(username=pseudoUser), type_notification=type).save()
def patient_messages(): #if no sent_messages/received messages, it'll be [] sent_messages = db.session.query(Message).filter(Message.sender_id==session["id"])[::-1] #reverse so it's listed in most recent received_messages = db.session.query(Message).filter(Message.recipient_id==session["id"])[::-1] #merge messages by most recent merged_messages = sorted([(m.id, m) for m in sent_messages] + [(m.id, m) for m in received_messages], key=lambda x:x[0], reverse=True) num_messages = len(merged_messages) message_bodies = [] for m_id, message in merged_messages: s = "" r = "" if message.sender_id == session["id"]: s = "You" else: sender = User.query.filter_by(id=message.sender_id).first() s = sender.fname + " " + sender.lname + " ID:"+ str(message.sender_id) if message.recipient_id == session["id"]: r = "You" else: recipient = User.query.filter_by(id=message.recipient_id).first() r = recipient.fname + " " + recipient.lname + " ID:"+ str(message.recipient_id) b = message.body #(sender name, recipient name, id, message body) message_bodies.append([s,r,b]) print(message_bodies) cipher_suite = Fernet(FERNET_KEY.encode('utf-8')) for i in range(len(message_bodies)): b_msg = bytes(message_bodies[i][2], encoding='utf-8') message_bodies[i][2] = cipher_suite.decrypt(b_msg).decode() #deals with sending the message user_physicians = db.session.query(TreatedBy).filter(TreatedBy.patient_id==session["id"]) physician_ids = [i.physician_id for i in user_physicians] physician_names = [] for i in physician_ids: physician = db.session.query(Physician).filter(Physician.physician_id==i) for a in physician: physician_names.append(a.practice_name + " ID:"+ str(i)) #physician_names[0].append(physician.practice_name) form = PatientSendMessageForm() #physician name and message body print("in patient") #physician_id = None if form.validate_on_submit(): physician_id = int(form.name.data.split()[-1][3:]) #e.g. Joptics ID:3 -> 3 #return redirect(url_for('patient_app.send_message', recipient = physician_id)) body_encrypted = cipher_suite.encrypt(bytes(form.message.data, encoding='utf-8')) msg = Message(sender_id=session['id'], recipient_id=physician_id, body=body_encrypted) db.session.add(msg) db.session.commit() notifMsg = "New Message" newNotif = Notification(physician_id, session['id'], notifMsg, "MESSAGE") db.session.add(newNotif) db.session.commit() flash(('Your message has been sent.')) return redirect(url_for('patient_app.patient_home')) loggedIn = 'id' in session.keys() and 'user_type' in session.keys() notifs = session['notifications'] if 'notifications' in session.keys() else [] usertype = session['user_type'] return render_template ('patient/messages.html', messages=merged_messages, message_bodies=message_bodies, num=num_messages, form=form, recipients=physician_names, notifs=notifs, num_notifs=len(notifs), loggedIn = loggedIn, usertype=usertype)