Beispiel #1
0
    def precio_total(self):
        activos = Activo.objects.filter(bodega=self).aggregate(
            total=Sum('articulo__precio'))
        agg = Sum(F('articulo__precio') * F('cantidad'))

        agg.output_field = DecimalField(max_digits=19, decimal_places=2)
        nserial = ActivoNoSerial.objects.filter(
            bodega=self).aggregate(total=agg)

        if activos['total']:
            total = activos['total']
        else:
            total = 0
        # end if
        if nserial['total']:
            total = total + nserial['total']
        # end if
        if total == 0:
            return total
        else:
            vals = str(total).split('.')
            money = MoneyInput()
            value = money.intToStringWithCommas(
                int(vals[0])).replace(',', '.') + ',' + vals[1]
            return value
Beispiel #2
0
 def precio_insumos(self):
     agg = Sum(F('articulo__precio') * F('cantidad'))
     agg.output_field = DecimalField(max_digits=19, decimal_places=2)
     nserial = ActivoInsumo.objects.filter(bodega=self).aggregate(total=agg)
     if nserial['total']:
         total = nserial['total']
         vals = str(total).split('.')
         money = MoneyInput()
         value = money.intToStringWithCommas(
             int(vals[0])).replace(',', '.') + ',' + vals[1]
         return u"$ %s" % value
     else:
         return u"$ %d" % 0
Beispiel #3
0
    def form_valid(self, form):        
        cantidad = form.cleaned_data['cantidad']
        tipo_dispositivo = form.cleaned_data['tipo_dispositivo']
        no_salida = form.cleaned_data['no_salida']

        etapa = inv_m.DispositivoEtapa.objects.get(id=inv_m.DispositivoEtapa.TR)
        estado = inv_m.DispositivoEstado.objects.get(id=inv_m.DispositivoEstado.PD)
        validar_dispositivos = inv_m.DispositivoTipo.objects.get(tipo=tipo_dispositivo)

        if(validar_dispositivos.kardex):
            sum_solicitudes = sum_devoluciones = sum_paquetes = 0
            solicitudes = inv_m.SolicitudMovimiento.objects.filter(no_salida=no_salida, tipo_dispositivo=validar_dispositivos, terminada=True, recibida=True, devolucion=False).aggregate(Sum('cantidad'))
            devoluciones = inv_m.SolicitudMovimiento.objects.filter(no_salida=no_salida, tipo_dispositivo=validar_dispositivos, terminada=True, recibida=True, devolucion=True).aggregate(Sum('cantidad'))
            paquetes = inv_m.Paquete.objects.filter(salida=no_salida, tipo_paquete__tipo_dispositivo=validar_dispositivos).aggregate(Sum('cantidad'))

            if solicitudes['cantidad__sum'] is not None:
                sum_solicitudes = solicitudes['cantidad__sum']

            if devoluciones['cantidad__sum'] is not None:
                sum_devoluciones = devoluciones['cantidad__sum']

            if paquetes['cantidad__sum'] is not None:
                sum_paquetes = paquetes['cantidad__sum']
        
            numero_dispositivos = sum_solicitudes - sum_devoluciones - sum_paquetes
        else:
            dispositivos_salida = inv_m.CambioEtapa.objects.filter(solicitud__no_salida=no_salida, etapa_final=etapa).values('dispositivo')
            numero_dispositivos = inv_m.Dispositivo.objects.filter(id__in=dispositivos_salida, tipo=validar_dispositivos, etapa=etapa, estado=estado).count()

        if(cantidad > numero_dispositivos):
            form.add_error('cantidad', 'No  hay suficientes dipositivos para satifacer la solicitud')
            return self.form_invalid(form)
        else:
            form.instance.creada_por = self.request.user
            form.instance.devolucion = True
            form.instance.etapa_inicial = inv_m.DispositivoEtapa.objects.get(id=inv_m.DispositivoEtapa.TR)
            form.instance.etapa_final = inv_m.DispositivoEtapa.objects.get(id=inv_m.DispositivoEtapa.AB)

        return super(DevolucionCreateView, self).form_valid(form)
Beispiel #4
0
 def query_total_xp(self, user):
     return Record.objects.filter(user=user, checked=True).aggregate(
         Sum('xp'))['xp__sum']
Beispiel #5
0
 def get_suggested_votes_by_agendas(self, num):
     votes = Vote.objects.filter(~Q(agendavotes__agenda=self))
     votes = votes.annotate(score=Sum('agendavotes__importance'))
     return votes.order_by('-score')[:num]
