Esempio n. 1
0
    def request_freeze_cancel(self, request, month=None):
        intern = request.user
        month = Month.from_int(int(month))
        current_freeze = intern.freezes.current_for_month(month)

        if not current_freeze:
            raise ObjectDoesNotExist("This month has no freeze to cancel.")

        if intern.freeze_cancel_requests.current_for_month(month):
            raise PermissionDenied("There is a pending freeze cancel request for this month already.")

        # TODO: Check that there are no rotations, leaves, freezes, or related requests in the month to be disabled

        cancel_request = FreezeCancelRequest.objects.create(
            intern=intern,
            month=month,
        )

        # --notifications--

        # Subscribe user to receive update notifications on the request
        subscribe(request.user.settings_set.first(), "freeze_cancel_request_approved", object_id=cancel_request.id)
        subscribe(request.user.settings_set.first(), "freeze_cancel_request_declined", object_id=cancel_request.id)

        # Notify medical internship unit of the request
        notify(
            "A freeze cancellation request has been submitted by %s" % (request.user.profile.get_en_full_name()),
            "freeze_cancel_request_submitted",
            url="/planner/%d/" % cancel_request.intern.profile.intern.internship.id,
            )

        messages.success(request._request, "Your freeze cancellation request has been submitted successfully.")

        return Response(status=HTTP_201_CREATED)
Esempio n. 2
0
    def respond(self, is_approved, comments=""):
        """
        Respond to the leave cancel request; raise an error if it's already responded to.
        """
        try:
            self.response
        except ObjectDoesNotExist:
            LeaveCancelRequestResponse.objects.create(
                request=self,
                is_approved=is_approved,
                comments=comments,
            )

            if is_approved:
                self.leave_request.leave.delete()

            # Notify intern
            if is_approved:
                # --notifications--
                notify(
                    "Your %s during %s has been cancelled." % (self.type.name, self.month.first_day().strftime("%B %Y")),
                    "leave_cancel_request_approved",
                    target_object=self,
                    url="/planner/%d/" % int(self.month),
                )
            else:
                # --notifications--
                notify(
                    "Your request to cancel your %s during %s has been declined." % (self.type.name, self.month.first_day().strftime("%B %Y")),
                    "leave_cancel_request_declined",
                    target_object=self,
                    url="/planner/%d/leaves/history/" % int(self.month),
                )
        else:
            raise Exception("This leave cancel request has already been responded to.")
Esempio n. 3
0
    def request_freeze(self, request, month=None):
        if request.method == "POST":
            month = Month.from_int(int(month))
            intern = self.request.user

            # TODO: Check that month is not frozen or disabled or there is a freeze request
            # TODO: Check that month has not current rotation or rotation request

            form = FreezeRequestForm(data=request.data, instance=FreezeRequest(intern=intern, month=month))

            if form.is_valid():

                freeze_request = form.save()

                # Subscribe user to receive update notifications on the request
                subscribe(intern.settings_set.first(), "freeze_request_approved", object_id=freeze_request.id)
                subscribe(intern.settings_set.first(), "freeze_request_declined", object_id=freeze_request.id)

                # Notify medical internship unit of the request
                notify(
                    "A new freeze request has been submitted by %s" % (request.user.profile.get_en_full_name()),
                    "freeze_request_submitted",
                    url="/planner/%d/" % freeze_request.intern.profile.intern.internship.id,
                )

                # Display success message to user
                messages.success(request._request, "Your freeze request has been submitted successfully.")

            response_data = {'errors': form.errors}
            return Response(response_data)
        return FreezeRequestFormView.as_view()(request._request, month)
Esempio n. 4
0
    def test_notify(self):

        # Subscribe User 1 to test key
        utils.subscribe(self.user1_settings, self.TEST_KEY)
        utils.notify("Test is a test", self.TEST_KEY)

        # Check that there is exactly 1 notification
        self.assertEqual(models.Notification.objects.all().count(), 1)
Esempio n. 5
0
    def test_notify(self):

        # Subscribe User 1 to test key
        utils.subscribe(self.user1_settings, self.TEST_KEY)
        utils.notify("Test is a test", self.TEST_KEY)

        # Check that there is exactly 1 notification
        self.assertEqual(models.Notification.objects.all().count(), 1)
Esempio n. 6
0
    def test_simple(self):

        TEST_KEY = 'test_key'
        user = User.objects.create_user('lalala')
        user_settings = models.Settings.objects.create(user=user)
        utils.subscribe(user_settings, TEST_KEY)
        utils.notify("Test Is a Test", TEST_KEY)

        self.assertEqual(models.Notification.objects.all().count(), 1)
