Ejemplo n.º 1
0
    def _populate_daily_summary_table(self):
        """Populate the daily summary table."""
        OCPUsageLineItemDailySummary.objects.all().delete()
        included_fields = [
            "usage_start",
            "usage_end",
            "namespace",
            "report_period_id",
            "pod",
            "node",
            "cluster_id",
            "cluster_alias",
            "node_capacity_cpu_cores",
            "pod_labels",
        ]
        annotations = {
            "pod_usage_cpu_core_hours":
            F("pod_usage_cpu_core_seconds") / 3600,
            "pod_request_cpu_core_hours":
            Sum(
                ExpressionWrapper(F("pod_request_cpu_core_seconds") / 3600,
                                  output_field=DecimalField())),
            "pod_limit_cpu_core_hours":
            Sum(
                ExpressionWrapper(F("pod_limit_cpu_core_seconds") / 3600,
                                  output_field=DecimalField())),
            "pod_usage_memory_gigabyte_hours":
            Sum(
                ExpressionWrapper(F("pod_usage_memory_byte_seconds") / 3600,
                                  output_field=DecimalField())) *
            math.pow(2, -30),
            "pod_request_memory_gigabyte_hours":
            Sum(
                ExpressionWrapper(F("pod_request_memory_byte_seconds") / 3600,
                                  output_field=DecimalField())) *
            math.pow(2, -30),
            "pod_limit_memory_gigabyte_hours":
            ExpressionWrapper(F("pod_limit_memory_byte_seconds") / 3600,
                              output_field=DecimalField()) * math.pow(2, -30),
            "node_capacity_cpu_core_hours":
            F("node_capacity_cpu_core_seconds") / 3600,
            "node_capacity_memory_gigabytes":
            F("node_capacity_memory_bytes") * math.pow(2, -30),
            "node_capacity_memory_gigabyte_hours":
            ExpressionWrapper(F("node_capacity_memory_byte_seconds") / 3600,
                              output_field=DecimalField()) * math.pow(2, -30),
            "cluster_capacity_cpu_core_hours":
            F("cluster_capacity_cpu_core_seconds") / 3600,
            "cluster_capacity_memory_gigabyte_hours":
            ExpressionWrapper(F("cluster_capacity_memory_byte_seconds") / 3600,
                              output_field=DecimalField()) * math.pow(2, -30),
            "total_capacity_cpu_core_hours":
            F("cluster_capacity_cpu_core_seconds") / 3600 * 2,
            "total_capacity_memory_gigabyte_hours":
            ExpressionWrapper(
                F("cluster_capacity_memory_byte_seconds") / 3600 * 2,
                output_field=DecimalField()) * math.pow(2, -30),
            "data_source":
            Value("Pod", output_field=CharField()),
        }

        entries = OCPUsageLineItemDaily.objects.values(
            *included_fields).annotate(**annotations)

        for entry in entries:
            summary = OCPUsageLineItemDailySummary(**entry)
            summary.save()
Ejemplo n.º 2
0
def get_individual_data_for_treq(treq_ids,
                                 fund,
                                 start_date=None,
                                 end_date=None):
    start_date, end_date = check_dates(start_date, end_date)

    profdev_requested = (Funding.objects.filter(
        treq=OuterRef("pk"),
        fund=fund,
        treq__departure_date__gte=start_date,
        treq__return_date__lte=end_date,
        treq__administrative=False,
    ).values("treq__pk").annotate(
        profdev_requested=Sum("amount", filter=Q(
            fund=fund))).values("profdev_requested"))

    admin_requested = (Funding.objects.filter(
        treq=OuterRef("pk"),
        fund=fund,
        treq__departure_date__gte=start_date,
        treq__return_date__lte=end_date,
        treq__administrative=True,
    ).values("treq__pk").annotate(
        admin_requested=Sum("amount", filter=Q(
            fund=fund))).values("admin_requested"))

    profdev_spent = (ActualExpense.objects.filter(
        treq=OuterRef("pk"),
        date_paid__lte=end_date,
        date_paid__gte=start_date,
        fund=fund,
        treq__administrative=False,
    ).values("treq__pk").annotate(
        profdev_spent=Sum("total", filter=Q(
            fund=fund))).values("profdev_spent"))

    admin_spent = (ActualExpense.objects.filter(
        treq=OuterRef("pk"),
        date_paid__lte=end_date,
        date_paid__gte=start_date,
        fund=fund,
        treq__administrative=True,
    ).values("treq__pk").annotate(admin_spent=Sum("total", filter=Q(
        fund=fund))).values("admin_spent"))

    rows = TravelRequest.objects.filter(pk__in=treq_ids).annotate(
        profdev_requested=Coalesce(
            Subquery(
                profdev_requested.values("profdev_requested"),
                output_field=DecimalField(),
            ),
            Value(0),
        ),
        admin_requested=Coalesce(
            Subquery(admin_requested.values("admin_requested"),
                     output_field=DecimalField()),
            Value(0),
        ),
        profdev_spent=Coalesce(
            Subquery(profdev_spent.values("profdev_spent"),
                     output_field=DecimalField()),
            Value(0),
        ),
        admin_spent=Coalesce(
            Subquery(admin_spent.values("admin_spent"),
                     output_field=DecimalField()),
            Value(0),
        ),
    )

    return rows
Ejemplo n.º 3
0
def get_individual_data_employee(employee_ids, start_date=None, end_date=None):
    start_date, end_date = check_dates(start_date, end_date)

    profdev_requested = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=False,
        departure_date__gte=start_date,
        return_date__lte=end_date,
    ).values("traveler__pk").annotate(
        profdev_requested=Sum("funding__amount")).values("profdev_requested"))

    profdev_spent = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=False).values("traveler__pk").annotate(
            profdev_spent=Sum(
                "actualexpense__total",
                filter=Q(actualexpense__date_paid__lte=end_date)
                & Q(actualexpense__date_paid__gte=start_date),
            )).values("profdev_spent"))

    admin_requested = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=True,
        departure_date__gte=start_date,
        return_date__lte=end_date,
    ).values("traveler__pk").annotate(
        admin_requested=Sum("funding__amount")).values("admin_requested"))

    admin_spent = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=True).values("traveler__pk").annotate(admin_spent=Sum(
            "actualexpense__total",
            filter=Q(actualexpense__date_paid__lte=end_date)
            & Q(actualexpense__date_paid__gte=start_date),
        )).values("admin_spent"))

    profdev_days_away = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=False,
        departure_date__gte=start_date,
        return_date__lte=end_date,
        canceled=False,
    ).values("traveler_id").annotate(profdev_days_away=Sum("days_ooo")))
    total_requested = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        departure_date__gte=start_date,
        return_date__lte=end_date,
    ).values("traveler__pk").annotate(
        total_requested=Sum("funding__amount")).values("total_requested"))

    total_spent = (TravelRequest.objects.filter(
        traveler=OuterRef("pk")).values("traveler__pk").annotate(
            total_spent=Sum(
                "actualexpense__total",
                filter=Q(actualexpense__date_paid__lte=end_date)
                & Q(actualexpense__date_paid__gte=start_date),
            )).values("total_spent"))

    admin_days_away = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        departure_date__gte=start_date,
        return_date__lte=end_date,
        administrative=True,
        canceled=False,
    ).values("traveler_id").annotate(admin_days_away=Sum("days_ooo")))

    # final query

    rows = (Employee.objects.filter(pk__in=employee_ids).annotate(
        profdev_requested=Coalesce(
            Subquery(profdev_requested, output_field=DecimalField()),
            Value(0)),
        profdev_spent=Coalesce(
            Subquery(profdev_spent, output_field=DecimalField()), Value(0)),
        admin_requested=Coalesce(
            Subquery(admin_requested, output_field=DecimalField()), Value(0)),
        admin_spent=Coalesce(
            Subquery(admin_spent, output_field=DecimalField()), Value(0)),
        profdev_days_away=Coalesce(
            Subquery(
                profdev_days_away.values("profdev_days_away")[:1],
                output_field=IntegerField(),
            ),
            Value(0),
        ),
        total_requested=Coalesce(
            Subquery(total_requested, output_field=DecimalField()), Value(0)),
        total_spent=Coalesce(
            Subquery(total_spent, output_field=DecimalField()), Value(0)),
        admin_days_away=Coalesce(
            Subquery(
                admin_days_away.values("admin_days_away")[:1],
                output_field=IntegerField(),
            ),
            Value(0),
        ),
    ).values(
        "id",
        "profdev_requested",
        "profdev_spent",
        "admin_requested",
        "admin_spent",
        "profdev_days_away",
        "total_requested",
        "total_spent",
        "admin_days_away",
    ))
    return rows