Beispiel #6
0
def report(request):
    """ Codice per la generazione del report """
    # Codice disabilitato per la gestione del prelievo e dei vessamenti da/per le casse (LiquidTransaction)
    """checkout = Checkout.objects.all().order_by('name')
    transactions = {}
    for item in checkout:
        transactions[item] = Order.objects.filter(checkout=item.id).filter(payment_method="C").aggregate(Sum('amount'))['amount__sum'] or 0"""
    # Codice per la gestione delle statistiche giornaliere (prodotti venduti e relative quantità)
    today_orders = Order.objects.working_day()
    today_products = {}
    for detail in OrderPartDetail.objects.filter(
            orderpart__in=OrderPart.objects.filter(order__in=today_orders)):
        product = detail.product
        group = product.productgroup
        if group not in today_products:
            today_products[group] = {}
        if product not in today_products[group]:
            today_products[group][product] = 0
        old = today_products[group][product]
        today_products[group][product] += detail.quantity
    # Prodotti più venduti (di sempre)
    products = Product.objects.annotate(
        num_products=Sum('orderpartdetail__quantity'))
    topsellers = products.order_by('-num_products')[:10]
    # Incassi giornalieri
    today = today_orders.aggregate(Sum('amount'))['amount__sum'] or 0
    cash = today_orders.filter(payment_method="C").aggregate(
        Sum('amount'))['amount__sum'] or 0
    card = today_orders.filter(payment_method="T").aggregate(
        Sum('amount'))['amount__sum'] or 0
    bancomat = today_orders.filter(payment_method="B").aggregate(
        Sum('amount'))['amount__sum'] or 0
    other = today_orders.filter(payment_method="A").aggregate(
        Sum('amount'))['amount__sum'] or 0
    # Incassi totali
    orders = Order.objects.all()
    every = orders.aggregate(Sum('amount'))['amount__sum'] or 0
    every_cash = orders.filter(payment_method="C").aggregate(
        Sum('amount'))['amount__sum'] or 0
    every_card = orders.filter(payment_method="T").aggregate(
        Sum('amount'))['amount__sum'] or 0
    every_bancomat = orders.filter(payment_method="B").aggregate(
        Sum('amount'))['amount__sum'] or 0
    every_other = orders.filter(payment_method="A").aggregate(
        Sum('amount'))['amount__sum'] or 0
    # Riepilogo dei prodotti con le relative quantità vendute
    grouped = {}
    groups = ProductGroup.objects.all().order_by('name')
    for group in groups:
        grouped[group] = products.filter(productgroup=ProductGroup.objects.get(
            id=group.id)).order_by("name")

    context = {}
    context['title'] = "Report"
    #context['transactions'] = transactions
    context['products'] = products
    context['today_products'] = today_products
    context['topsellers'] = topsellers
    context['today'] = today
    context['cash'] = cash
    context['card'] = card
    context['bancomat'] = bancomat
    context['other'] = other
    context['every'] = every
    context['every_cash'] = every_cash
    context['every_card'] = every_card
    context['every_bancomat'] = every_bancomat
    context['every_other'] = every_other
    context['grouped'] = grouped
    return render_to_response('pos/report.html', context)
 def sum_of_transitions(self):
     return Transaction.objects.filter(category=self).aggregate(
         Sum('amount'))['amount__sum']
Beispiel #8
0
def base_widgets(sender, subevent=None, **kwargs):
    prodc = Item.objects.filter(
        event=sender, active=True,
    ).filter(
        (Q(available_until__isnull=True) | Q(available_until__gte=now())) &
        (Q(available_from__isnull=True) | Q(available_from__lte=now()))
    ).count()

    if subevent:
        opqs = OrderPosition.objects.filter(subevent=subevent)
    else:
        opqs = OrderPosition.objects

    tickc = opqs.filter(
        order__event=sender, item__admission=True,
        order__status__in=(Order.STATUS_PAID, Order.STATUS_PENDING),
    ).count()

    paidc = opqs.filter(
        order__event=sender, item__admission=True,
        order__status=Order.STATUS_PAID,
    ).count()

    if subevent:
        rev = opqs.filter(
            order__event=sender, order__status=Order.STATUS_PAID
        ).aggregate(
            sum=Sum('price')
        )['sum'] or Decimal('0.00')
    else:
        rev = Order.objects.filter(
            event=sender,
            status=Order.STATUS_PAID
        ).aggregate(sum=Sum('total'))['sum'] or Decimal('0.00')

    return [
        {
            'content': NUM_WIDGET.format(num=tickc, text=_('Attendees (ordered)')),
            'display_size': 'small',
            'priority': 100,
            'url': reverse('control:event.orders', kwargs={
                'event': sender.slug,
                'organizer': sender.organizer.slug
            }) + ('?subevent={}'.format(subevent.pk) if subevent else '')
        },
        {
            'content': NUM_WIDGET.format(num=paidc, text=_('Attendees (paid)')),
            'display_size': 'small',
            'priority': 100,
            'url': reverse('control:event.orders.overview', kwargs={
                'event': sender.slug,
                'organizer': sender.organizer.slug
            }) + ('?subevent={}'.format(subevent.pk) if subevent else '')
        },
        {
            'content': NUM_WIDGET.format(
                num=formats.localize(round_decimal(rev, sender.currency)), text=_('Total revenue ({currency})').format(currency=sender.currency)),
            'display_size': 'small',
            'priority': 100,
            'url': reverse('control:event.orders.overview', kwargs={
                'event': sender.slug,
                'organizer': sender.organizer.slug
            }) + ('?subevent={}'.format(subevent.pk) if subevent else '')
        },
        {
            'content': NUM_WIDGET.format(num=prodc, text=_('Active products')),
            'display_size': 'small',
            'priority': 100,
            'url': reverse('control:event.items', kwargs={
                'event': sender.slug,
                'organizer': sender.organizer.slug
            })
        },
    ]
