Exemplo n.º 1
0
def get_authorized_product_types(permission):
    user = get_current_user()

    if user.is_superuser:
        return Product_Type.objects.all().order_by('name')

    if settings.FEATURE_NEW_AUTHORIZATION:
        roles = get_roles_for_permission(permission)
        authorized_roles = Product_Type_Member.objects.filter(product_type=OuterRef('pk'),
            user=user,
            role__in=roles)
        product_types = Product_Type.objects.annotate(member=Exists(authorized_roles)).order_by('name')
        product_types = product_types.filter(member=True)
    else:
        if user.is_staff:
            product_types = Product_Type.objects.all().order_by('name')
        else:
            product_types = Product_Type.objects.filter(authorized_users__in=[user]).order_by('name')
    return product_types
Exemplo n.º 2
0
    def get_queryset(self):
        queryset = (super().get_queryset().annotate(is_esign=Exists(
            Event.objects.filter(
                action_id=OuterRef("action_id"),
                event_type__in=(
                    enums.EventType.FINISH_LEO,
                    enums.EventType.FINISH_LEO_FAX_PENDING,
                ),
            ))).filter(is_esign=True))

        search_query = self.request.GET.get("q")
        if search_query:
            queryset = queryset.filter(search=search_query)

        region_filter = self.request.GET.get("region")
        if region_filter:
            queryset = queryset.filter(region_id=int(region_filter))

        return queryset.select_related("state")
Exemplo n.º 3
0
 def export_form_fields(self):
     name_scheme = PERSON_NAME_SCHEMES[self.event.settings.name_scheme]
     d = OrderedDict([
         ('items',
          forms.ModelMultipleChoiceField(
              queryset=self.event.items.annotate(no_badging=Exists(
                  BadgeItem.objects.filter(item=OuterRef('pk'),
                                           layout__isnull=True))).exclude(
                                               no_badging=True),
              label=_('Limit to products'),
              widget=forms.CheckboxSelectMultiple(
                  attrs={'class': 'scrolling-multiple-choice'}),
              initial=self.event.items.filter(admission=True))),
         ('include_pending',
          forms.BooleanField(label=_('Include pending orders'),
                             required=False)),
         ('include_addons',
          forms.BooleanField(label=_('Include add-on or bundled positions'),
                             required=False)),
         ('rendering',
          forms.ChoiceField(
              label=_('Rendering option'),
              choices=[(k, r['name']) for k, r in OPTIONS.items()],
              required=True,
              help_text=
              _('This option allows you to align multiple badges on one page, for example if you '
                'want to print to a sheet of stickers with a regular office printer. Please note '
                'that your individual badge layouts must already be in the correct size.'
                ))),
         ('order_by',
          forms.ChoiceField(
              label=_('Sort by'),
              choices=[
                  ('name', _('Attendee name')),
                  ('code', _('Order code')),
              ] + ([('name:{}'.format(k),
                     _('Attendee name: {part}').format(part=label))
                    for k, label, w in name_scheme['fields']]
                   if settings.JSON_FIELD_AVAILABLE
                   and len(name_scheme['fields']) > 1 else []),
          )),
     ])
     return d
Exemplo n.º 4
0
    def filter_qs(self, qs):
        fdata = self.cleaned_data

        if fdata.get('query'):
            u = fdata.get('query')

            if "-" in u:
                code = (Q(event__slug__icontains=u.split("-")[0])
                        & Q(code__icontains=Order.normalize_code(u.split("-")[1])))
            else:
                code = Q(code__icontains=Order.normalize_code(u))

            matching_invoice = Invoice.objects.filter(
                order=OuterRef('pk'),
            ).annotate(
                inr=Concat('prefix', 'invoice_no')
            ).filter(
                Q(invoice_no__iexact=u)
                | Q(invoice_no__iexact=u.zfill(5))
                | Q(inr=u)
            )

            qs = qs.annotate(has_inv=Exists(matching_invoice))
            qs = qs.filter(
                code
                | Q(email__icontains=u)
                | Q(positions__attendee_name__icontains=u)
                | Q(positions__attendee_email__icontains=u)
                | Q(invoice_address__name__icontains=u)
                | Q(invoice_address__company__icontains=u)
                | Q(has_inv=True)
            )

        if fdata.get('status'):
            s = fdata.get('status')
            if s == 'o':
                qs = qs.filter(status=Order.STATUS_PENDING, expires__lt=now().replace(hour=0, minute=0, second=0))
            elif s == 'ne':
                qs = qs.filter(status__in=[Order.STATUS_PENDING, Order.STATUS_EXPIRED])
            else:
                qs = qs.filter(status=s)

        return qs