Ejemplo n.º 4
0
class ServiceDetail(Model):
    service = ForeignKey(Service)
    brand = ForeignKey(
        Tree,
        related_name='brand',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[3][0]})
    wash_type = ForeignKey(
        Tree,
        related_name='wash_type',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[4][0]})
    sound_proofing_type = ForeignKey(
        Tree,
        related_name='sound_proofing_type',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[5][0]})
    foil_type = ForeignKey(
        Tree,
        related_name='foil_type',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[6][0]})
    foil_model_front = ForeignKey(
        Tree,
        related_name='foil_model_front',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[7][0]})
    foil_model_sides_back = ForeignKey(
        Tree,
        related_name='foil_model_sides_back',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[8][0]})
    glass_damage_size = ForeignKey(
        Tree,
        related_name='glass_damage_size',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[9][0]})
    tire_repair_type = ForeignKey(
        Tree,
        related_name='tire_repair_type',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[10][0]})
    body_damage_size = ForeignKey(
        Tree,
        related_name='body_damage_size',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[11][0]})
    sound_suit = ForeignKey(
        Tree,
        related_name='sound_suit',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[12][0]})  # 音响改装套餐
    main_light_suit = ForeignKey(
        Tree,
        related_name='main_light_suit',
        null=True,
        blank=True,
        limit_choices_to={'tree_type': Tree.tree_type_choice[13][0]})  # 大灯改装套餐
    price = DecimalField(decimal_places=0, max_digits=5)
    price_preorder = DecimalField(decimal_places=0, max_digits=5)

    def __str__(self):
        r = str(self.service) if self.service else ''

        r += self.foil_type.name + '|' if self.foil_type is not None else ''
        r += self.foil_model_front.name + '|' if self.foil_model_front is not None else ''
        r += self.foil_model_sides_back.name + '|' if self.foil_model_sides_back is not None else ''
        r += self.wash_type.name + '|' if self.wash_type is not None else ''
        r += self.glass_damage_size.name + '|' if self.glass_damage_size is not None else ''
        r += self.tire_repair_type.name + '|' if self.tire_repair_type is not None else ''
        r += self.body_damage_size.name + '|' if self.body_damage_size is not None else ''
        r += self.sound_proofing_type.name + '|' if self.sound_proofing_type is not None else ''
        r += self.sound_suit.name + '|' if self.sound_suit is not None else ''
        r += self.main_light_suit.name + '|' if self.main_light_suit is not None else ''
        return r
Ejemplo n.º 5
0
class HojaTrabajoDiarioViewSet(viewsets.ModelViewSet):
    queryset = HojaTrabajoDiario.objects.select_related(
        'tasa',
        'colaborador',
    ).prefetch_related(
        'mis_horas_trabajadas',
        'mis_horas_trabajadas',
        'mis_horas_trabajadas__literal',
        'mis_horas_trabajadas__literal__proyecto',
    ).annotate(
        costo_total=ExpressionWrapper((Coalesce(Sum('mis_horas_trabajadas__cantidad_minutos'), V(0)) / 60) * (
                F('tasa__costo') / F('tasa__nro_horas_mes_trabajadas')), output_field=DecimalField(max_digits=4)),
        cantidad_horas=ExpressionWrapper((Coalesce(Sum('mis_horas_trabajadas__cantidad_minutos'), V(0)) / 60),
                                         output_field=DecimalField(max_digits=4))
    ).all()
    serializer_class = HojaTrabajoDiarioSerializer

    def retrieve(self, request, *args, **kwargs):
        self.serializer_class = HojaTrabajoDiarioConDetalleSerializer
        return super().retrieve(request, *args, **kwargs)

    def perform_create(self, serializer):
        instance = serializer.save(creado_por=self.request.user)
        colaborador = instance.colaborador
        object, created = ColaboradorCostoMesBiable.objects.get_or_create(
            lapso=instance.fecha.replace(day=1),
            colaborador=colaborador
        )
        instance.tasa = object
        if created:
            campos_tasas = colaborador._meta.get_fields()
            for i in campos_tasas:
                if hasattr(object, i.name) and i.name not in ['mis_dias_trabajados', 'id', 'colaborador']:
                    valor = getattr(colaborador, i.name)
                    setattr(object, i.name, valor)
            object.save()
            object.calcular_costo_total()

        instance.save()

    @list_route(http_method_names=['get', ])
    def listar_x_fechas(self, request):
        fecha_inicial = request.GET.get('fecha_inicial')
        fecha_final = request.GET.get('fecha_final')
        qs = None

        gestiona_otros = request.user.has_perm('mano_obra.para_otros_hojatrabajodiario')
        listar_autogestionados = request.user.has_perm('mano_obra.list_hojatrabajodiario_solo_autogestionados')

        if gestiona_otros:
            qs = self.queryset
        elif listar_autogestionados:
            qs = self.queryset.filter(colaborador__autogestion_horas_trabajadas=True)
        else:
            if hasattr(request.user, 'colaborador') and not gestiona_otros:
                colaborador = request.user.colaborador
                if colaborador.en_proyectos and colaborador.autogestion_horas_trabajadas:
                    qs = self.queryset.filter(colaborador=colaborador)

        if fecha_final and fecha_final and qs:
            qs = qs.filter(fecha__gte=fecha_inicial, fecha__lte=fecha_final)

        serializer = self.get_serializer(qs, many=True)
        return Response(serializer.data)
Ejemplo n.º 6
0
class Category(Model):
    """Categories info (name, amount), related to Event."""
    name = CharField(max_length=256)
    amount = DecimalField(max_digits=20, decimal_places=2)
    event = ForeignKey(Event, on_delete=CASCADE)