Beispiel #9
0
 def test_multiple_aggregates(self):
     vals = Author.objects.aggregate(Sum("age"), Avg("age"))
     self.assertEqual(vals, {"age__sum": 337, "age__avg": Approximate(37.4, places=1)})
    def post(self, request, id):
        firewall_rule_ids = get_firewall_rules_id_from_request(request)
        try:
            tt = TroubleTicketAnomaly.objects.get(
                id=id,
                firewall_rule__in=firewall_rule_ids
            )
            if tt.reasons:
                reasons = [
                    self.REASONS_MAP[i.strip()]
                    for i in tt.reasons.split(',')
                ]

            ip = tt.source_address
            objects = TrafficLogDetailHourly.objects.filter(
                source_address=ip,
                firewall_rule__in=firewall_rule_ids
            )
            numeric_values = objects.values('source_address').aggregate(
                ###### NUMERIC COLS SUM ##############
                bytes_sent=Sum('sum_bytes_sent'),
                bytes_received=Sum('sum_bytes_received'),
                packets_sent=Sum('sum_packets_sent'),
                packets_received=Sum('sum_packets_received'),
                time_elapsed=Sum('sum_time_elapsed'),
                n_records=Count('application')  # Count any arbitrary field
            )

            n_records = numeric_values.pop('n_records') - 1

            numeric = {}
            numeric_reasons = set()

            for reason in reasons:
                try:
                    difference = numeric_values[reason] - getattr(tt, reason)
                    numeric[reason] = format(difference/n_records, '.2f')
                    numeric_reasons.add(reason)
                except KeyError as e:
                    pass

            categorical = {}
            categorical_reasons = set(reasons) - numeric_reasons
            for reason in categorical_reasons:
                query = {reason: getattr(tt, reason)}
                count = objects.filter(**query).count()
                categorical[reason] = count
            return Response({
                "numeric": numeric,
                "categorical": categorical
            })
            query = {}
            max = objects.count()
            if max == 0:
                return Response({
                    "categorical": {},
                    "numeric": {}
                })

            for reason in reasons:
                if reason not in {'logged_datetime'}:
                    query[reason] = self.get_stats(objects, reason, max)

            stats = objects.aggregate(**query)
            categorical = {}
            numeric = {}
            for stat in stats:
                if stat in self._numeric_cols:
                    numeric[stat] = format(stats[stat], '.2f')
                else:
                    categorical[stat] = stats[stat]
            return Response({'reasons': {
                'categorical': categorical,
                'numeric': numeric
            }})

        except TroubleTicketAnomaly.DoesNotExist as e:
            return Response({"error": 'yes'})
Beispiel #11
0
 def save(self, *args, **kwargs):
     self.balance = self.person_set.all().aggregate(Sum('balance'))['balance__sum'] \
         if self.person_set.all().exists() else 0
     super().save(*args, *kwargs)