Exemplo n.º 5
0
def product_search(qs, phrase):
    """Return matching products for storefront views.

        Name and description is matched using search vector.

    Args:
        qs (ProductsQueryset): searched data set
        phrase (str): searched phrase

    """
    query = SearchQuery(phrase, config="english")
    vector = F("search_vector")
    ft_in_description_or_name = Q(search_vector=query)

    variants = ProductVariant.objects.filter(sku=phrase).values("id")
    ft_by_sku = Q(Exists(variants.filter(product_id=OuterRef("pk"))))

    return (qs.annotate(rank=SearchRank(vector, query)).filter(
        (ft_in_description_or_name | ft_by_sku)).order_by("-rank", "id"))
Exemplo n.º 6
0
def filter_products_by_minimal_price(
    qs, channel_slug, minimal_price_lte=None, minimal_price_gte=None
):
    channel = Channel.objects.filter(slug=channel_slug).first()
    if not channel:
        return qs
    product_channel_listings = ProductChannelListing.objects.filter(
        channel_id=channel.id
    )
    if minimal_price_lte:
        product_channel_listings = product_channel_listings.filter(
            discounted_price_amount__lte=minimal_price_lte
        )
    if minimal_price_gte:
        product_channel_listings = product_channel_listings.filter(
            discounted_price_amount__gte=minimal_price_gte
        )
    product_channel_listings = product_channel_listings.values("product_id")
    return qs.filter(Exists(product_channel_listings.filter(product_id=OuterRef("pk"))))
Exemplo n.º 7
0
    def get_queryset(self):
        """
        Optionally restricts the returned purchases to a given user,
        by filtering against a `username` query parameter in the URL.
        """
        # Add upvote count.
        queryset = Submission.objects.annotate(upvote_count=Count("upvote"))

        user_pk = self.request.user.pk if self.request.user.is_authenticated else None
        if self.request.user.is_authenticated:
            queryset = queryset.annotate(upvoted=Exists(
                Upvote.objects.filter(
                    user=self.request.user.pk,
                    submission=OuterRef("pk"),
                )))
        else:
            queryset = queryset.annotate(upvoted=Value(False, BooleanField()))

        # Filter by username if required.
        username = self.request.query_params.get("username", None)
        if username is not None:
            queryset = queryset.filter(user__github_id=username)

        ordering = self.request.query_params.get("ordering", None)
        if ordering == "hot":
            # Hotness algorithm: https://medium.com/hacking-and-gonzo/how-hacker-news-ranking-algorithm-works-1d9b0cf2c08d
            gravity = 1.8

            class Age(Func):
                template = "(EXTRACT(EPOCH FROM current_timestamp) - EXTRACT(EPOCH  FROM %(expressions)s))/3600"

            queryset = queryset.annotate(hotness=ExpressionWrapper(
                F("upvote_count") /
                Power(Age("created_at", output_field=FloatField()), gravity),
                output_field=FloatField(),
            ))
            queryset = queryset.order_by("-hotness")

        elif ordering == "top":
            queryset = queryset.order_by("-upvote_count")
        elif ordering == "new":
            queryset = queryset.order_by("-created_at")
        return queryset