Ejemplo n.º 7
0
def summary(request):
    pur_reqs = Request.objects.all()
    in_format = "%b %d, %Y"
    db_format = "%Y-%m-%d"

    earliest_req_time = pur_reqs.earliest('timestamp').timestamp
    # Date filtering
    if "dr" in request.GET and " - " in request.GET["dr"]:
        st, et = request.GET["dr"].split(" - ")
        if validate_date_input(st, in_format) and validate_date_input(et, in_format):
            st = datetime.strptime(st, in_format)
            et = datetime.strptime(et, in_format) + timedelta(days=1)

            start_time = st
            end_time = et

            st = st.astimezone(pytz.timezone(settings.TIME_ZONE)).strftime(db_format)
            et = et.astimezone(pytz.timezone(settings.TIME_ZONE)).strftime(db_format)

            pur_reqs = pur_reqs.filter((Q(timestamp__gte=st) | Q(approved_timestamp__gte=st) |
                                        Q(order_timestamp__gte=st) | Q(delivery_timestamp__gte=st)) &
                                       (Q(timestamp__lte=et) | Q(approved_timestamp__lte=et) |
                                        Q(order_timestamp__lte=et) | Q(delivery_timestamp__lte=et)))
        else:
            start_time = earliest_req_time
            end_time = timezone.now()
    else:
        start_time = earliest_req_time
        end_time = timezone.now()


    # Data generation for the chart
    activity = []
    spending = []

    range_width = end_time - start_time
    print(range_width)
    if range_width <= timedelta(days=1):
        interval = "hour"
        tt_format = "h:mm a"
        start_time = datetime(start_time.year, start_time.month, start_time.day, hour=start_time.hour, minute=0,
                              second=0, microsecond=0, tzinfo=start_time.tzinfo)
        round_up = 0 if end_time.minute == 0 and end_time.second == 0 and end_time.microsecond == 0 else 1
        end_time = datetime(end_time.year, end_time.month, end_time.day, hour=end_time.hour + round_up, minute=0,
                            second=0, microsecond=0, tzinfo=end_time.tzinfo)

        range_width = end_time - start_time
        num_bins = int((range_width.days * 86400 + range_width.seconds) / 3600)
    elif range_width <= timedelta(days=6):
        interval = "day"
        tt_format = "M/D h:mm a"
        num_days = range_width.days

        start_time = datetime(start_time.year, start_time.month, start_time.day,
                              hour=int(start_time.hour/num_days)*num_days, minute=0, second=0, microsecond=0,
                              tzinfo=start_time.tzinfo)
        round_up = 0 if end_time.minute == 0 and end_time.second == 0 and end_time.microsecond == 0 else num_days
        end_time = datetime(end_time.year, end_time.month, end_time.day,
                            hour=int(end_time.hour/num_days)*num_days + round_up, minute=0, second=0, microsecond=0,
                            tzinfo=end_time.tzinfo)

        range_width = end_time - start_time
        num_bins = int((range_width.days * 86400 + range_width.seconds) / (3600 * num_days))
    elif range_width <= timedelta(weeks=3):
        interval = "day"
        tt_format = "M/D"
        start_time = datetime(start_time.year, start_time.month, start_time.day, tzinfo=start_time.tzinfo)
        round_up = 0 if end_time.minute == 0 and end_time.second == 0 and end_time.microsecond == 0 else 2
        end_time = datetime(end_time.year, end_time.month, end_time.day, tzinfo=end_time.tzinfo)

        range_width = end_time - start_time
        num_bins = range_width.days
    elif end_time <= start_time + relativedelta(months=+6):
        interval = "week"
        tt_format = "[Week of] M/D"
        start_time = datetime(start_time.year, start_time.month, start_time.day)
        start_time = start_time - timedelta(days=start_time.isoweekday() % 7)

        end_time = datetime(end_time.year, end_time.month, end_time.day)
        end_time = end_time + timedelta(days=7 - (end_time.isoweekday() % 7))

        range_width = end_time - start_time
        num_bins = int(range_width.days / 7)
    elif end_time <= start_time + relativedelta(years=+2):
        interval = "month"
        tt_format = "MMMM"
        # For up to two years, do by month
        for n in range(12 * (end_time.year - start_time.year) + end_time.month - start_time.month + 1):
            bin_start = datetime(start_time.year, start_time.month, 1) + (n * relativedelta(months=+1))
            bin_end = bin_start + relativedelta(months=+1)

            m_activity, m_spending = gen_dt_bin_data(pur_reqs, bin_start, bin_end)
            activity.append(m_activity)
            spending.append(m_spending)
        num_bins = 0
    else:
        interval = "year"
        tt_format = "YYYY"
        for n in range(end_time.year - start_time.year + 1):
            bin_start = datetime(start_time.year, 1, 1) + relativedelta(years=+n)
            bin_end = bin_start + relativedelta(years=+1)

            m_activity, m_spending = gen_dt_bin_data(pur_reqs, bin_start, bin_end)
            activity.append(m_activity)
            spending.append(m_spending)
        num_bins = 0

    if num_bins:
        bin_width = (end_time - start_time) / num_bins
        for n in range(num_bins):
            bin_start = start_time + (n * bin_width)
            bin_end = bin_start + bin_width

            bin_activity, bin_spending = gen_dt_bin_data(pur_reqs, bin_start, bin_end)
            activity.append(bin_activity)
            spending.append(bin_spending)

    # Bottom summary data
    app_reqs = pur_reqs.filter(approved=True)
    team_data = {
        'num_reqs': pur_reqs.count(),
        'num_app': app_reqs.count(),
        'total_req': pur_reqs.aggregate(total=Sum(F('quantity') * F('cost'), output_field=DecimalField()))["total"],
        'total_app': app_reqs.aggregate(total=Sum(F('quantity') * F('cost'), output_field=DecimalField()))["total"],
    }
    if team_data['total_req'] is None:
        team_data['total_req'] = 0
    if team_data['total_app'] is None:
        team_data['total_app'] = 0

    user_reqs = pur_reqs.filter(author=request.user)
    user_app_reqs = user_reqs.filter(approved=True)
    user_data = {
        'num_reqs': user_reqs.count(),
        'num_app': user_app_reqs.count(),
        'total_req': user_reqs.aggregate(total=Sum(F('quantity') * F('cost'), output_field=DecimalField()))["total"],
        'total_app': user_app_reqs.aggregate(total=Sum(F('quantity') * F('cost'), output_field=DecimalField()))["total"],
    }
    if user_data['total_req'] is None:
        user_data['total_req'] = 0
    if user_data['total_app'] is None:
        user_data['total_app'] = 0

    context = {
        'activity': activity,
        'spending': spending,
        'team_data': team_data,
        'user_data': user_data,
        'earliest_req': earliest_req_time.strftime(db_format),
        'start_date': start_time.strftime(db_format),
        'end_date': end_time.strftime(db_format),
        'interval': interval,
        'tt_format': tt_format,
        'theme_color': settings.THEME_COLOR,
    }
    return render(request, "purchaseRequests/summary.html", context)
Ejemplo n.º 8
0
 def add_budget(self):
     return self.annotate(
         budget=ExpressionWrapper(Round(
             0.933 * F('after_repair_value') - F('purchase_price') -
             F('profit') - 400.00, 2),
                                  output_field=DecimalField()))
Ejemplo n.º 9
0
 def add_potential_profit(self):
     return self.add_total_spent().annotate(
         potential_profit=ExpressionWrapper(Round(
             0.933 * F('after_repair_value') - F('purchase_price') -
             F('total_spent') - 400.00, 2),
                                            output_field=DecimalField()))
Ejemplo n.º 10
0
 def add_total_paid(self):
     return self.annotate(total_paid1=Coalesce(
         Subquery(Request_Payment.objects.filter(
             job_id=OuterRef('pk'), approved=True).values('job_id').
                  order_by().annotate(sum=Sum('amount')).values('sum')[:1],
                  output_field=DecimalField()), 0))
Ejemplo n.º 11
0
 def add_balance(self):
     return self.add_total_paid().annotate(balance1=ExpressionWrapper(
         F('start_amount') - F('total_paid1'), output_field=DecimalField()))
Ejemplo n.º 12
0
    def get(self, request, list_id):
        """display a book list"""
        book_list = get_object_or_404(models.List, id=list_id)
        if not book_list.visible_to_user(request.user):
            return HttpResponseNotFound()

        if is_api_request(request):
            return ActivitypubResponse(book_list.to_activity(**request.GET))

        query = request.GET.get("q")
        suggestions = None

        # sort_by shall be "order" unless a valid alternative is given
        sort_by = request.GET.get("sort_by", "order")
        if sort_by not in ("order", "title", "rating"):
            sort_by = "order"

        # direction shall be "ascending" unless a valid alternative is given
        direction = request.GET.get("direction", "ascending")
        if direction not in ("ascending", "descending"):
            direction = "ascending"

        directional_sort_by = {
            "order": "order",
            "title": "book__title",
            "rating": "average_rating",
        }[sort_by]
        if direction == "descending":
            directional_sort_by = "-" + directional_sort_by

        items = book_list.listitem_set
        if sort_by == "rating":
            items = items.annotate(average_rating=Avg(
                Coalesce("book__review__rating", 0.0),
                output_field=DecimalField(),
            ))
        items = items.filter(approved=True).order_by(directional_sort_by)

        paginated = Paginator(items, PAGE_LENGTH)

        if query and request.user.is_authenticated:
            # search for books
            suggestions = connector_manager.local_search(
                query,
                raw=True,
                filters=[~Q(parent_work__editions__in=book_list.books.all())],
            )
        elif request.user.is_authenticated:
            # just suggest whatever books are nearby
            suggestions = request.user.shelfbook_set.filter(~Q(
                book__in=book_list.books.all()))
            suggestions = [s.book for s in suggestions[:5]]
            if len(suggestions) < 5:
                suggestions += [
                    s.default_edition for s in models.Work.objects.filter(
                        ~Q(editions__in=book_list.books.all()), ).order_by(
                            "-updated_date")
                ][:5 - len(suggestions)]

        page = paginated.get_page(request.GET.get("page"))
        data = {
            "list":
            book_list,
            "items":
            page,
            "page_range":
            paginated.get_elided_page_range(page.number,
                                            on_each_side=2,
                                            on_ends=1),
            "pending_count":
            book_list.listitem_set.filter(approved=False).count(),
            "suggested_books":
            suggestions,
            "list_form":
            forms.ListForm(instance=book_list),
            "query":
            query or "",
            "sort_form":
            forms.SortListForm({
                "direction": direction,
                "sort_by": sort_by
            }),
        }
        return TemplateResponse(request, "lists/list.html", data)