Esempio n. 7
0
def notify_test(sender, instance, **kwargs):

    logger.info("New object created: {}".format(str(instance)))

    notify(
        _("Message is: {}".format(instance.name)),
        NOTIFICATION_TEST_KEY,
        target_object=instance,
    )
Esempio n. 8
0
 def test_mark_read(self):
     utils.subscribe(self.user_settings, self.TEST_KEY)
     utils.notify("Test Is a Test", self.TEST_KEY)
     self.assertEqual(
         models.Notification.objects.filter(is_viewed=False).count(), 1)
     nid = models.Notification.objects.get().id
     self.client.login(username=self.user.username, password='******')
     self.client.get(reverse('nyt:json_mark_read', args=(nid, )))
     self.assertEqual(
         models.Notification.objects.filter(is_viewed=False).count(), 0)
Esempio n. 9
0
 def test_mark_read(self):
     utils.subscribe(self.user_settings, self.TEST_KEY)
     utils.notify("Test Is a Test", self.TEST_KEY)
     self.assertEqual(models.Notification.objects.filter(is_viewed=False).count(),
                      1)
     nid = models.Notification.objects.get().id
     self.client.login(username=self.user.username,
                       password='******')
     self.client.get(reverse('nyt:json_mark_read', args=(nid,)))
     self.assertEqual(models.Notification.objects.filter(is_viewed=False).count(),
                      0)
Esempio n. 10
0
def notifyu(request):
    if not request.user.is_authenticated():
        return HttpResponse("not authoride")

    notify(
        "hello",
        "test",
        target_object=request.user,
    )

    return HttpResponse("OK")
Esempio n. 11
0
    def test_simple(self):

        TEST_KEY = 'test_key'
        user = User.objects.create_user(
            'lalala'
        )
        user_settings = models.Settings.objects.create(user=user)
        utils.subscribe(user_settings, TEST_KEY)
        utils.notify("Test Is a Test", TEST_KEY)

        self.assertEqual(models.Notification.objects.all().count(), 1)
Esempio n. 12
0
 def plugin_notification(instance, **kwargs):
     if notification_dict.get('ignore', lambda x: False)(instance):
         return
     if kwargs.get('created', False) == notification_dict.get('created', True):
         url = None
         if 'get_url' in notification_dict:
             url = notification_dict['get_url'](instance)
         else:
             url = default_url(notification_dict['get_article'](instance))
         
         message = notification_dict['message'](instance)
         notify(message, notification_dict['key'],
                target_object=notification_dict['get_article'](instance), url=url)
Esempio n. 13
0
    def notify_and_message(self, request, rotation_request):
        # Subscribe user to receive update notifications on the request
        subscribe(request.user.settings_set.first(), "rotation_request_approved", object_id=rotation_request.id)
        subscribe(request.user.settings_set.first(), "rotation_request_declined", object_id=rotation_request.id)

        # Notify medical internship unit of the request
        notify(
            "A new rotation request has been submitted by %s" % (request.user.profile.get_en_full_name()),
            "rotation_request_submitted",
            url="/interns/%d/" % rotation_request.internship.id,
        )  # FIXME: avoid sending a lot of simultaneous notifications

        # Display success message to user
        messages.success(request._request, "Your request has been submitted successfully.")
Esempio n. 14
0
    def test_notify_two_users(self):

        # Subscribe User 2 to test key
        utils.subscribe(self.user2_settings, self.TEST_KEY)
        utils.subscribe(self.user1_settings, self.TEST_KEY)
        utils.notify("Another test", self.TEST_KEY)

        self.assertEqual(models.Notification.objects.all().count(), 2)

        # Now create the same notification again, this should not create new
        # objects in the DB but instead increase the count of that notification!
        utils.notify("Another test", self.TEST_KEY)

        self.assertEqual(models.Notification.objects.filter(occurrences=2).count(), 2)
Esempio n. 15
0
    def test_notify_two_users(self):

        # Subscribe User 2 to test key
        utils.subscribe(self.user2_settings, self.TEST_KEY)
        utils.subscribe(self.user1_settings, self.TEST_KEY)
        utils.notify("Another test", self.TEST_KEY)

        self.assertEqual(models.Notification.objects.all().count(), 2)

        # Now create the same notification again, this should not create new
        # objects in the DB but instead increase the count of that notification!
        utils.notify("Another test", self.TEST_KEY)

        self.assertEqual(
            models.Notification.objects.filter(occurrences=2).count(), 2)