Exemplo n.º 8
0
    def _ranges_that_contain_product(self, product):
        Category = product.categories.model
        included_in_subtree = product.categories.filter(
            path__rstartswith=OuterRef("path"), depth__lte=OuterRef("depth")
        )
        category_tree = Category.objects.annotate(
            is_included_in_subtree=Exists(included_in_subtree.values("id"))
        ).filter(is_included_in_subtree=True)

        wide = self.filter(
            ~models.Q(excluded_products=product), includes_all_products=True
        )
        narrow = self.filter(
            models.Q(included_products=product)
            | models.Q(included_categories__in=category_tree)
            | models.Q(classes__in=product_class_as_queryset(product)),
            includes_all_products=False,
        )
        return wide | narrow
Exemplo n.º 9
0
def create_summary_report(user, interval):
    """Create a report with statistics for a user regarding the period
    of time received as interval."""
    
    sr = SummaryReport()
    sr.user = user
    
    sr.posts_made = Post.objects.filter(user=user, created__gte=interval).count()
    sr.comments_made = Comment.objects.filter(user=user, created__gte=interval).count()
    sr.comments_received = Comment.objects.filter(
		~Q(user=user),
		Exists(Post.objects.filter(id=OuterRef('post_id'), user=user)),
		created__gte=interval
	).count()
    sr.messages_sent = PrivateMessage.objects.filter(origin_user=user, created__gte=interval).count()
    sr.messages_received = PrivateMessage.objects.filter(target_user=user, created__gte=interval).count()
    sr.notifications = Notification.objects.filter(target_user=user, created__gte=interval).count()
    sr.save()
    create_notification(user)
Exemplo n.º 10
0
    def param_queryset(self, query_params, default_queryset):
        filters = self.parse_query_params(query_params)
        auth_user = utils.get_user_auth(self.request)
        if 'filter[preprint]' in query_params:
            query = Preprint.objects.preprint_permissions_query(user=auth_user.user)
            subquery = Preprint.objects.filter(query & Q(deleted__isnull=True) & Q(node=OuterRef('pk')))
            queryset = default_queryset.annotate(preprints_exist=Exists(subquery))
        else:
            queryset = default_queryset

        if filters:
            for key, field_names in filters.items():
                for field_name, operation in field_names.items():
                    # filter[parent]=null
                    if field_name == 'parent' and operation['op'] == 'eq' and not operation['value']:
                        queryset = queryset.get_roots()
                        query_params = deepcopy(query_params)
                        query_params.pop(key)
        return super(NodesFilterMixin, self).param_queryset(query_params, queryset)
Exemplo n.º 11
0
    def get_users_with_permission(self, permission):
        """
        Returns a queryset of users who have a specific permission to this event.

        :return: Iterable of User
        """
        from .auth import User

        if permission:
            kwargs = {permission: True}
        else:
            kwargs = {}

        team_with_perm = Team.objects.filter(
            members__pk=OuterRef('pk'), organizer=self.organizer,
            **kwargs).filter(Q(all_events=True) | Q(limit_events__pk=self.pk))

        return User.objects.annotate(twp=Exists(team_with_perm)).filter(
            twp=True)
Exemplo n.º 12
0
 def _migratable(self):
     return StorageMedium.objects.exclude(status=0).filter(
         storage_target__storage_method_target_relations__status=
         STORAGE_TARGET_STATUS_MIGRATE, ).annotate(
             has_non_migrated_storage_object=self.
             _has_non_migrated_storage_object(False),
             migrate_method_rel=Subquery(
                 StorageMethodTargetRelation.objects.filter(
                     storage_target=OuterRef('storage_target'),
                     status=STORAGE_TARGET_STATUS_MIGRATE,
                 ).values('storage_method')[:1]),
             has_enabled_target=Exists(
                 StorageMethodTargetRelation.objects.filter(
                     storage_method=OuterRef('migrate_method_rel'),
                     status=STORAGE_TARGET_STATUS_ENABLED,
                 ))).filter(
                     has_non_migrated_storage_object=True,
                     has_enabled_target=True,
                 )