Ejemplo n.º 13
0
 def __init__(self, provider, report_type):
     """Constructor."""
     self._mapping = [
         {
             'provider':
             'AWS',
             'alias':
             'account_alias__account_alias',
             'annotations': {
                 'account': 'usage_account_id',
                 'service': 'product_code',
                 'az': 'availability_zone'
             },
             'end_date':
             'usage_end',
             'filters': {
                 'account': [{
                     'field': 'account_alias__account_alias',
                     'operation': 'icontains',
                     'composition_key': 'account_filter'
                 }, {
                     'field': 'usage_account_id',
                     'operation': 'icontains',
                     'composition_key': 'account_filter'
                 }],
                 'service': {
                     'field': 'product_code',
                     'operation': 'icontains'
                 },
                 'az': {
                     'field': 'availability_zone',
                     'operation': 'icontains'
                 },
                 'region': {
                     'field': 'region',
                     'operation': 'icontains'
                 },
                 'product_family': {
                     'field': 'product_family',
                     'operation': 'icontains'
                 }
             },
             'group_by_options':
             ['service', 'account', 'region', 'az', 'product_family'],
             'tag_column':
             'tags',
             'report_type': {
                 'costs': {
                     'aggregates': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Sum(Value(0, output_field=DecimalField())),
                         'markup_cost':
                         Sum(
                             Coalesce(F('markup_cost'),
                                      Value(0,
                                            output_field=DecimalField()))),
                     },
                     'aggregate_key':
                     'unblended_cost',
                     'annotations': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Value(0, output_field=DecimalField()),
                         'markup_cost':
                         Sum(
                             Coalesce(F('markup_cost'),
                                      Value(0,
                                            output_field=DecimalField()))),
                         'cost_units':
                         Coalesce(Max('currency_code'), Value('USD'))
                     },
                     'delta_key': {
                         'cost':
                         Sum(
                             ExpressionWrapper(F('unblended_cost') +
                                               F('markup_cost'),
                                               output_field=DecimalField()))
                     },
                     'filter': [{}],
                     'cost_units_key':
                     'currency_code',
                     'cost_units_fallback':
                     'USD',
                     'sum_columns': [
                         'cost', 'infrastructure_cost', 'derived_cost',
                         'markup_cost'
                     ],
                     'default_ordering': {
                         'cost': 'desc'
                     },
                 },
                 'instance_type': {
                     'aggregates': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Sum(Value(0, output_field=DecimalField())),
                         'markup_cost':
                         Sum('markup_cost'),
                         'count':
                         Sum(Value(0, output_field=DecimalField())),
                         'usage':
                         Sum('usage_amount'),
                     },
                     'aggregate_key':
                     'usage_amount',
                     'annotations': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Value(0, output_field=DecimalField()),
                         'markup_cost':
                         Sum(
                             Coalesce(F('markup_cost'),
                                      Value(0,
                                            output_field=DecimalField()))),
                         'cost_units':
                         Coalesce(Max('currency_code'), Value('USD')),
                         # The summary table already already has counts
                         'count':
                         Max('resource_count'),
                         'count_units':
                         Value('instances', output_field=CharField()),
                         'usage':
                         Sum('usage_amount'),
                         'usage_units':
                         Coalesce(Max('unit'), Value('Hrs'))
                     },
                     'delta_key': {
                         'usage': Sum('usage_amount')
                     },
                     'filter': [
                         {
                             'field': 'instance_type',
                             'operation': 'isnull',
                             'parameter': False
                         },
                     ],
                     'group_by': ['instance_type'],
                     'cost_units_key':
                     'currency_code',
                     'cost_units_fallback':
                     'USD',
                     'usage_units_key':
                     'unit',
                     'usage_units_fallback':
                     'Hrs',
                     'count_units_fallback':
                     'instances',
                     'sum_columns': [
                         'usage', 'cost', 'infrastructure_cost',
                         'derived_cost', 'markup_cost', 'count'
                     ],
                     'default_ordering': {
                         'usage': 'desc'
                     },
                 },
                 'storage': {
                     'aggregates': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Sum(Value(0, output_field=DecimalField())),
                         'markup_cost':
                         Sum('markup_cost'),
                         'usage':
                         Sum('usage_amount'),
                     },
                     'aggregate_key':
                     'usage_amount',
                     'annotations': {
                         'cost':
                         Sum(
                             Coalesce(F('unblended_cost'),
                                      Value(0,
                                            output_field=DecimalField())) +
                             Coalesce(F('markup_cost'),
                                      Value(0, output_field=DecimalField()))
                         ),
                         'infrastructure_cost':
                         Sum('unblended_cost'),
                         'derived_cost':
                         Value(0, output_field=DecimalField()),
                         'markup_cost':
                         Sum(
                             Coalesce(F('markup_cost'),
                                      Value(0,
                                            output_field=DecimalField()))),
                         'cost_units':
                         Coalesce(Max('currency_code'), Value('USD')),
                         'usage':
                         Sum('usage_amount'),
                         'usage_units':
                         Coalesce(Max('unit'), Value('GB-Mo'))
                     },
                     'delta_key': {
                         'usage': Sum('usage_amount')
                     },
                     'filter': [{
                         'field': 'product_family',
                         'operation': 'contains',
                         'parameter': 'Storage'
                     }, {
                         'field': 'unit',
                         'operation': 'exact',
                         'parameter': 'GB-Mo'
                     }],
                     'cost_units_key':
                     'currency_code',
                     'cost_units_fallback':
                     'USD',
                     'usage_units_key':
                     'unit',
                     'usage_units_fallback':
                     'GB-Mo',
                     'sum_columns': [
                         'usage', 'cost', 'infrastructure_cost',
                         'derived_cost', 'markup_cost'
                     ],
                     'default_ordering': {
                         'usage': 'desc'
                     },
                 },
                 'tags': {
                     'default_ordering': {
                         'cost': 'desc'
                     },
                 },
             },
             'start_date':
             'usage_start',
             'tables': {
                 'query': AWSCostEntryLineItemDailySummary,
             },
         },
     ]
     super().__init__(provider, report_type)
Ejemplo n.º 14
0
class Diapositive(PublishedModel):
    # TODO: Pouvoir paramétrer :
    #       couleur de fond, placement vertical, largeur du texte.
    # TODO: Ajuster automatiquement h1, h2, h3, ou h4 en fonction
    #       du nombre de caractères du titre court.

    # Objet lié
    content_type = ForeignKey(
        ContentType,
        limit_choices_to={
            'model__in': _get_valid_modelnames_func(autorites_only=False)
        },
        verbose_name=_('type d’objet lié'),
        on_delete=CASCADE)
    object_id = PositiveIntegerField(_('identifiant de l’objet lié'))
    content_object = GenericForeignKey()
    content_object.short_description = _('objet lié')
    # Contenu
    title = CharField(_('titre'), max_length=70)
    subtitle = CharField(_('sous-titre'), max_length=100, blank=True)
    ALIGNEMENT_CHOICES = (
        ('text-left', _('Gauche')),
        ('text-center', _('Centre')),
        ('text-right', _('Droite')),
    )
    text_align = CharField(_('alignement du texte'),
                           max_length=11,
                           choices=ALIGNEMENT_CHOICES,
                           default='text-left')
    text_background = BooleanField(
        _('cadre derrière le texte'),
        default=False,
        help_text=_('Ajoute un cadre semi-transparent derrière le texte '
                    'pour faciliter la lecture.'))
    image = ImageField(_('image'), upload_to='accueil')
    cropping = ImageRatioField('image',
                               '450x450',
                               free_crop=True,
                               size_warning=True,
                               verbose_name=_('découpage de l’image'))
    image_align = CharField(_('alignement de l’image'),
                            max_length=11,
                            choices=ALIGNEMENT_CHOICES,
                            default='text-right')
    OPACITIES = [(Decimal(str(k)), v) for k, v in (
        (1.0, _('Opaque')),
        (0.9, _('90 %')),
        (0.8, _('80 %')),
        (0.7, _('70 %')),
        (0.6, _('60 %')),
        (0.5, _('50 %')),
        (0.4, _('40 %')),
        (0.3, _('30 %')),
        (0.2, _('20 %')),
        (0.1, _('10 %')),
    )]
    opacity = DecimalField(_('opacité'),
                           max_digits=2,
                           decimal_places=1,
                           default=0.6,
                           choices=OPACITIES)
    position = PositiveSmallIntegerField(_('position'),
                                         default=get_default_position)

    SLIDER_LG_WIDTH = 1140
    SLIDER_MD_WIDTH = 940
    SLIDER_SM_WIDTH = 720
    SLIDER_HEIGHT = 450
    SLIDER_LG_RATIO = SLIDER_LG_WIDTH / SLIDER_HEIGHT
    SLIDER_MD_RATIO = SLIDER_MD_WIDTH / SLIDER_HEIGHT
    SLIDER_SM_RATIO = SLIDER_SM_WIDTH / SLIDER_HEIGHT

    class Meta(object):
        verbose_name = _('diapositive')
        verbose_name_plural = _('diapositives')
        ordering = ('position', )

    def __str__(self):
        return self.title

    def box(self, slider_ratio):
        x1, y1, x2, y2 = map(int, self.cropping.split(','))
        w, h = self.size(slider_ratio, scale_down=False)
        x1 += ((x2 - x1) - w) // 2
        return ','.join(map(str, (x1, y1, x1 + w, y1 + h)))

    def size(self, slider_ratio, scale_down=True):
        x1, y1, x2, y2 = map(int, self.cropping.split(','))
        w = x2 - x1
        h = y2 - y1
        if scale_down and h > self.SLIDER_HEIGHT:
            w = w * self.SLIDER_HEIGHT // h
            h = self.SLIDER_HEIGHT
        if w / h > slider_ratio:
            w = int(h * slider_ratio)
        return w, h

    def box_lg(self):
        return self.box(self.SLIDER_LG_RATIO)

    def box_md(self):
        return self.box(self.SLIDER_MD_RATIO)

    def box_sm(self):
        return self.box(self.SLIDER_SM_RATIO)

    def size_lg(self):
        return self.size(self.SLIDER_LG_RATIO)

    def size_md(self):
        return self.size(self.SLIDER_MD_RATIO)

    def size_sm(self):
        return self.size(self.SLIDER_SM_RATIO)

    def thumbnail_instance(self, size=None, box=None):
        if size is None:
            size = (150, 150)
        if box is None:
            box = self.cropping
        return get_thumbnailer(self.image).get_thumbnail({
            'size': size,
            'box': box,
        })

    def thumbnail(self):
        thumbnail_instance = self.thumbnail_instance()
        return (f'<img src="{thumbnail_instance.url}" '
                f'style="width: {thumbnail_instance.width}; '
                f'height: {thumbnail_instance.height};" />')

    thumbnail.short_description = _('miniature')
    thumbnail.allow_tags = True