Beispiel #12
0
    def extra_handle_list_data(self, data):
        user_ids = [row['obj_id'] for row in data]
        rank_type = self.query_data.get('type', int)
        if rank_type is None or rank_type == RANK_TYPE_PERSON:
            rank_detail = self.queryset.filter(submit_user_id__in=user_ids)
            rank_detail = rank_detail.values(
                'submit_user_id',
                'type').annotate(solved_count=Count('task_hash'),
                                 sum_score=Sum('weight_score'))
            rank_detail_rows = {
                '{user_id}/{type}'.format(user_id=row['submit_user_id'],
                                          type=row['type']): row
                for row in rank_detail
            }
        if rank_type == RANK_TYPE_FACULTY:
            rank_detail = self.queryset.filter(
                submit_user__faculty_id__in=user_ids)
            rank_detail = rank_detail.values(
                'submit_user__faculty_id',
                'type').annotate(solved_count=Count('task_hash'),
                                 sum_score=Sum('weight_score'))
            rank_detail_rows = {
                '{user_id}/{type}'.format(
                    user_id=row['submit_user__faculty_id'], type=row['type']):
                row
                for row in rank_detail
            }
        if rank_type == RANK_TYPE_MAJOR:
            rank_detail = self.queryset.filter(
                submit_user__major_id__in=user_ids)
            rank_detail = rank_detail.values(
                'submit_user__major_id',
                'type').annotate(solved_count=Count('task_hash'),
                                 sum_score=Sum('weight_score'))
            rank_detail_rows = {
                '{user_id}/{type}'.format(user_id=row['submit_user__major_id'],
                                          type=row['type']): row
                for row in rank_detail
            }
        if rank_type == RANK_TYPE_CLASSES:
            rank_detail = self.queryset.filter(
                submit_user__classes_id__in=user_ids)
            rank_detail = rank_detail.values(
                'submit_user__classes_id',
                'type').annotate(solved_count=Count('task_hash'),
                                 sum_score=Sum('weight_score'))
            rank_detail_rows = {
                '{user_id}/{type}'.format(
                    user_id=row['submit_user__classes_id'], type=row['type']):
                row
                for row in rank_detail
            }

        for row in data:
            if rank_type is None or rank_type == RANK_TYPE_PERSON:
                row['obj_name'] = '{}->{}->{}->{}'.format(
                    row['faculty_name'], row['major_name'],
                    row['classes_name'], row['obj_name'])
            elif rank_type == RANK_TYPE_FACULTY:
                pass
            elif rank_type == RANK_TYPE_MAJOR:
                row['obj_name'] = '{}->{}'.format(row['faculty_name'],
                                                  row['obj_name'])
            else:
                row['obj_name'] = '{}->{}->{}'.format(row['faculty_name'],
                                                      row['major_name'],
                                                      row['obj_name'])
            if rank_detail_rows.get('{user_id}/{type}'.format(
                    user_id=row['obj_id'],
                    type=PRACTICE_TYPE_THEORY)) is not None:
                row['theory_count'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_THEORY))['solved_count']
                row['theory_score'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_THEORY))['sum_score']
            else:
                row['theory_count'] = 0
                row['theory_score'] = 0
            if rank_detail_rows.get('{user_id}/{type}'.format(
                    user_id=row['obj_id'],
                    type=PRACTICE_TYPE_REAL_VULN)) is not None:
                row['real_vuln_count'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_REAL_VULN))['solved_count']
                row['real_vuln_score'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_REAL_VULN))['sum_score']
            else:
                row['real_vuln_count'] = 0
                row['real_vuln_score'] = 0
            if rank_detail_rows.get('{user_id}/{type}'.format(
                    user_id=row['obj_id'],
                    type=PRACTICE_TYPE_EXCRISE)) is not None:
                row['exercise_count'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_EXCRISE))['solved_count']
                row['exercise_score'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_EXCRISE))['sum_score']
            else:
                row['exercise_count'] = 0
                row['exercise_score'] = 0
            if rank_detail_rows.get('{user_id}/{type}'.format(
                    user_id=row['obj_id'],
                    type=PRACTICE_TYPE_INFILTRATION)) is not None:
                row['infiltration_count'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_INFILTRATION))['solved_count']
                row['infiltration_score'] = rank_detail_rows.get(
                    '{user_id}/{type}'.format(
                        user_id=row['obj_id'],
                        type=PRACTICE_TYPE_INFILTRATION))['sum_score']
            else:
                row['infiltration_count'] = 0
                row['infiltration_score'] = 0
        return data