Exemplo n.º 13
0
    def get(self, request, user_id):
        current_user_id = request.user.pk
        user = User.objects.filter(pk=user_id).first()
        if not user:
            raise Http404("User not exist")

        # get feeds and check if feed is in favorites
        bookmark = Bookmark.objects.filter(
            user_id=current_user_id, feed_id=OuterRef("pk")
        )
        feeds = (
            Feed.objects.prefetch_related("comments__author")
            .filter(channel__user_id=user.pk)
            .annotate(is_favorite=Exists(bookmark))
            .order_by("-pub_date")
        )

        # use pagination
        paginator = Paginator(feeds, 25)
        page = request.GET.get("page")
        feeds_per_page = paginator.get_page(page)

        has_next = feeds_per_page.has_next()
        has_previous = feeds_per_page.has_previous()
        if current_user_id == user_id:
            h1 = "Your feeds"
        else:
            h1 = f"{user.email} feeds"

        template_data = {
            "h1": h1,
            "email": user.email,
            "feeds": feeds_per_page,
            "pagination": {
                "has_previous": has_previous,
                "has_next": has_next,
                "num_pages": feeds_per_page.paginator.num_pages,
                "number": feeds_per_page.number,
            },
        }

        return render(request, self.template_name, template_data)
Exemplo n.º 14
0
    def property_to_Q(self) -> Q:
        from .cohort import CohortPeople

        if self.type in CLICKHOUSE_ONLY_PROPERTY_TYPES:
            raise ValueError(
                f"property_to_Q: type is not supported: {repr(self.type)}")

        value = self._parse_value(self.value)
        if self.type == "cohort":
            cohort_id = int(cast(Union[str, int], value))
            return Q(
                Exists(
                    CohortPeople.objects.filter(
                        cohort_id=cohort_id,
                        person_id=OuterRef("id"),
                    ).only("id")))

        if self.operator == "is_not":
            return Q(~lookup_q(f"properties__{self.key}", value)
                     | ~Q(properties__has_key=self.key))
        if self.operator == "is_set":
            return Q(**{"properties__{}__isnull".format(self.key): False})
        if self.operator == "is_not_set":
            return Q(**{"properties__{}__isnull".format(self.key): True})
        if self.operator in ("regex",
                             "not_regex") and not is_valid_regex(value):
            # Return no data for invalid regexes
            return Q(pk=-1)
        if isinstance(self.operator, str) and self.operator.startswith("not_"):
            return Q(~Q(
                **{
                    "properties__{}__{}".format(self.key, self.operator[4:]):
                    value
                })
                     | ~Q(properties__has_key=self.key)
                     | Q(**{"properties__{}".format(self.key): None}))

        if self.operator == "exact" or self.operator is None:
            return lookup_q(f"properties__{self.key}", value)
        else:
            assert not isinstance(value, list)
            return Q(**{f"properties__{self.key}__{self.operator}": value})
Exemplo n.º 15
0
    def add_debate_ballot_link_column(self, debates, show_ballot=False):
        ballot_links_header = {'key': "ballot", 'icon': 'search',
                               'tooltip': _("The ballot you submitted")}

        if self.admin:
            ballot_links_data = [{
                'text': _("View/Edit Ballot"),
                'link': reverse_tournament('old-results-ballotset-edit', self.tournament, kwargs={'pk': debate.confirmed_ballot.id}),
            } if debate.confirmed_ballot else "" for debate in debates]
            self.add_column(ballot_links_header, ballot_links_data)

        elif self.private_url:
            debates = Debate.objects.filter(pk__in=[d.pk for d in debates]).select_related('round').annotate(
                has_ballot=Exists(BallotSubmission.objects.filter(debate_id=OuterRef('id')).exclude(discarded=True)),
            ).prefetch_related(
                Prefetch('ballotsubmission_set', queryset=BallotSubmission.objects.exclude(discarded=True), to_attr='nondiscard_ballots'))
            ballot_links_data = []
            for debate in debates:
                if not debate.has_ballot:
                    ballot_links_data.append(_("No ballot"))
                elif not get_result_class(debate.nondiscard_ballots[0], debate.round, self.tournament).uses_speakers:
                    ballot_links_data.append(_("No scores"))
                else:
                    ballot_links_data.append({
                        'text': _("View Ballot"),
                        'link': reverse_round(
                            'results-privateurl-scoresheet-view', debate.round, kwargs={'url_key': self.private_url_key}),
                    })
            self.add_column(ballot_links_header, ballot_links_data)

        elif self.tournament.pref('ballots_released'):
            ballot_links_data = []
            for debate in debates:
                if self.tournament.pref('teams_in_debate') == 'bp' and debate.round.is_break_round:
                    ballot_links_data.append("")
                else:
                    ballot_links_data.append({
                        'text': _("View Ballot"),
                        'link': reverse_tournament('results-public-scoresheet-view', self.tournament,
                            kwargs={'pk': debate.id}),
                    })
            self.add_column(ballot_links_header, ballot_links_data)