Ejemplo n.º 15
0
 def add_value(self):
     return self.annotate(value=ExpressionWrapper(
         F("price") * F("amount"), output_field=DecimalField()))
Ejemplo n.º 16
0
    def get_context_data(self, **kwargs):
        context = super(PrincipalView, self).get_context_data(**kwargs)            
        usr= usuario_actual(self.request)
        
        fecha_desde = ultimo_anio()
        fecha_hoy = hoy()
        pvs = pto_vta_habilitados_list(self.request)
        empresas = empresas_habilitadas(self.request)
        
        comprobantes = cpb_comprobante.objects.filter(estado__in=[1,2]).filter(fecha_cpb__range=[fecha_desde, fecha_hoy],empresa=empresa_actual(self.request))
        
        ventas = comprobantes.filter(cpb_tipo__compra_venta='V',pto_vta__in=pvs,cpb_tipo__tipo__in=[1,2,3,9,21,22,23])
        total_ventas_mensual = ventas.filter(fecha_cpb__range=[inicioMes(), fecha_hoy])
        total_ventas_mensual = total_ventas_mensual.aggregate(sum=Sum(F('importe_total')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0 
        total_ventas = ventas.aggregate(sum=Sum(F('importe_total')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0 
        context['total_ventas'] = total_ventas            
        context['total_ventas_mensual'] = total_ventas_mensual


        deuda_cobrar_total = ventas.aggregate(sum=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0        
        deuda_cobrar_mensual = ventas.filter(fecha_cpb__range=[inicioMes(), fecha_hoy]).aggregate(sum=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0                    
        context['deuda_cobrar_total'] = deuda_cobrar_total
        context['deuda_cobrar_mensual'] = deuda_cobrar_mensual
        
        porc_cobrar_total = 0
        porc_cobrar_mensual = 0
        if total_ventas > 0:
            porc_cobrar_total=(deuda_cobrar_total/total_ventas)*100                        
        if total_ventas_mensual > 0:
            porc_cobrar_mensual=(deuda_cobrar_mensual/total_ventas_mensual)*100    
        context['porc_cobrar_mensual'] = porc_cobrar_mensual
        context['porc_cobrar_total'] = porc_cobrar_total
        
        compras = comprobantes.filter(cpb_tipo__compra_venta='C',cpb_tipo__tipo__in=[1,2,3,9,21,22,23])
        total_compras = compras.aggregate(sum=Sum(F('importe_total')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0 
        context['total_compras'] = total_compras
        total_compras_mensual = compras.filter(fecha_cpb__range=[inicioMes(), fecha_hoy]).aggregate(sum=Sum(F('importe_total')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0 
        context['total_compras_mensual'] = total_compras_mensual
                   
        deuda_pagar_total = compras.aggregate(sum=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0      
        deuda_pagar_mensual = compras.filter(fecha_cpb__range=[inicioMes(), fecha_hoy]).aggregate(sum=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0      
        context['deuda_pagar_total'] = deuda_pagar_total            
        context['deuda_pagar_mensual'] = deuda_pagar_mensual            
        
        porc_pagar_total = 0
        porc_pagar_mensual = 0
        if total_compras > 0:
            porc_pagar_total=(deuda_pagar_total/total_compras)*100                        
        if total_compras_mensual > 0:
            porc_pagar_mensual=(deuda_pagar_mensual/total_compras_mensual)*100    
        context['porc_pagar_total'] = porc_pagar_total
        context['porc_pagar_mensual'] = porc_pagar_mensual
        
        context['ultimas_ventas'] = ventas.filter(cpb_tipo__id__in=[1,3,5,14]).order_by('-fecha_cpb','-fecha_creacion','-id').select_related('entidad','cpb_tipo','estado')[:10]
        context['ultimas_compras'] = compras.filter(cpb_tipo__id__in=[2,4,6,18],estado__in=[1,2]).order_by('-fecha_cpb','-fecha_creacion','-id').select_related('entidad','cpb_tipo','estado')[:10]
        # context['ultimos_presup'] = comprobantes.filter(cpb_tipo__id=11).order_by('-fecha_cpb','-fecha_creacion','-id').select_related('entidad','cpb_tipo','estado','presup_aprobacion','presup_aprobacion')[:10]
        
        if usr.tipoUsr==0:
            context['tareas'] = gral_tareas.objects.filter(empresa__id__in=empresas).select_related('usuario_creador','usuario_asignado').order_by('-fecha','-fecha_creacion','-id')                
        else:    
            context['tareas'] = gral_tareas.objects.filter(empresa__id__in=empresas).filter(Q(usuario_asignado=usr)|Q(usuario_asignado__isnull=True)).select_related('usuario_creador','usuario_asignado').order_by('-fecha','-fecha_creacion','-id')        
        
        
        comprobantes = comprobantes.filter(cpb_tipo__tipo__in=[1,2,3,9,21,22,23]).distinct().annotate(m=Month('fecha_cpb'),anio=Year('fecha_cpb')).order_by(F('anio'),F('m')).values('m','anio')        

        meses_cpbs = comprobantes.values_list('m','anio')

        meses = list()
        import locale        
        locale.setlocale(locale.LC_ALL, '')
        

        ventas_deuda = list()
        ventas_pagos = list()
        compras_deuda = list()
        compras_pagos = list()
        
        for m in meses_cpbs:                        
            meses.append(MESES[m[0]-1][1]+' '+str(m[1])[2:4]+"'")
            ventas = comprobantes.filter(cpb_tipo__compra_venta='V',anio=m[1],m=m[0]).annotate(pendiente=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'),output_field=DecimalField()),saldado=Sum((F('importe_total')-F('saldo'))*F('cpb_tipo__signo_ctacte'),output_field=DecimalField())).order_by(F('anio'),F('m'))
            compras = comprobantes.filter(cpb_tipo__compra_venta='C',anio=m[1],m=m[0]).annotate(pendiente=Sum(F('saldo')*F('cpb_tipo__signo_ctacte'),output_field=DecimalField()),saldado=Sum((F('importe_total')-F('saldo'))*F('cpb_tipo__signo_ctacte'),output_field=DecimalField())).order_by(F('anio'),F('m'))
            if ventas:
                ventas_deuda.append(ventas[0].get('pendiente',Decimal(0.00)))
                ventas_pagos.append(ventas[0].get('saldado',Decimal(0.00)))
            else:
                ventas_deuda.append(Decimal(0.00))
                ventas_pagos.append(Decimal(0.00))
            
            if compras:
                compras_deuda.append(compras[0].get('pendiente',Decimal(0.00)))
                compras_pagos.append(compras[0].get('saldado',Decimal(0.00)))            
            else:
                compras_deuda.append(Decimal(0.00))
                compras_pagos.append(Decimal(0.00))
            
        context['meses']= json.dumps(meses,cls=DecimalEncoder)
       
        context['ventas_deuda']=  json.dumps(ventas_deuda,cls=DecimalEncoder)
        context['ventas_pagos']=  json.dumps(ventas_pagos,cls=DecimalEncoder)
        context['compras_deuda']= json.dumps(compras_deuda,cls=DecimalEncoder)
        context['compras_pagos']= json.dumps(compras_pagos,cls=DecimalEncoder)

        context['hoy'] = fecha_hoy
        context['fecha_desde'] = fecha_desde

        productos_vendidos = cpb_comprobante_detalle.objects.filter(cpb_comprobante__pto_vta__in=pvs,cpb_comprobante__cpb_tipo__compra_venta='V',cpb_comprobante__cpb_tipo__tipo__in=[1,2,3,9,21,22,23],cpb_comprobante__estado__in=[1,2],cpb_comprobante__fecha_cpb__range=[fecha_desde, fecha_hoy])
        productos_vendidos_total = productos_vendidos.aggregate(sum=Sum(F('importe_total')*F('cpb_comprobante__cpb_tipo__signo_ctacte'), output_field=DecimalField()))['sum'] or 0 
        productos_vendidos = productos_vendidos.values('producto__nombre').annotate(tot=Sum(F('importe_total')*F('cpb_comprobante__cpb_tipo__signo_ctacte'),output_field=DecimalField())).order_by('-tot')[:10]
        context['productos_vendidos']= productos_vendidos 
        
        vars_sistema = settings

        return context
Ejemplo n.º 17
0
class Review(Model):
    user = ForeignKey(User, on_delete=CASCADE)
    content = CharField(max_length=500, null=False, blank=False)
    product = ForeignKey(Product, on_delete=CASCADE)
    rate = DecimalField(decimal_places=1,max_digits=2, null=True, blank=True)
Ejemplo n.º 18
0
    def __init__(self, provider, report_type):
        """Constructor."""
        self._mapping = [{
            "provider":
            Provider.PROVIDER_AZURE,
            "alias":
            "subscription_guid",  # FIXME: probably wrong
            "annotations": {},
            "end_date":
            "costentrybill__billing_period_end",
            "filters": {
                "subscription_guid": [{
                    "field": "subscription_guid",
                    "operation": "icontains",
                    "composition_key": "account_filter"
                }],
                "service_name": {
                    "field": "service_name",
                    "operation": "icontains"
                },
                "resource_location": {
                    "field": "resource_location",
                    "operation": "icontains"
                },
                "instance_type": {
                    "field": "instance_type",
                    "operation": "icontains"
                },
            },
            "group_by_options": [
                "service_name", "subscription_guid", "resource_location",
                "instance_type"
            ],
            "tag_column":
            "tags",
            "report_type": {
                "costs": {
                    "aggregates": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_markup":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_total":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                    },
                    "aggregate_key": "pretax_cost",
                    "annotations": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Value(0, output_field=DecimalField()),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Value(0, output_field=DecimalField()),
                        "sup_usage":
                        Value(0, output_field=DecimalField()),
                        "sup_markup":
                        Value(0, output_field=DecimalField()),
                        "sup_total":
                        Value(0, output_field=DecimalField()),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Value(0, output_field=DecimalField()),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_units":
                        Coalesce(Max("currency"), Value("USD")),
                        "source_uuid":
                        ArrayAgg(F("source_uuid"),
                                 filter=Q(source_uuid__isnull=False),
                                 distinct=True),
                    },
                    "delta_key": {
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField())))
                    },
                    "filter": [{}],
                    "cost_units_key": "currency",
                    "cost_units_fallback": "USD",
                    "sum_columns": ["cost_total", "sup_total", "infra_total"],
                    "default_ordering": {
                        "cost_total": "desc"
                    },
                },
                "instance_type": {
                    "aggregates": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_markup":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_total":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "count":
                        Sum(Value(0, output_field=DecimalField())),
                        "usage":
                        Sum("usage_quantity"),
                    },
                    "aggregate_key":
                    "usage_quantity",
                    "annotations": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Value(0, output_field=DecimalField()),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Value(0, output_field=DecimalField()),
                        "sup_usage":
                        Value(0, output_field=DecimalField()),
                        "sup_markup":
                        Value(0, output_field=DecimalField()),
                        "sup_total":
                        Value(0, output_field=DecimalField()),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Value(0, output_field=DecimalField()),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_units":
                        Coalesce(Max("currency"), Value("USD")),
                        "count":
                        Max("instance_count"),
                        "count_units":
                        Value("instance_types", output_field=CharField()),
                        "usage":
                        Sum("usage_quantity"),
                        "usage_units":
                        Coalesce(Max("unit_of_measure"), Value("Hrs")),
                        "source_uuid":
                        ArrayAgg(F("source_uuid"),
                                 filter=Q(source_uuid__isnull=False),
                                 distinct=True),
                    },
                    "delta_key": {
                        "usage": Sum("usage_quantity")
                    },
                    "filter": [
                        {
                            "field": "instance_type",
                            "operation": "isnull",
                            "parameter": False
                        },
                        {
                            "field": "unit_of_measure",
                            "operation": "exact",
                            "parameter": "Hrs"
                        },
                    ],
                    "group_by": ["instance_type"],
                    "cost_units_key":
                    "currency",
                    "cost_units_fallback":
                    "USD",
                    "usage_units_key":
                    "unit_of_measure",
                    "usage_units_fallback":
                    "Hrs",
                    "count_units_fallback":
                    "instances",
                    "sum_columns": [
                        "usage", "cost_total", "sup_total", "infra_total",
                        "count"
                    ],
                    "default_ordering": {
                        "usage": "desc"
                    },
                },
                "storage": {
                    "aggregates": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_markup":
                        Sum(Value(0, output_field=DecimalField())),
                        "sup_total":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Sum(Value(0, output_field=DecimalField())),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "usage":
                        Sum("usage_quantity"),
                    },
                    "aggregate_key":
                    "usage_quantity",
                    "annotations": {
                        "infra_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "infra_raw":
                        Sum("pretax_cost"),
                        "infra_usage":
                        Value(0, output_field=DecimalField()),
                        "infra_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "sup_raw":
                        Value(0, output_field=DecimalField()),
                        "sup_usage":
                        Value(0, output_field=DecimalField()),
                        "sup_markup":
                        Value(0, output_field=DecimalField()),
                        "sup_total":
                        Value(0, output_field=DecimalField()),
                        "cost_total":
                        Sum(
                            Coalesce(F("pretax_cost"),
                                     Value(0, output_field=DecimalField())) +
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_raw":
                        Sum("pretax_cost"),
                        "cost_usage":
                        Value(0, output_field=DecimalField()),
                        "cost_markup":
                        Sum(
                            Coalesce(F("markup_cost"),
                                     Value(0, output_field=DecimalField()))),
                        "cost_units":
                        Coalesce(Max("currency"), Value("USD")),
                        "usage":
                        Sum("usage_quantity"),
                        "usage_units":
                        Coalesce(Max("unit_of_measure"), Value("GB-Mo")),
                        "source_uuid":
                        ArrayAgg(F("source_uuid"),
                                 filter=Q(source_uuid__isnull=False),
                                 distinct=True),
                    },
                    "delta_key": {
                        "usage": Sum("usage_quantity")
                    },
                    "filter": [
                        {
                            "field": "service_name",
                            "operation": "icontains",
                            "parameter": "Storage"
                        },
                        {
                            "field": "unit_of_measure",
                            "operation": "exact",
                            "parameter": "GB-Mo"
                        },
                    ],
                    "cost_units_key":
                    "currency",
                    "cost_units_fallback":
                    "USD",
                    "usage_units_key":
                    "unit_of_measure",
                    "usage_units_fallback":
                    "GB-Mo",
                    "sum_columns":
                    ["usage", "cost_total", "sup_total", "infra_total"],
                    "default_ordering": {
                        "usage": "desc"
                    },
                },
                "tags": {
                    "default_ordering": {
                        "cost_total": "desc"
                    }
                },
            },
            "start_date":
            "costentrybill__billing_period_start",
            "tables": {
                "query": AzureCostEntryLineItemDailySummary
            },
        }]

        self.views = {
            "costs": {
                "default": AzureCostSummary,
                ("subscription_guid", ): AzureCostSummaryByAccount,
                ("resource_location", ): AzureCostSummaryByLocation,
                ("resource_location", "subscription_guid"):
                AzureCostSummaryByLocation,
                ("service_name", ): AzureCostSummaryByService,
                ("service_name", "subscription_guid"):
                AzureCostSummaryByService,
            },
            "instance_type": {
                "default": AzureComputeSummary,
                ("instance_type", ): AzureComputeSummary,
                ("instance_type", "subscription_guid"): AzureComputeSummary,
                ("subscription_guid", ): AzureComputeSummary,
            },
            "storage": {
                "default": AzureStorageSummary,
                ("subscription_guid", ): AzureStorageSummary
            },
            "database": {
                "default": AzureDatabaseSummary,
                ("service_name", ): AzureDatabaseSummary,
                ("service_name", "subscription_guid"): AzureDatabaseSummary,
                ("subscription_guid", ): AzureDatabaseSummary,
            },
            "network": {
                "default": AzureNetworkSummary,
                ("service_name", ): AzureNetworkSummary,
                ("service_name", "subscription_guid"): AzureNetworkSummary,
                ("subscription_guid", ): AzureNetworkSummary,
            },
        }
        super().__init__(provider, report_type)
Ejemplo n.º 19
0
class PaymentReceived(Model):
    timestamp = DateTimeField()
    amount = DecimalField(max_digits=20, decimal_places=2)
    income = ForeignKey('Income',
                        related_name="payments_received",
                        on_delete=CASCADE)
Ejemplo n.º 20
0
 def _calculate_total_price(self):
     self.total_price = self.orderproductmembership_set.aggregate(total=Sum(
         F('product__price') *
         F('quantity'), output_field=DecimalField()))['total']
Ejemplo n.º 21
0
def gen_dt_bin_data(raw_data, bin_start, bin_end):
    bin_reqs = raw_data.filter(timestamp__gte=bin_start, timestamp__lt=bin_end)
    bin_apps = raw_data.filter(approved_timestamp__gte=bin_start, approved_timestamp__lt=bin_end)
    bin_ords = raw_data.filter(order_timestamp__gte=bin_start, order_timestamp__lt=bin_end)
    bin_dels = raw_data.filter(delivery_timestamp__gte=bin_start, delivery_timestamp__lt=bin_end)

    return {'t': bin_start.strftime("%Y-%m-%d %H:%M"),
            'y': bin_reqs.count() + bin_apps.count() + bin_ords.count() + bin_dels.count()},\
           {'t': bin_start.strftime("%Y-%m-%d %H:%M"),
            'y': float(bin_ords.aggregate(t=Sum(F('cost') * F('quantity'), output_field=DecimalField()))["t"] or 0.00) +
                 float(bin_ords.exclude(shipping_cost__isnull=True).aggregate(sc=Sum('shipping_cost'))["sc"] or 0.00)}
Ejemplo n.º 22
0
class UserFund(Model):

    user = ForeignKey("auth.User", related_name="userfunds")
    bounty = ForeignKey("bounty.Bounty", related_name="userfunds")
    funding_address = CharField(max_length=100)
    refund_address = CharField(max_length=100, blank=True)
    refund_payments = ManyToManyField('asset.PaymentLog',
                                      related_name="refunds",
                                      null=True,
                                      blank=True)

    # remind user to set refund_address
    remind_count = IntegerField(default=0)
    remind_date = DateField(null=True, blank=True)  # last reminded

    # CASHED FOR VIEWS ONLY!!!
    cashed_funds_received = DecimalField(max_digits=512,
                                         decimal_places=256,
                                         default=Decimal("0.0"))

    @property
    def _am(self):
        from apps.asset import control as asset_control
        return asset_control.get_manager(self.bounty.asset)

    @property
    def received(self):
        """ Total funds received. """
        return self._am.get_received(self.funding_address)

    @property
    def torefund(self):

        # no refund for ongoing bounties
        if self.bounty.state in ['PENDING', 'ACTIVE', 'MEDIATION']:
            return Decimal("0.0")

        # no refund for successful bounties not yet payed
        from apps.claim.models import Claim  # avoid circular import
        claim = get_object_or_none(Claim, bounty=self.bounty, successful=True)
        if claim and not claim.payout:
            return Decimal("0.0")

        # everything <= minheight already processed
        minheight = 0
        if claim and claim.payout:
            minheight = claim.payout.chainheight
        for payment in self.refund_payments.all():
            if payment.chainheight > minheight:
                minheight = payment.chainheight

        unprocessedtx = lambda tx: self._am.get_tx_height(tx['txid']
                                                          ) > minheight
        txlist = filter(unprocessedtx, self.receive_transactions)
        total = Decimal(sum(map(lambda tx: tx["amount"], txlist)))
        return total - self._am.quantize(total * self.bounty.fraction_fees)

    @property
    def bound_funds(self):
        if self.bounty.state in ['PENDING', 'ACTIVE', 'MEDIATION']:
            fees = self._am.quantize(self.received * self.bounty.fraction_fees)
            return self.received - fees
        return self.torefund

    @property
    def has_min_refund_amount(self):
        return self.torefund > Decimal(
            "0.0")  # FIXME get min from asset manager

    @property
    def display_send_transactions(self):
        txlist = []
        for payment in self.refund_payments.all():
            tx = payment.transaction
            tx["user"] = self.user  # add user for use in templates
            tx["type"] = _("REFUND")  # add type for use in templates
            txlist.append(tx)
        return txlist

    @property
    def receive_transactions(self):
        txlist = self._am.get_receives(self.funding_address)
        return filter(lambda tx: tx["confirmations"] > 0, txlist)  # confirmed

    @property
    def display_receive_transactions(self):
        txlist = self._am.get_receives(self.funding_address)
        for tx in txlist:
            tx["user"] = self.user  # add user for use in templates
            tx["type"] = _("FUNDING")  # add type for use in templates
        return txlist

    def __unicode__(self):
        from apps.asset.templatetags.asset_tags import render_asset
        return "User: %s - Bounty.id: %s - %s - %s" % (
            self.user.username, self.bounty.id,
            render_asset(self.received, self.bounty.asset),
            self.refund_address and self.refund_address or "NO_REFUND_ADDRESS")
Ejemplo n.º 23
0
 def ajusta_horas(self, instance):
     tasa = instance.hoja.tasa
     es_salario_fijo = instance.hoja.tasa.es_salario_fijo
     nro_horas_contrato = instance.hoja.colaborador.nro_horas_mes
     horas_trabajadas = nro_horas_contrato
     if es_salario_fijo:
         horas = HoraHojaTrabajo.objects.filter(
             hoja__tasa__lapso=instance.hoja.tasa.lapso,
             hoja__colaborador=instance.hoja.colaborador
         ).aggregate(horas=ExpressionWrapper(Sum('cantidad_minutos') / 60, output_field=DecimalField(max_digits=4)))[
             'horas']
         if horas > nro_horas_contrato:
             horas_trabajadas = horas
     tasa.nro_horas_mes_trabajadas = horas_trabajadas
     tasa.save()
Ejemplo n.º 24
0
 def __init__(self, col, separator='|', source=None, **extra):
     self.sql_template = "%%(function)s(%%(field)s ORDER BY %%(field)s SEPARATOR '%s')" % separator
     c = DecimalField()  # XXX
     super(ConcatenateSQL, self).__init__(col, source=c, **extra)
Ejemplo n.º 25
0
 def cart_total(self, cart_id, as_value=False, queryset=None):
     cart = queryset or self.cart_products(cart_id)
     total = cart.aggregate(cart_total=Sum(F('true_price') * F('quantity'), output_field=DecimalField()))
     
     if as_value:
         total = total['cart_total']
         if total is None:
             return 0
         return float(str(total))
     return total
Ejemplo n.º 26
0
    def imprimir_ficha(self, request, *args, **kwargs):
        movimiento_id = request.GET.get('id', None)
        # Si no viene el id del movimiento se retorna 400
        if movimiento_id is None:
            return Response({"detalle": "Se necesita el id del movimiento"},
                            status=status.HTTP_400_BAD_REQUEST)
        usuario = User.objects.get(pk=request.user.id)
        persona = usuario.perfilusuario.persona
        # Si la persona no tiene impresora designada, se retorna 400
        if persona.impresora is None or persona.impresora == "":
            return Response(
                {"detalle": "El usuario no cuenta con una impresora asignada"},
                status=status.HTTP_400_BAD_REQUEST)
        movimiento = Movimiento.objects.get(pk=movimiento_id)
        # Para cada detalle del movimiento se obtienen los datos que van a sus fichas
        detalles = movimiento.detalle.exclude(persona=None).prefetch_related(
            'persona', 'producto').annotate(
                precio_total=ExpressionWrapper(F('cantidad_ficha') *
                                               F('precio_ficha'),
                                               output_field=DecimalField()))
        fichas = []
        for detalle in detalles:
            esta = False
            for ficha in fichas:
                if ficha[u'chica'] == detalle.persona.nombre:
                    descripcion = ""
                    if detalle.producto.nombre.lower() == "servicio":
                        descripcion = " " + detalle.producto_presentacion.presentacion.nombre
                    ficha[u'detalle'].append({
                        u'item':
                        detalle.producto.nombre + descripcion,
                        u'fichas':
                        detalle.cantidad_ficha,
                        u'valor':
                        detalle.precio_ficha,
                        u'total':
                        detalle.precio_total
                    })
                    ficha[u'total'] += detalle.precio_total
                    esta = True
            if not esta:
                descripcion = ""
                if detalle.producto.nombre.lower() == "servicio":
                    descripcion = " " + detalle.producto_presentacion.presentacion.nombre
                fichas.append({
                    u'fecha':
                    detalle.creado,
                    u'mesero':
                    movimiento.transacciones.first().usuario.username,
                    u'chica':
                    detalle.persona.nombre,
                    u'detalle': [{
                        u'item': detalle.producto.nombre + descripcion,
                        u'fichas': detalle.cantidad_ficha,
                        u'valor': detalle.precio_ficha,
                        u'total': detalle.precio_total
                    }],
                    u'total':
                    detalle.precio_total
                })
        # Procedimiento para imprimir
        for ficha in fichas:
            file_comanda = str(settings.MEDIA_ROOT) + "/fichas.txt"
            hr = ficha[u'fecha']
            # Se definen las zonas horarias
            HERE = tz.tzlocal()
            UTC = tz.gettz('UTC')
            # Se hace la conversion de la zona horaria
            gmt = hr.replace(tzinfo=UTC)
            gmt = gmt.astimezone(HERE)
            # Se reformatea la variable a mostrar para la comanda
            gmt = gmt.strftime('%H:%M:%S')
            # Se toma la fecha en la que se creo debido a que esta en UTC por el servidor
            # cuando se quiere mostrar se pasa a la zona horaria local
            fea = hr.replace(tzinfo=UTC)
            fea = fea.astimezone(HERE)
            fea = fea.strftime('%d/%m/%Y')
            # Crea la FICHA y coloca las variables en los lugares correspondientes en el txt
            fc = open(file_comanda, 'w')
            fc.write('************* PRESTIGE - FICHA *************\n')
            encabezado = 'DETALLE'
            limite = 44 - len('ORDEN # ' + str(movimiento_id))
            while len(encabezado) < limite:
                encabezado += " "
            encabezado += 'ORDEN # ' + str(movimiento_id) + "\n\n"
            fc.write(encabezado)
            fc.write('FECHA:           ' + str(fea) + '\n')
            fc.write('HORA:            ' + str(gmt) + '\n')
            fc.write('MESERO:          ' + str(ficha[u'mesero']) + '\n')
            fc.write('CHICA:           ' + str(ficha[u'chica']) + '\n')
            fc.write('TOTAL FICHA:     ' + str(ficha[u'total']) + '\n\n')
            fc.write('============================================\n')
            fc.write('ITEM            FICHAS   VALOR         TOTAL\n')
            fc.write('============================================\n')
            for detalle in ficha[u'detalle']:
                item = str(detalle[u'item'])
                cadena = ""
                while len(item) > 14:
                    cadena += item[0:14] + '\n'
                    item = item[14:]
                while len(item) < 16:
                    item += " "
                ultima_linea = item
                ultima_linea += str(detalle[u'fichas'])
                while len(ultima_linea) < 25:
                    ultima_linea += " "
                ultima_linea += "Q" + str(detalle[u'valor'])
                total = "Q" + str(detalle[u'total'])
                limite = 44 - len(total)
                while len(ultima_linea) < limite:
                    ultima_linea += " "
                ultima_linea += total
                cadena += ultima_linea
                fc.write(cadena + '\n')
            fc.write('--------------------------------------------\n\n')
            fc.write('============================================\n\n')
            fc.write('CAJERO:          ' + str(persona.nombre) + '\n')
            fecha_impresion = datetime.now().strftime('%d/%m/%Y %H:%M:%S')
            fc.write('FECHA IMPRESION: ' + str(fecha_impresion) + '\n')
            fc.write('\n    \n    \n  =  \n    \n    \n    \n')

            fc.write(chr(0x19))  # Linea de corte para HP
            ESC = chr(27)
            fc.write(ESC + 'i')  # Linea de corte para Epson
            fc.close()
            conn = cups.Connection()
            conn.printFile(persona.impresora, file_comanda,
                           "Ficha " + ficha[u'chica'], {})

        # Serializador de la data de las fichas
        serializer = FichasSerializer(data=fichas, many=True)
        if serializer.is_valid():
            return Response(serializer.data, status=status.HTTP_200_OK)
        else:
            Response({"detalle": "Data invalida"},
                     status=status.HTTP_400_BAD_REQUEST)
Ejemplo n.º 27
0
def get_individual_data_for_fund(employee_ids,
                                 fund,
                                 start_date=None,
                                 end_date=None):
    start_date, end_date = check_dates(start_date, end_date)

    # 4 subqueries plugged into the final query
    profdev_requested = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=False,
        departure_date__gte=start_date,
        return_date__lte=end_date,
        funding__fund=fund,
    ).values("traveler__pk").annotate(
        profdev_requested=Sum("funding__amount", filter=Q(
            funding__fund=fund))).values("profdev_requested"))

    profdev_spent = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=False,
        actualexpense__fund=fund).values("traveler__pk").annotate(
            profdev_spent=Sum(
                "actualexpense__total",
                filter=Q(actualexpense__fund=fund)
                & Q(actualexpense__date_paid__lte=end_date)
                & Q(actualexpense__date_paid__gte=start_date),
            )).values("profdev_spent"))

    admin_requested = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"),
        administrative=True,
        departure_date__gte=start_date,
        return_date__lte=end_date,
        funding__fund=fund,
    ).values("traveler__pk").annotate(
        admin_requested=Sum("funding__amount"),
        filter=Q(funding__fund=fund)).values("admin_requested"))

    admin_spent = (TravelRequest.objects.filter(
        traveler=OuterRef("pk"), administrative=True,
        actualexpense__fund=fund).values("traveler__pk").annotate(
            admin_spent=Sum(
                "actualexpense__total",
                filter=Q(actualexpense__fund=fund)
                & Q(actualexpense__date_paid__lte=end_date)
                & Q(actualexpense__date_paid__gte=start_date),
            )).values("admin_spent"))

    # final query
    rows = Employee.objects.filter(pk__in=employee_ids).annotate(
        profdev_requested=Coalesce(
            Subquery(
                profdev_requested.values("profdev_requested"),
                output_field=DecimalField(),
            ),
            Value(0),
        ),
        profdev_spent=Coalesce(
            Subquery(profdev_spent.values("profdev_spent"),
                     output_field=DecimalField()),
            Value(0),
        ),
        admin_requested=Coalesce(
            Subquery(admin_requested.values("admin_requested"),
                     output_field=DecimalField()),
            Value(0),
        ),
        admin_spent=Coalesce(
            Subquery(admin_spent.values("admin_spent"),
                     output_field=DecimalField()),
            Value(0),
        ),
    )
    return rows