Beispiel #13
0
def UserProfile(request, username):
    user = get_object_or_404(User, username=username)
    profile = Profile.objects.get(user=user)
    url = request.resolver_match.url_name

    tiers = None
    no_a_subscriber = None
    posts = None
    page_type = None
    posts_data = None

    if request.user != user:
        try:
            #Check if the user is subscribed to the profile
            subscriber_tier = Subscription.objects.get(subscriber=request.user,
                                                       subscribed=user,
                                                       expired=False)
            #Then we get the tiers of the profile and exclude the tiers that we are currently subscribed
            tiers = Tier.objects.filter(user=user).exclude(
                number=subscriber_tier.tier.number)

            # for pictures
            if url == 'profilephotos':
                posts = PostFileContent.objects.filter(
                    user=user,
                    tier__number__lte=subscriber_tier.tier.number).order_by(
                        '-posted').exclude(file__endswith='mp4')
                page_type = 1
            # for videos
            elif url == 'profilevideos':
                posts = PostFileContent.objects.filter(
                    user=user,
                    tier__number__lte=subscriber_tier.tier.number).order_by(
                        '-posted').exclude(file__endswith='jpg')
                page_type = 2
            else:
                posts = Post.objects.filter(
                    user=user,
                    tier__number__lte=subscriber_tier.tier.number).order_by(
                        '-posted')
                page_type = 3
        # if user not subscribed then display all available tiers
        except Exception:
            tiers = Tier.objects.filter(user=user)
            no_a_subscriber = False
    else:
        if url == 'profilephotos':
            posts = PostFileContent.objects.filter(
                user=user).order_by('-posted').exclude(file__endswith='mp4')
            page_type = 1
        elif url == 'profilevideos':
            posts = PostFileContent.objects.filter(
                user=user).order_by('-posted').exclude(file__endswith='jpg')
            page_type = 2
        else:
            posts = Post.objects.filter(user=user).order_by('-posted')
            page_type = 3

    #Pagination
    if posts:
        paginator = Paginator(posts, 6)
        page_number = request.GET.get('page')
        posts_data = paginator.get_page(page_number)

    #Profile stats
    income = Subscription.objects.filter(subscribed=user,
                                         expired=False).aggregate(
                                             Sum('tier__price'))
    fans_count = Subscription.objects.filter(subscribed=user,
                                             expired=False).count()
    posts_count = Post.objects.filter(user=user).count()

    #Favorite people lists select
    favorite_list = PeopleList.objects.filter(user=request.user)

    #Check if the profile is in any of favorite list
    person_in_list = PeopleList.objects.filter(user=request.user,
                                               people=user).exists()

    #New Favorite List form
    if request.method == 'POST':
        form = NewListForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            PeopleList.objects.create(title=title, user=request.user)
            return HttpResponseRedirect(reverse('profile', args=[username]))
    else:
        form = NewListForm()

    context = {
        'profile': profile,
        'income': income,
        'tiers': tiers,
        'form': form,
        'favorite_list': favorite_list,
        'person_in_list': person_in_list,
        'posts': posts_data,
        'page_type': page_type,
        'fans_count': fans_count,
        'posts_count': posts_count,
        'no_a_subscriber': no_a_subscriber,
    }

    return render(request, 'profile.html', context)
    def get_context_data(self, **kwargs):
        context = super(IndexView, self).get_context_data(**kwargs)
        quantidade_cadastro = {}
        agenda_hoje = {}
        alertas = {}
        data_atual = datetime.now().date()

        nfes = NotaFiscal.objects.all()

        nro_notas_em_digitacao = 0
        nro_notas_autorizadas = 0
        nro_notas_canceladas = 0

        for nf in nfes:
            if nf.status_nfe == '3':
                nro_notas_em_digitacao += 1
            if nf.status_nfe == '1':
                nro_notas_autorizadas += 1
            if nf.status_nfe == '8':
                nro_notas_canceladas += 1

        nro_notas_restantes = 200 - nro_notas_autorizadas

        with connection.cursor() as cursor:
            cursor.execute("SELECT pg_database_size('SGEO')")
            tamanho = cursor.fetchall()[0][0]
            context['armazenamento'] = round((tamanho / 1000000), 3)

        data_de_hoje = datetime.now().date()
        mes_atual = datetime.now().month
        ano_atual = datetime.now().year

        dias_do_mes = monthrange(ano_atual, mes_atual)[1]

        ultimo_dia_mes = datetime(ano_atual, mes_atual, dias_do_mes)
        primeiro_dia_mes = datetime(ano_atual, mes_atual, 1)

        a_receber_dia = Entrada.objects.filter(
            data_vencimento=datetime.now().date(), status__in=['1'])

        a_receber_mes = Entrada.objects.filter(
            data_vencimento__gte=data_de_hoje,
            data_vencimento__lte=ultimo_dia_mes,
            status__in=['1'])

        recebidos_dia = Entrada.objects.filter(
            data_vencimento=datetime.now().date(), status__in=['0'])

        recebidos_mes = Entrada.objects.filter(
            data_vencimento__lte=data_de_hoje,
            data_vencimento__gte=primeiro_dia_mes,
            status__in=['0'])

        pagamentos_dia = Saida.objects.filter(
            data_vencimento=datetime.now().date(), status__in=['0'])

        pagamentos_mes = Saida.objects.filter(
            data_vencimento__lte=data_de_hoje,
            data_vencimento__gte=primeiro_dia_mes,
            status__in=['0'])

        a_pagar_dia = Saida.objects.filter(
            data_vencimento=datetime.now().date(), status__in=['1'])

        a_pagar_mes = Saida.objects.filter(data_vencimento__gte=data_de_hoje,
                                           data_vencimento__lte=ultimo_dia_mes,
                                           status__in=['1'])

        context['valor_a_receber_dia'] = a_receber_dia.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']
        context['valor_a_receber_mes'] = a_receber_mes.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']

        context['valor_recebidos_dia'] = recebidos_dia.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']
        context['valor_recebidos_mes'] = recebidos_mes.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']

        context['valor_a_pagar_dia'] = a_pagar_dia.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']
        context['valor_a_pagar_mes'] = a_pagar_mes.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']

        context['valor_pago_dia'] = pagamentos_dia.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']
        context['valor_pago_mes'] = pagamentos_mes.aggregate(
            soma_total=Sum('valor_liquido'))['soma_total']

        context['todos_recebidos'] = MovimentoCaixa.objects.order_by(
            'data_movimento').all()

        context['all_a_receber'] = Entrada.objects.filter(
            data_vencimento__gte=datetime.now().date(),
            status__in=['1']).order_by('data_vencimento')[:7]

        context['qtd_a_receber'] = Entrada.objects.filter(
            data_vencimento__gte=datetime.now().date(),
            status__in=['1']).count()

        context['all_a_pagar'] = Saida.objects.filter(
            data_vencimento__gte=datetime.now().date(),
            status__in=['1']).order_by('data_vencimento')[:7]

        context['qtd_a_pagar'] = Saida.objects.filter(
            data_vencimento__gte=datetime.now().date(),
            status__in=['1']).count()

        context['entradas_atrasadas'] = Entrada.objects.filter(
            data_vencimento__lt=datetime.now().date(),
            status__in=['1', '2']).order_by('data_vencimento')[:7]

        context['pagamentos_atrasados'] = Saida.objects.filter(
            data_vencimento__lt=datetime.now().date(),
            status__in=['1', '2']).order_by('data_vencimento')[:7]

        context['contador_nfe_em_digitacao'] = nro_notas_em_digitacao
        context['contador_nfe_autorizada'] = nro_notas_autorizadas
        context['contador_nfe_cancelada'] = nro_notas_canceladas
        context['contador_nfe_restantes'] = nro_notas_restantes
        context['contador_nfe_total'] = nfes.count()
        context[
            'certificado_a1'] = ConfiguracaoNotaFiscal.arquivo_certificado_a1

        context['data_atual'] = data_atual.strftime('%d/%m/%Y')

        quantidade_cadastro['clientes'] = Cliente.objects.all().count()
        quantidade_cadastro['fornecedores'] = Fornecedor.objects.all().count()
        quantidade_cadastro['produtos'] = Produto.objects.all().count()
        #quantidade_cadastro['servicos'] = Servico.objects.all().count()
        quantidade_cadastro['empresas'] = Empresa.objects.all().count()
        quantidade_cadastro['transportadoras'] = Transportadora.objects.all(
        ).count()
        context['quantidade_cadastro'] = quantidade_cadastro

        agenda_hoje['orcamento_venda_hoje'] = OrcamentoVenda.objects.filter(
            data_vencimento=data_atual, status='0').count()
        agenda_hoje['orcamento_compra_hoje'] = OrcamentoCompra.objects.filter(
            data_vencimento=data_atual, status='0').count()
        agenda_hoje['pedido_venda_hoje'] = PedidoVenda.objects.filter(
            data_entrega=data_atual, status='0').count()
        agenda_hoje['pedido_compra_hoje'] = PedidoCompra.objects.filter(
            data_entrega=data_atual, status='0').count()
        agenda_hoje['contas_receber_hoje'] = Entrada.objects.filter(
            data_vencimento=data_atual, status__in=['1', '2']).count()
        agenda_hoje['contas_pagar_hoje'] = Saida.objects.filter(
            data_vencimento=data_atual, status__in=['1', '2']).count()
        context['agenda_hoje'] = agenda_hoje

        alertas['produtos_baixo_estoque'] = Produto.objects.filter(
            estoque_atual__lte=F('estoque_minimo')).count()
        alertas['orcamentos_venda_vencidos'] = OrcamentoVenda.objects.filter(
            data_vencimento__lte=data_atual, status='0').count()
        alertas['pedidos_venda_atrasados'] = PedidoVenda.objects.filter(
            data_entrega__lte=data_atual, status='0').count()
        alertas['orcamentos_compra_vencidos'] = OrcamentoCompra.objects.filter(
            data_vencimento__lte=data_atual, status='0').count()
        alertas['pedidos_compra_atrasados'] = PedidoCompra.objects.filter(
            data_entrega__lte=data_atual, status='0').count()
        alertas['contas_receber_atrasadas'] = Entrada.objects.filter(
            data_vencimento__lte=data_atual, status__in=['1', '2']).count()
        alertas['contas_pagar_atrasadas'] = Saida.objects.filter(
            data_vencimento__lte=data_atual, status__in=['1', '2']).count()
        context['alertas'] = alertas

        try:
            context['movimento_dia'] = MovimentoCaixa.objects.get(
                data_movimento=data_atual)
        except (MovimentoCaixa.DoesNotExist, ObjectDoesNotExist):
            ultimo_mvmt = MovimentoCaixa.objects.filter(
                data_movimento__lt=data_atual)
            if ultimo_mvmt:
                context['saldo'] = ultimo_mvmt.latest(
                    'data_movimento').saldo_final
            else:
                context['saldo'] = '0,00'

        return context