class CompletedTaskView(OwnerPerformCreateMixin, mixins.CreateModelMixin,
                        mixins.ListModelMixin, mixins.RetrieveModelMixin,
                        viewsets.GenericViewSet):
    """Completed task"""
    serializer_class = s.CompletedTaskSerializer
    queryset = m.CompletedTask.objects.all() \
        .annotate(grade_present=Exists(m.Grade.objects.filter(completed_task=OuterRef('pk'))))
    permission_classes = (permissions.IsAuthenticated, )

    # filter_backends = [DjangoFilterBackend]    # INVESTIGATE
    # filterset_fields = ["grade_present", ]  #TypeError: 'Meta.fields' must not contain non-model field names: grade_present

    def get_queryset(self):
        """
        User is teacher:
            all completed tasks where teacher is a member of the course.
        User is student:
            user's own completed tasks.
        """
        user = self.request.user
        if user.is_teacher:
            queryset = self.queryset.filter(course__memberships__user=user)
        else:
            queryset = self.queryset.filter(owner=user)
        return queryset

    def get_permissions(self):
        """
        Instantiates and returns the list of permissions that this view requires.
        create(), retrieve(), update(), partial_update(), destroy() and list()
        """
        if self.action == "create":
            permission_classes = [
                permissions.IsAuthenticated, IsCompletedTaskRelatedToCourse
            ]
        elif self.action in ["retrieve", "list"]:
            permission_classes = [
                permissions.IsAuthenticated, IsCourseMemberOrOwner
            ]
        else:
            permission_classes = self.permission_classes
        return [permission() for permission in permission_classes]
Exemplo n.º 17
0
    def render(self, form_data: dict):
        qs = self.event.invoices.filter(shredded=False)

        if form_data.get('payment_provider'):
            qs = qs.annotate(has_payment_with_provider=Exists(
                OrderPayment.objects.filter(
                    Q(order=OuterRef('order_id'))
                    & Q(provider=form_data.get('payment_provider')))))
            qs = qs.filter(has_payment_with_provider=1)

        if form_data.get('date_from'):
            date_value = form_data.get('date_from')
            if isinstance(date_value, str):
                date_value = dateutil.parser.parse(date_value).date()
            qs = qs.filter(date__gte=date_value)

        if form_data.get('date_to'):
            date_value = form_data.get('date_to')
            if isinstance(date_value, str):
                date_value = dateutil.parser.parse(date_value).date()
            qs = qs.filter(date__lte=date_value)

        with tempfile.TemporaryDirectory() as d:
            with ZipFile(os.path.join(d, 'tmp.zip'), 'w') as zipf:
                for i in qs:
                    try:
                        if not i.file:
                            invoice_pdf_task.apply(args=(i.pk, ))
                            i.refresh_from_db()
                        i.file.open('rb')
                        zipf.writestr('{}.pdf'.format(i.number), i.file.read())
                        i.file.close()
                    except FileNotFoundError:
                        invoice_pdf_task.apply(args=(i.pk, ))
                        i.refresh_from_db()
                        i.file.open('rb')
                        zipf.writestr('{}.pdf'.format(i.number), i.file.read())
                        i.file.close()

            with open(os.path.join(d, 'tmp.zip'), 'rb') as zipf:
                return '{}_invoices.zip'.format(
                    self.event.slug), 'application/zip', zipf.read()