Esempio n. 16
0
            def plugin_notification(instance, **kwargs):
                if notification_dict.get("ignore", lambda x: False)(instance):
                    return
                if kwargs.get("created",
                              False) == notification_dict.get("created", True):
                    if "get_url" in notification_dict:
                        url = notification_dict["get_url"](instance)
                    else:
                        url = models.default_url(
                            notification_dict["get_article"](instance))

                    message = notification_dict["message"](instance)
                    notify(
                        message,
                        notification_dict["key"],
                        target_object=notification_dict["get_article"](
                            instance),
                        url=url,
                    )
Esempio n. 17
0
    def respond(self, is_approved, comments=""):
        """
        Respond to the leave request; raise an error if it's already responded to.
        """
        try:
            self.response
        except ObjectDoesNotExist:
            LeaveRequestResponse.objects.create(
                request=self,
                is_approved=is_approved,
                comments=comments,
            )

            # TODO: Test
            if is_approved:
                self.intern.leaves.create(
                    month=self.month,
                    type=self.type,
                    start_date=self.start_date,
                    end_date=self.end_date,
                    request=self,
                )

            # Notify intern
            if is_approved:
                # --notifications--
                notify(
                    "%s request #%d for %s has been approved." % (self.type.name, self.id, self.month.first_day().strftime("%B %Y")),
                    "leave_request_approved",
                    target_object=self,
                    url="/planner/%d/" % int(self.month),
                )
            else:
                # --notifications--
                notify(
                    "%s request #%d for %s has been declined." % (self.type.name, self.id, self.month.first_day().strftime("%B %Y")),
                    "leave_request_declined",
                    target_object=self,
                    url="/planner/%d/leaves/history/" % int(self.month),
                )
        else:
            raise Exception("This leave request has already been responded to.")
Esempio n. 18
0
    def notify_subscribers(self):
        SearchFilter = apps.get_model('subscriptions', 'SearchFilter')
        Subscription = apps.get_model('subscriptions', 'Subscription')

        filters = SearchFilter.objects.annotate(
            similarity=TrigramSimilarity('search', self.name)).filter(
                Q(activity_type=self.activity_type)
                | Q(activity_category=self.activity_category)
                | Q(similarity__gt=0.1))

        for f in filters:
            subscribers = Subscription.objects.filter(search_filter=f)
            for s in subscribers:
                if s.user != self.organizer:
                    notify(
                        ("New suitable activity %s" % self.name),
                        "test",
                        target_object=s.user,
                    )

        return
Esempio n. 19
0
def post_article_revision_save(**kwargs):
    instance = kwargs["instance"]
    if kwargs.get("created", False):
        url = default_url(instance.article)
        filter_exclude = {"settings__user": instance.user}
        if instance.deleted:
            notify(
                _("Article deleted: %s") % get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude,
            )
        elif instance.previous_revision:
            notify(
                _("Article modified: %s") % get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude,
            )
        else:
            notify(
                _("New article created: %s") % get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance,
                url=url,
                filter_exclude=filter_exclude,
            )