Beispiel #15
0
def show_line_graph(request):

    kakeibo_data = Kakeibo.objects.all()

    #カテゴリリストデータの生成
    category_list = []
    category_data = Category.objects.all().order_by('-category_name')
    for item in category_data:
        category_list.append(item.category_name)
    date_list = []
    for i in kakeibo_data:
        date_list.append((i.date.strftime('%Y/%m/%d')[:7]))
        date_list.sort()
    #重複値の除外
    x_label = list(set(date_list))
    x_label.sort(reverse=False)

    #月毎&カテゴリー毎の合計金額データセット
    monthly_sum_data = []
    for i in range(len(x_label)):
        year, month = x_label[i].split("/")
        month_range = calendar.monthrange(int(year), int(month))[1]
        first_date = year + '-' + month + '-' + '01'
        last_date = year + '-' + month + '-' + str(month_range)
        #1ヶ月分のデータ
        total_of_month = Kakeibo.objects.filter(date__range=(first_date,
                                                             last_date))
        category_total = total_of_month.values('category').annotate(
            total_price=Sum('money'))
    for j in range(len(category_total)):
        money = category_total[j]['total_price']
        category = Category.objects.get(pk=category_total[i]['category'])
        monthly_sum_data.append([x_label[i], category.category_name, money])

    #折れ線グラフのボーダーカラー
    border_color_list = [
        '254,97,132,0.8', '54,164,235,0.8', '0,255,65,0.8', '255,241,15,0.8',
        '255,94,25,0.8', '84,77,203,0.8', '204,153,50,0.8', '214,216,165,0.8',
        '33,30,45,0.8', '52,38,89,0.8'
    ]
    border_color = []
    for x, y in zip(category_list, border_color_list):
        border_color.append([x, y])

    background_color_list = [
        '254,97,132,0.5', '54,164,235,0.5', '0,255,65,0.5', '255,241,15,0.5',
        '255,94,25,0.5', '84,77,203,0.5', '204,153,50,0.5', '214,216,165,0.5'
        '33,30,45,0.5', '52,38,89,0.5'
    ]
    background_color = []
    for x, y in zip(category_list, background_color_list):
        background_color.append([x, y])

    matrix_list = []
    for item_label in x_label:
        for item_category in category_list:
            matrix_list.append([item_label, item_category, 0])
    """ matrix_listとmonthlysum_dataに対して、「年月+カテゴリ」の
        組み合わせが一致する要素に対してmatrix_listの金額(0円)を
        monthly_sum_dataの金額で上書きする。
    """
    for yyyy_mm, category, total in monthly_sum_data:
        for i, data in enumerate(matrix_list):
            if data[0] == yyyy_mm and data[1] == category:
                matrix_list[i][2] = total
    return render(
        request, 'kakeibo/kakeibo_line.html', {
            'x_label': x_label,
            'category_list': category_list,
            'border_color': border_color,
            'background_color': background_color,
            'matrix_list': matrix_list,
        })