Exemplo n.º 18
0
    def property_to_Q(self) -> Q:
        from .cohort import CohortPeople

        value = self._parse_value(self.value)
        if self.type == "cohort":
            return Q(Exists(CohortPeople.objects.filter(cohort_id=int(value), person_id=OuterRef("id"),).only("id")))

        if self.operator == "is_not":
            return Q(~Q(**{"properties__{}".format(self.key): value}) | ~Q(properties__has_key=self.key))
        if self.operator == "is_set":
            return Q(**{"properties__{}__isnull".format(self.key): False})
        if self.operator == "is_not_set":
            return Q(**{"properties__{}__isnull".format(self.key): True})
        if isinstance(self.operator, str) and self.operator.startswith("not_"):
            return Q(
                ~Q(**{"properties__{}__{}".format(self.key, self.operator[4:]): value})
                | ~Q(properties__has_key=self.key)
                | Q(**{"properties__{}".format(self.key): None})
            )
        return Q(**{"properties__{}{}".format(self.key, f"__{self.operator}" if self.operator else ""): value})
Exemplo n.º 19
0
def _get_children(node, auth):
    """
    Returns the serialized representation of the given node and all of its children
    for which the given user has ADMIN permission.
    """
    is_admin = Contributor.objects.filter(node=OuterRef('pk'),
                                          admin=True,
                                          user=auth.user)
    parent_node_sqs = NodeRelation.objects.filter(
        child=OuterRef('pk'), is_node_link=False).values('parent__guids___id')
    children = (Node.objects.get_children(node).filter(
        is_deleted=False).annotate(
            parentnode_id=Subquery(parent_node_sqs[:1])).annotate(
                has_admin_perm=Exists(is_admin)).filter(has_admin_perm=True))

    nested = defaultdict(list)
    for child in children:
        nested[child.parentnode_id].append(child)

    return serialize_children(nested[node._id], nested)
Exemplo n.º 20
0
def _annotate_has_visuals(datasets):
    """
    Adds a bool annotation to queryset if the dataset has visuals
    @param datasets: django queryset
    @return: the annotated dataset
    """
    if datasets.model is ReferenceDataset or datasets.model is VisualisationCatalogueItem:
        datasets = datasets.annotate(has_visuals=Value(False, BooleanField()))
    if datasets.model is DataSet:
        datasets = datasets.annotate(has_visuals=Case(
            When(
                Exists(
                    DataSetVisualisation.objects.filter(
                        dataset_id=OuterRef("id"))),
                then=True,
            ),
            default=False,
            output_field=BooleanField(),
        ))
    return datasets
Exemplo n.º 21
0
 def get(self, request):
     books = Books.objects.prefetch_related(
         'shop', 'genre', 'author'
     )  # .annotate(avg_rate=Avg('user_rate__rate')) (Аннтотация -Добавление поля в sql таблицу)
     books = books.annotate(count=Count('comment', distinct=True))
     genre = Genre.objects.all()
     comments = Comment.objects.all()
     if request.user.is_authenticated:
         is_owner = Exists(
             User.objects.filter(books=OuterRef('pk'), id=request.user.id))
         books = books.annotate(is_owner=is_owner)
     paginator = Paginator(books, 4)
     context = {
         'title': 'Shop Book',
         'books': paginator.get_page(request.GET.get('page', 1)),
         'comments': comments,
         'range': range(1, 6),
         'genre': genre,
     }
     return render(request, 'manager/index.html', context=context)
Exemplo n.º 22
0
 def get_specs_search_rank(self, ct_obj: ContentType, cat_list=None):
     """Rank and filter specifications by search text"""
     query = self.query
     vector = self.get_specs_vector()
     qs_prod = self.get_products_search(ct_obj)
     product = qs_prod.filter(id=OuterRef('object_id'))
     product_rank = product.annotate(rank=SearchRank('search', query))
     qs = get_specs(ct_id=ct_obj.id).annotate(search=vector)
     if cat_list is None:
         qs = qs.filter(Q(Exists(product)) | Q(search=query))
     else:
         qs = qs.filter(category_id__in=cat_list)
     qs = qs.annotate(
         rank_prod=Subquery(product_rank.order_by().values('rank')),
         rank_spec=SearchRank('search', query),
     ).annotate(rank=Case(
         When(rank_prod__isnull=True, then='rank_spec'),
         default=(F('rank_prod') + F('rank_spec')),
     ))
     return get_specs_with_rating(qs)