Esempio n. 20
0
def post_article_revision_save(**kwargs):
    instance = kwargs['instance']
    if kwargs.get('created', False):
        url = default_url(instance.article)
        filter_exclude = {'settings__user': instance.user}
        if instance.deleted:
            notify(
                _('Article deleted: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude)
        elif instance.previous_revision:
            notify(
                _('Article modified: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude)
        else:
            notify(
                _('New article created: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance,
                url=url,
                filter_exclude=filter_exclude)
Esempio n. 21
0
def post_article_revision_save(**kwargs):
    instance = kwargs['instance']
    if kwargs.get('created', False):
        url = default_url(instance.article)
        filter_exclude = {'settings__user': instance.user}
        if instance.deleted:
            notify(
                _('Article deleted: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude)
        elif instance.previous_revision:
            notify(
                _('Article modified: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance.article,
                url=url,
                filter_exclude=filter_exclude)
        else:
            notify(
                _('New article created: %s') %
                get_title(instance),
                settings.ARTICLE_EDIT,
                target_object=instance,
                url=url,
                filter_exclude=filter_exclude)
Esempio n. 22
0
    def create(self, request, *args, **kwargs):
        # Check that the responding user has sufficient permissions
        if not request.user.has_perm("months.freeze_cancel_request_response.create"):
            raise PermissionDenied

        # Check that freeze cancellation request exists
        freeze_cancel_request = get_object_or_404(FreezeCancelRequest, id=int(request.data['request']))

        # Check that there is no response already
        if hasattr(freeze_cancel_request, 'response'):
            raise PermissionDenied

        response = super(FreezeCancelRequestResponseViewSet, self).create(request, *args, **kwargs)

        # Delete freeze (if approved) and notify intern
        if bool(request.data['is_approved']):

            freeze = Freeze.objects.get(
                intern=freeze_cancel_request.intern,
                month=freeze_cancel_request.month,
            )
            freeze.delete()

            notify(
                "Freeze cancellation request %d for %s has been approved." % (freeze_cancel_request.id, freeze_cancel_request.month.first_day().strftime("%B %Y")),
                "freeze_cancel_request_approved",
                target_object=freeze_cancel_request,
                url="/planner/%d/" % int(freeze_cancel_request.month),
            )
        else:
            notify(
                "Freeze cancellation request %d for %s has been declined." % (freeze_cancel_request.id, freeze_cancel_request.month.first_day().strftime("%B %Y")),
                "freeze_cancel_request_declined",
                target_object=freeze_cancel_request,
                url="/planner/%d/" % int(freeze_cancel_request.month),
            )

        return response
Esempio n. 23
0
    def cancel_rotation(self, request, month=None):
        internship = request.user.profile.intern.internship
        month = Month.from_int(int(month))
        current_rotation = internship.rotations.current_for_month(month)

        if not current_rotation:
            raise ObjectDoesNotExist("This month has no rotation to cancel.")

        if internship.rotation_requests.current_for_month(month):
            raise PermissionDenied("There is a pending rotation request for this month already.")

        requested_department = current_rotation.rotation_request.requested_department
        requested_department.id = None
        requested_department.save()

        rr = internship.rotation_requests.create(
            month=month,
            specialty=requested_department.department.specialty,
            requested_department=requested_department,
            is_delete=True,
        )

        # --notifications--

        # Subscribe user to receive update notifications on the request
        subscribe(request.user.settings_set.first(), "rotation_request_approved", object_id=rr.id)
        subscribe(request.user.settings_set.first(), "rotation_request_declined", object_id=rr.id)

        # Notify medical internship unit of the request
        notify(
            "A cancellation request has been submitted by %s" % (request.user.profile.get_en_full_name()),
            "rotation_request_submitted",
            url="/planner/%d/" % rr.internship.id,
            )  # FIXME: avoid sending a lot of simultaneous notifications

        messages.success(request._request, "Your cancellation request has been submitted successfully.")

        return Response(status=HTTP_201_CREATED)
Esempio n. 24
0
    def respond(self, is_approved, comments=""):
        """
        Respond to the freeze request; raise an error if it's already responded to.
        """
        try:
            self.response
        except ObjectDoesNotExist:
            FreezeRequestResponse.objects.create(
                request=self,
                is_approved=is_approved,
                comments=comments,
            )

            if is_approved:
                self.intern.freezes.create(
                    month=self.month,
                    freeze_request=self,
                )

            # Notify intern
            if is_approved:
                # --notifications--
                notify(
                    "Freeze request for %s has been approved." % (self.month.first_day().strftime("%B %Y")),
                    "freeze_request_approved",
                    target_object=self,
                    url="/planner/%d/" % int(self.month),
                )
            else:
                # --notifications--
                notify(
                    "Freeze request for %s has been declined." % (self.month.first_day().strftime("%B %Y")),
                    "freeze_request_declined",
                    target_object=self,
                    url="/planner/%d/freezes/history/" % int(self.month),
                )
        else:
            raise Exception("This freeze request has already been responded to.")
Esempio n. 25
0
def notify(*args, **kwargs):
    """
    DEPRECATED - please access django_nyt.utils.notify
    """
    from django_nyt.utils import notify
    return notify(*args, **kwargs)
Esempio n. 26
0
    def respond_all(self):
        """
        Respond to all the requests in the Acceptance List appropriately.
        """
        # Verifications
        # (1) Redo general verifications to account for updates to the lists
        self.verify()
        # (2) All manually determined requests should have comments attached to them
        all_requests = self.auto_accepted + self.auto_declined + self.manual_accepted + self.manual_declined
        manual_requests = self.manual_accepted + self.manual_declined
        for request in manual_requests:
            assert hasattr(request, 'response'), "A manually determined request should have a comment attached."
            assert request.response.comments.strip(), "Comment can't be empty."

        responses = list()
        rotations = list()
        old_rotations = Q(pk=None)  # A query to old rotations in order to delete them

        for request in self.auto_accepted:
            if hasattr(request, 'response'):
                response = request.response
                response.is_approved = True
            else:
                response = RotationRequestResponse(
                    rotation_request=request,
                    is_approved=True,
                    comments="",
                )
            responses.append(response)

            rotations.append(Rotation(
                internship=request.internship,
                month=request.month,
                department=request.requested_department.department,
                specialty=request.specialty,
                is_elective=request.is_elective,
                rotation_request=request,
            ))

            old_rotations = old_rotations | Q(internship=request.internship, month=request.month)

        for request in self.auto_declined:
            if hasattr(request, 'response'):
                response = request.response
                response.is_approved = False
            else:
                response = RotationRequestResponse(
                    rotation_request=request,
                    is_approved=False,
                    comments="",
                )
            responses.append(response)

        for request in self.manual_accepted:
            response = request.response
            response.is_approved = True
            responses.append(response)

            rotations.append(Rotation(
                internship=request.internship,
                month=request.month,
                department=request.requested_department.department,
                specialty=request.specialty,
                is_elective=request.is_elective,
                rotation_request=request,
            ))

            old_rotations = old_rotations | Q(internship=request.internship, month=request.month)

        for request in self.manual_declined:
            response = request.response
            response.is_approved = False
            responses.append(response)

        RotationRequestResponse.objects.bulk_create(responses)

        Rotation.objects.filter(old_rotations).delete()
        Rotation.objects.bulk_create(rotations)

        for rotation_request in all_requests:
            if rotation_request.response.is_approved:
                notify(
                    "Rotation request %d for %s has been approved." % (rotation_request.id, rotation_request.month.first_day().strftime("%B %Y")),
                    "rotation_request_approved",
                    target_object=rotation_request,
                    url="/planner/%d/" % int(rotation_request.month),
                )
            else:
                notify(
                    "Rotation request %d for %s has been declined." % (rotation_request.id, rotation_request.month.first_day().strftime("%B %Y")),
                    "rotation_request_declined",
                    target_object=rotation_request,
                    url="/planner/%d/history/" % int(rotation_request.month),
                )
Esempio n. 27
0
    def respond(self, request, pk=None):
        """
        Respond to rotation request.
        """
        rotation_request = self.get_queryset().get(pk=pk)
        is_approved = bool(int(request.query_params.get("is_approved")))
        comments = request.query_params.get("comments", "")

        # Checks

        if hasattr(rotation_request, 'response'):
            raise ResponseExists("This rotation request has already been responded to.")
        
        department_requires_memo = rotation_request.requested_department.get_department().requires_memo
        memo_handed_by_intern = rotation_request.requested_department.get_department().memo_handed_by_intern
        if department_requires_memo and not hasattr(rotation_request, 'forward') and is_approved and not rotation_request.is_delete:
            raise ForwardExpected("This rotation request can't be approved without forwarding it first.")

        # TODO: Check that the appropriate person is recording the response
        if department_requires_memo and memo_handed_by_intern:
            pass

        RotationRequestResponse.objects.create(
            rotation_request=rotation_request,
            is_approved=is_approved,
            comments=comments,
        )
        
        if is_approved:
            # Remove any previous rotation in the request's month
            rotation_request.internship.rotations.filter(month=rotation_request.month).delete()

            # Unless this is a delete, request, add a new rotation object for the current month
            if not rotation_request.is_delete:
                # If the requested department is not in the database, add it.
                # FIXME: This shouldn't be default behavior
                if not rotation_request.requested_department.is_in_database:
                    rotation_request.requested_department.add_to_database()

                rotation_request.internship.rotations.create(
                    month=rotation_request.month,
                    specialty=rotation_request.specialty,
                    department=rotation_request.requested_department.get_department(),
                    is_elective=rotation_request.is_elective,
                    rotation_request=rotation_request,
                )
                
                # --notifications--

                notify(
                    "Rotation request %d for %s has been approved." % (rotation_request.id, rotation_request.month.first_day().strftime("%B %Y")),
                    "rotation_request_approved",
                    target_object=rotation_request,
                    url="/planner/%d/" % int(rotation_request.month),
                )
            else:

                # --notifications--
                notify(
                    "Rotation request %d for %s has been declined." % (rotation_request.id, rotation_request.month.first_day().strftime("%B %Y")),
                    "rotation_request_declined",
                    target_object=rotation_request,
                    url="/planner/%d/history/" % int(rotation_request.month),
                )
        
        if not request.query_params.get("suppress_message"):
            messages.success(request._request, "Your response has been recorded.")

        return Response({"status": RotationRequest.REVIEWED_STATUS, "is_approved": request.data.get("is_approved")})
Esempio n. 28
0
def notify(*args, **kwargs):
    """
    DEPRECATED - please access django_nyt.utils.notify
    """
    from django_nyt.utils import notify
    return notify(*args, **kwargs)