Beispiel #16
0
 def recalculate_rating(self):
     self.rating = self.artworks.aggregate(
         Sum('points'))['points__sum'] / self.artworks.count()
Beispiel #17
0
 def points_earned(self):
     return Enrollment.objects.filter(person=self).aggregate(
         Sum('points'))['points__sum']
Beispiel #18
0
 def test_filter_aggregate(self):
     vals = Author.objects.filter(age__gt=29).aggregate(Sum("age"))
     self.assertEqual(len(vals), 1)
     self.assertEqual(vals["age__sum"], 254)
Beispiel #19
0
def get_volunteer_score(openid):
    res = ActivityRegister.objects.filter(
        volunteer__openid=openid, status=ActivityRegister.SIGNED_UP).aggregate(
            total_score=Sum('activity__type__score'))
    return res["total_score"] if len(res) > 0 and res["total_score"] else 0
Beispiel #20
0
 def test_sum_duration_field(self):
     self.assertEqual(
         Publisher.objects.aggregate(Sum('duration', output_field=DurationField())),
         {'duration__sum': datetime.timedelta(days=3)}
     )
Beispiel #21
0
 def get_stat_info(self):
     return self.crawler.values('created_by').annotate(
         completed=Sum('is_complete', output_field=IntegerField()),
         successful=Sum('is_successful', output_field=IntegerField()),
         loaded=Sum('is_loaded', output_field=IntegerField()))
def _customer_total_balance(id):
    ''' Sum up the balances in customer's accounts types'''
    return CustomerAccount.objects.filter(customer__customer__id=id).aggregate(
        Sum('balance')).get('balance__sum')