Exemplo n.º 23
0
 def _get_database_records(self, questions, region):
     q = None
     for question in questions:
         sub_q = Q(full_subdomain=str(question.qname),
                   rtype=question.qtype,
                   rclass=question.qclass)
         sub_q = sub_q | Q(full_subdomain=str(question.qname),
                           rtype=QTYPE.CNAME,
                           rclass=question.qclass)
         if not q:
             q = sub_q
         else:
             q = q | sub_q
     if region:
         q_region = Q(region_name__in=[
             region.state, region.province, region.city, region.zone
         ])
         regions = Record.objects.filter(q & q_region)
         q = (q & q_region) | (~Exists(regions) & q)
     return list(Record.objects.filter(q).all())
Exemplo n.º 24
0
def get_calendars(when, calendar_ids=None):
    calendars = Calendar.objects.filter(Q(end_date__gte=when) | Q(end_date=None),
                                        start_date__lte=when)
    calendar_dates = CalendarDate.objects.filter(Q(end_date__gte=when) | Q(end_date=None),
                                                 start_date__lte=when)
    if calendar_ids is not None:
        # cunningly make the query faster
        calendars = calendars.filter(id__in=calendar_ids)
        calendar_dates = calendar_dates.filter(calendar__in=calendar_ids)
    exclusions = calendar_dates.filter(operation=False)
    inclusions = calendar_dates.filter(operation=True)
    special_inclusions = inclusions.filter(special=True)
    only_certain_dates = Exists(CalendarDate.objects.filter(calendar=OuterRef('id'), special=False, operation=True))
    return calendars.filter(
        ~Q(calendardate__in=exclusions)
    ).filter(
        Q(~only_certain_dates) | Q(calendardate__in=inclusions)
    ).filter(
        Q(**{when.strftime('%a').lower(): True}) | Q(calendardate__in=special_inclusions)
    )
Exemplo n.º 25
0
def annotated_event_query(request):
    active_orders = Order.objects.filter(
        event=OuterRef('pk'),
        status__in=[
            Order.STATUS_PENDING, Order.STATUS_PAID
        ]).order_by().values('event').annotate(c=Count('*')).values('c')

    required_actions = RequiredAction.objects.filter(event=OuterRef('pk'),
                                                     done=False)
    qs = request.user.get_events_with_any_permission(request).annotate(
        order_count=Subquery(active_orders, output_field=IntegerField()),
        has_ra=Exists(required_actions)).annotate(
            min_from=Min('subevents__date_from'),
            max_from=Max('subevents__date_from'),
            max_to=Max('subevents__date_to'),
            max_fromto=Greatest(Max('subevents__date_to'),
                                Max('subevents__date_from')),
        ).annotate(order_to=Coalesce('max_fromto', 'max_to', 'max_from',
                                     'date_to', 'date_from'), )
    return qs
Exemplo n.º 26
0
    def progress(self):
        questions = Question.objects.filter(
            attribute_id=OuterRef('pk'),
            questionset__section__catalog_id=self.catalog.id)
        attributes = Attribute.objects.annotate(
            active=Exists(questions)).filter(active=True).distinct()

        total = attributes.count()
        values = self.values.filter(snapshot=None) \
                            .filter(attribute__in=attributes) \
                            .exclude((models.Q(text='') | models.Q(text=None)) & models.Q(option=None) &
                                     (models.Q(file='') | models.Q(file=None))) \
                            .distinct().values('attribute').count()

        try:
            ratio = values / total
        except ZeroDivisionError:
            ratio = 0

        return {'total': total, 'values': values, 'ratio': ratio}