Ejemplo n.º 28
0
 def _resolve_output_field(self):
     has_decimals = any(isinstance(s.output_field, DecimalField) for s in self.get_source_expressions())
     return DecimalField() if has_decimals else FloatField()
Ejemplo n.º 29
0
 def get_loaded_query(self, pallet_id, ymd):
     pallet = Pallet.objects.get(id=pallet_id)
     orders = OrderList.objects.filter(Q(ymd=ymd), Q(pallet=pallet))\
         .annotate(types=F('productCode__type')) \
         .annotate(amount_types=F('productCode__amount_kg')) \
         .annotate(amount=ExpressionWrapper(F('count') * F('productCode__amount_kg'), output_field=DecimalField())) \
     .order_by('id')
     return orders
Ejemplo n.º 30
0
    def cotizaciones_resumen_tuberia_ventas(self, request):
        self.serializer_class = CotizacionTuberiaVentaSerializer
        filtro_ano = request.GET.get('ano', None)
        filtro_mes = request.GET.get('mes', None)
        year = int(filtro_ano) if filtro_ano else timezone.datetime.now().year
        month = int(filtro_mes) if filtro_mes else timezone.datetime.now().month
        current_date = timezone.datetime.now()
        current_quarter = int(ceil(current_date.month / 3))
        _ordenes_compra = CotizacionPagoProyectado.objects.using('read_only').values('cotizacion_id').annotate(
            valor_oc=Sum('valor_orden_compra')
        ).filter(
            cotizacion_id=OuterRef('id'),
            cotizacion__estado='Cierre (Aprobado)',
            orden_compra_fecha__year=year,
            orden_compra_fecha__month=month
        ).distinct()

        qsBase = Cotizacion.objects.using('read_only').select_related(
            'cliente',
            'contacto_cliente',
            'cotizacion_inicial__cliente',
            'cotizacion_inicial__contacto_cliente',
            'responsable'
        ).annotate(
            valor_orden_compra_mes=ExpressionWrapper(
                Subquery(_ordenes_compra.values('valor_oc')),
                output_field=DecimalField(max_digits=12, decimal_places=4)
            )
        )
        qs2 = qsBase.filter(
            estado='Cierre (Aprobado)'
        )

        qs3 = None
        filtro_mes_o_ano = filtro_ano and filtro_mes
        if not filtro_mes_o_ano:
            _ordenes_compra_trimestre = CotizacionPagoProyectado.objects.values('cotizacion_id').annotate(
                valor_oc=Sum('valor_orden_compra')
            ).filter(
                cotizacion_id=OuterRef('id'),
                orden_compra_fecha__year=year,
                orden_compra_fecha__quarter=current_quarter
            ).distinct()

            qs2 = qs2.annotate(
                valor_orden_compra_trimestre=ExpressionWrapper(
                    Subquery(_ordenes_compra_trimestre.values('valor_oc')),
                    output_field=DecimalField(max_digits=12, decimal_places=4)
                )
            )
            qs3 = qsBase.filter(
                estado__in=[
                    'Cita/Generación Interés',
                    'Configurando Propuesta',
                    'Cotización Enviada',
                    'Evaluación Técnica y Económica',
                    'Aceptación de Terminos y Condiciones',
                    'Aplazado',
                ]
            )
        if filtro_mes_o_ano:
            # Sólo ira el valor de las ordenes de compra
            qsFinal = qs2.filter(Q(valor_orden_compra_mes__gt=0))
        else:
            qs2 = qs2.filter(Q(valor_orden_compra_mes__gt=0) | Q(valor_orden_compra_trimestre__gt=0))
            qsFinal = qs2 | qs3
        serializer = self.get_serializer(qsFinal, many=True)
        return Response(serializer.data)