Beispiel #23
0
def print_order(request, order_id):
    """ Codice per la stampa dell'ordine """
    order = Order.objects.get(pk=order_id)
    response = HttpResponse(content_type="text/plain")
    response[
        'Content-Disposition'] = 'attachment; filename=pos-%d.txt' % order.id
    response.write(sprint_b['top'])
    date = timezone.localtime(order.date)
    orderparts = OrderPart.objects.filter(order=order_id)
    checkout = Checkout.objects.get(pk=order.checkout_id)
    details = {}
    # Creazione dello scontrino
    response.write(sprint_b['reset'])
    for line in TESTATA.strip().splitlines():
        if len(line) > sprint_b['line_length']:
            response_write(line)
        else:
            response.write(line.center(sprint_b['line_length']))
        response.write("\n")
    response.write("\n\n")
    response.write("%s %d %s\n\n" % (date, order.id, checkout))
    for orderpart in orderparts:
        orderpartdetails = OrderPartDetail.objects.filter(orderpart=orderpart)
        if orderpart.offer:  # Gestione delle offerte
            for orderpartdetail in orderpartdetails:
                if orderpartdetail.product.productgroup not in details:
                    details[orderpartdetail.product.productgroup] = []
                details[orderpartdetail.product.productgroup].append(
                    "%dx %s (%s)\n" %
                    (orderpartdetail.quantity, orderpartdetail.product,
                     orderpart.offer))
            last = ("%dx %s" % (orderpartdetail.quantity, orderpart.offer))
            response.write(last)
            response.write(("%.2f euro" %
                            (orderpart.offer.price * orderpartdetail.quantity)
                            ).rjust(sprint_b['line_length'] - len(last)))
            response.write("\n")
        else:  # Gestione dei prodotti non associati alle offerte
            for orderpartdetail in orderpartdetails:
                if orderpartdetail.product.productgroup not in details:
                    details[orderpartdetail.product.productgroup] = []
                details[orderpartdetail.product.productgroup].append(
                    "%dx %s\n" %
                    (orderpartdetail.quantity, orderpartdetail.product))
                last = ("%dx %s" %
                        (orderpartdetail.quantity, orderpartdetail.product))
                response.write(last)
                response.write(
                    str("%.2f euro" %
                        orderpartdetail.amount).rjust(sprint_b['line_length'] -
                                                      len(last)))
                response.write("\n")
    response.write("\n")
    last = ">>> Totale"
    response.write(last)
    response.write(("%.2f euro" % order.amount).rjust(sprint_b['line_length'] -
                                                      len(last)))
    response.write("\n")
    if order.contributor:
        last = ">>> Totale (non scontato)"
        response.write(last)
        amount = OrderPart.objects.filter(order=order_id).aggregate(
            Sum('amount'))['amount__sum'] or 0
        response.write(
            ("%.2f euro" % amount).rjust(sprint_b['line_length'] - len(last)))
        response.write("\n")
    # Creazione delle comande
    response.write(sprint_b['bottom'])
    response.write(sprint_b['partial_cut'])
    response.write(sprint_b['double_height_on'])
    for group, detail in details.items(
    ):  # Stampa della comanda divisa per categoria
        response.write("* Comanda *".center(sprint_b['line_length']))
        response.write("\n\n")
        response.write("%s %d %s\n\n" % (date, order.id, checkout))
        response.write(">>> %s\n\n" % group)
        for item in detail:
            response.write(item)
            response.write("\n\n")
        response.write(sprint_b['bottom'])
        response.write(sprint_b['partial_cut'])
    response.write(sprint_b['reset'])
    return response
def _customer_total_transactions(pk, transction_type):
    '''Return the total sum of customer withdrawals or deposits'''
    return Transaction.objects.filter(
        customer__customer__id=pk, transaction_type=transction_type).aggregate(
            Sum('amount')).get('amount__sum')
 def get_vote_count(self):
     result = self.avm_answer.aggregate(Sum('vote'))['vote__sum']
     if result:
         return result
     else:
         return 0
Beispiel #26
0
 def get_score(self):
     return self.rating_set.aggregate(Sum('rating'))
Beispiel #27
0
 def query_unchecked_spent_xp(self, user):
     return Record.objects.filter(user=user,
                                  checked=False,
                                  action__category=5).aggregate(
                                      Sum('xp'))['xp__sum']
 def get_queryset(self):
     return SepaExport.objects.filter(event=self.request.event).annotate(
         cnt=Count('sepaexportorder'),
         sum=Sum('sepaexportorder__amount'),
     ).order_by('-datetime')
Beispiel #29
0
def get_payments_for_me_not_confirmed(user):
    return Payment.objects.filter(whom=user, confirm=False).aggregate(
        Sum('payment_amount'))['payment_amount__sum']
Beispiel #30
0
 def obtener_tiempo(self):
     return PersonaTaskRelacion.objects.filter(task=self).aggregate(total=Sum('tiempo'))['total'] or 0
Beispiel #31
0
 def money_spent(self):
     return Payment.objects.filter(enrollment__person=self).aggregate(
         Sum('price'))['price__sum']
 def get(self, request, pk):
     due_total = DueAmount.objects.filter(student=pk, status=True, delete=False)
     due_total_amount = due_total.aggregate(student_total_due=Coalesce(Sum('amount'), 0))
     return Response(due_total_amount['student_total_due'])