Exemplo n.º 27
0
 def get(self, request, *args, **kwargs):
     context = {}
     context["available_members"] = []
     event, _ = Event.objects.get_or_create(title=kwargs["event_name"])
     context["team_members"] = self.request.user.team.members.all(
     ).annotate(is_registered=Exists(
         SubTeam.objects.filter(members__id=OuterRef("id"),
                                event__title=event.title)))
     context["registered_events"] = get_registered_events(self.request.user)
     for member in self.request.user.team.members.exclude(
             subteams__event__title=event.title).all():
         context["available_members"].append({
             "pk":
             member.pk,
             "name":
             member.fullname or member.first_name + " " + member.last_name
         })
     context["event_name"] = kwargs["event_name"]
     context["event"] = event
     return render(request, self.template_name, context=context)
Exemplo n.º 28
0
    def _post_postponement(self):
        # Postpone the prerequisite only at the end to be sure to have all learning units and education groups
        self._check_options()

        luys_not_postponed = LearningUnitYear.objects.filter(
            id__in=self._learning_units_id_in_n_instance
        ).exclude(learning_unit__in=LearningUnit.objects.filter(
            learningunityear__id__in=self._learning_units_id_in_n1_instance
        )).annotate(has_prerequisite=Exists(
            PrerequisiteItem.objects.filter(
                prerequisite__education_group_year__id=self.instance.id,
                prerequisite__learning_unit_year__id=OuterRef("id"),
            )))
        for luy in luys_not_postponed:
            if luy.has_prerequisite:
                self.warnings.append(PrerequisiteWarning(
                    luy, self.instance_n1))

        for old_luy, new_luy in self.postponed_luy:
            self._postpone_prerequisite(old_luy, new_luy)
Exemplo n.º 29
0
 def get_budget_function_queryset(self):
     filters = [
         Q(treasury_account_id=OuterRef("pk")),
         Q(final_of_fy=True),
         Q(treasury_account__funding_toptier_agency=self.toptier_agency),
         Q(submission__reporting_fiscal_year=self.fiscal_year),
         Q(
             Q(obligations_incurred_by_program_object_class_cpe__gt=0)
             | Q(obligations_incurred_by_program_object_class_cpe__lt=0)
             | Q(gross_outlay_amount_by_program_object_class_cpe__gt=0)
             | Q(gross_outlay_amount_by_program_object_class_cpe__lt=0)
         ),
     ]
     return (
         TreasuryAppropriationAccount.objects.annotate(
             include=Exists(FinancialAccountsByProgramActivityObjectClass.objects.filter(*filters).values("pk"))
         )
         .filter(include=True)
         .values("budget_function_code", "budget_subfunction_code")
     )
Exemplo n.º 30
0
def all_unconfirmed_suggested_alike(request):
    confirmed_subquery = ConfirmedAlike.objects \
        .filter(game1=OuterRef('game1'), game2=OuterRef('game2'))

    unconf_sugg_alike = SuggestAlike.objects \
        .annotate(already_confirmed=Exists(confirmed_subquery)) \
        .filter(already_confirmed=False) \
        .annotate(game1_title=Coalesce(
            'game1__game_eu__title', 'game1__game_us__title')) \
        .annotate(game1_image=Coalesce(
            'game1__game_eu__image_sq_h2_url', 'game1__game_us__front_box_art',
            output_field=CharField())) \
        .annotate(game2_title=Coalesce(
            'game2__game_eu__title', 'game2__game_us__title')) \
        .annotate(game2_image=Coalesce(
            'game2__game_eu__image_sq_h2_url', 'game2__game_us__front_box_art',
            output_field=CharField())) \
        .values(
            'game1__id', 'game1__game_code_unique', 'game1_title', 'game1_image',
            'game2__id', 'game2__game_code_unique', 'game2_title', 'game2_image',
        ) \
        .distinct()

    response = list(
        map(lambda alike: {
            'game1': {
                'id': alike['game1__id'],
                'game_code': alike['game1__game_code_unique'],
                'title': alike['game1_title'],
                'game_image': alike['game1_image'],
            },
            'game2': {
                'id': alike['game2__id'],
                'game_code': alike['game2__game_code_unique'],
                'title': alike['game2_title'],
                'game_image': alike['game2_image'],
            },
        }, unconf_sugg_alike)
    )

    return Response(response, status=status.HTTP_200_OK)