예제 #1
0
def simulation_view(request):
    if request.method == "POST":
        return_dict = {}
        paynodes = Paynode.objects.filter(user=request.user)
        if request.POST['start_month']:
            paynodes = paynodes.filter(paydate__gte=datetime.datetime.strptime(request.POST['start_month'], '%Y-%m'))
            return_dict['start_month'] = request.POST['start_month']
        if request.POST['end_month']:
            paynodes = paynodes.filter(paydate__lte=datetime.datetime.strptime(request.POST['end_month'], '%Y-%m'))
            return_dict['end_month'] = request.POST['end_month']
        groups = paynodes.annotate(month=functions.TruncMonth('paydate')).values('month').annotate(sum=Sum('balance')).order_by('month')#.annotate(sum=Sum('balance'))
        return_dict['groups'] = groups
        return render(request, 'bookkeep/simulation.html', return_dict)
    else:
        groups = Paynode.objects.filter(user=request.user).annotate(month=functions.TruncMonth('paydate')).values('month').annotate(sum=Sum('balance')).order_by('month')#.annotate(sum=Sum('balance'))
        return render(request, 'bookkeep/simulation.html', {'groups':groups})
예제 #2
0
    def get_group_queryset(self, period_step, start, end):
        query = self.get_span_queryset(period_step, start, end)
        ann_kwargs = {}
        if period_step == models.STEP_DAY:
            ann_kwargs['_date'] = db_functions.TruncDay(
                self.date_field, output_field=DateField())
            ann_kwargs['_month'] = db_functions.TruncMonth(self.date_field)
            ann_kwargs['_year'] = db_functions.TruncYear(self.date_field)
        if period_step == models.STEP_MONTH:
            ann_kwargs['_date'] = db_functions.TruncMonth(
                self.date_field, output_field=DateField())
            ann_kwargs['_year'] = db_functions.TruncYear(self.date_field)
        if period_step == models.STEP_YEAR:
            ann_kwargs['_date'] = db_functions.TruncYear(
                self.date_field, output_field=DateField())

        return query.annotate(**ann_kwargs).values(*ann_kwargs.keys())
예제 #3
0
def _get_django_function(type_, name, qs):
    def IsNull(field_name):
        # https://code.djangoproject.com/ticket/32200
        if django.VERSION[:3] == (3, 1, 3):  # pragma: django 3.1.3
            return Subquery(
                qs.annotate(ddb_is_null=ExpressionWrapper(
                    Q(**{field_name: None}), output_field=BooleanField())).
                filter(pk=OuterRef("pk")).values("ddb_is_null")[:1],
                output_field=BooleanField(),
            )
        else:
            return ExpressionWrapper(Q(**{field_name: None}),
                                     output_field=BooleanField())

    if issubclass(type_, ArrayTypeMixin) and name == "length":
        return (ArrayLenTransform, NumberType, (), None, {})

    mapping = {
        "year": (functions.ExtractYear, NumberType, (), ASC, {
            "useGrouping": False
        }),
        "quarter": (functions.ExtractQuarter, NumberType, (), ASC, {}),
        "month":
        (functions.ExtractMonth, NumberChoiceType, _month_choices, ASC, {}),
        "month_start": (
            lambda x: functions.TruncMonth(x, DateField()),
            DateType,
            (),
            ASC,
            {},
        ),
        "day": (functions.ExtractDay, NumberType, (), ASC, {}),
        "week_day": (
            functions.ExtractWeekDay,
            NumberChoiceType,
            _weekday_choices,
            ASC,
            {},
        ),
        "hour": (functions.ExtractHour, NumberType, (), ASC, {}),
        "minute": (functions.ExtractMinute, NumberType, (), ASC, {}),
        "second": (functions.ExtractSecond, NumberType, (), ASC, {}),
        "date": (functions.TruncDate, DateType, (), ASC, {}),
        "is_null": (IsNull, IsNullType, (), None, {}),
        "length": (functions.Length, NumberType, (), None, {}),
    }
    mapping.update({
        "iso_year": (functions.ExtractIsoYear, NumberType, (), ASC, {}),
        "iso_week": (functions.ExtractWeek, NumberType, (), ASC, {}),
        "week_start": (
            lambda x: functions.TruncWeek(x, DateField()),
            DateType,
            (),
            ASC,
            {},
        ),
    })
    return mapping[name]
예제 #4
0
def patientovview_trend(start_date,
                        end_date):  # The performance graph time trend monthly
    result = [['Month', 'Percent']]
    try:
        monthly_total_trend_query = Respirology.objects. \
            annotate(month=functions.TruncMonth('appointment_date')). \
            values('month').all(). \
            annotate(total=Count('month')). \
            filter(Q(appointment_date__gte=start_date),
                   Q(appointment_date__lte=end_date),
                   (Q(checkin_time__isnull=False)|
                   Q(noshow_flag__isnull=False)|
                    Q(canceled_flag__isnull=False))
                   ). \
            order_by('month')

        complete_rate_total_trend_query = Respirology.objects. \
            annotate(month=functions.TruncMonth('appointment_date')). \
            values('month').all(). \
            annotate(total=Count('month')). \
            filter(Q(appointment_date__gte=start_date),
                   Q(appointment_date__lte=end_date),
                   Q(checkin_time__isnull=False)). \
            order_by('month')

    except ObjectDoesNotExist:
        return result

    print("1\n")
    print(monthly_total_trend_query)
    print("2\n")
    print(complete_rate_total_trend_query)
    print("3\n")

    print(len(complete_rate_total_trend_query))
    for i in range(len(complete_rate_total_trend_query)):
        result.append([
            monthly_total_trend_query[i]['month'],
            (complete_rate_total_trend_query[i]['total'] /
             monthly_total_trend_query[i]['total']) * 100
        ])
    print("4\n")
    print(result)

    return result
예제 #5
0
 def get_monthly_response(self,
                          field_to_sum=None,
                          filter_field=None,
                          queryset=None):
     queryset = queryset if queryset else self.queryset
     filter_field = filter_field if filter_field else self.filter_field
     return (queryset.annotate(
         date=F.TruncMonth(filter_field)).values("date").annotate(
             **self.generate_value_annotate(field_to_sum)).order_by("date"))
예제 #6
0
파일: tasks.py 프로젝트: lui1798/polemarch
 def stats(self, last):
     qs = self.filter(start_time__gte=now() - timedelta(days=last))
     qs = qs.annotate(
         day=dbfunc.TruncDay('start_time'),
         month=dbfunc.TruncMonth('start_time'),
         year=dbfunc.TruncYear('start_time'),
     )
     return OrderedDict(day=self._get_history_stats_by(qs, 'day'),
                        month=self._get_history_stats_by(qs, 'month'),
                        year=self._get_history_stats_by(qs, 'year'))
예제 #7
0
    def _get_interval_annotation(self, key: str) -> Dict[str, Any]:
        map: Dict[str, Any] = {
            'minute': functions.TruncMinute('timestamp'),
            'hour': functions.TruncHour('timestamp'),
            'day': functions.TruncDay('timestamp'),
            'week': functions.TruncWeek('timestamp'),
            'month': functions.TruncMonth('timestamp'),
        }
        func = map.get(key)
        if func is None:
            return {'day': map.get('day')} # default

        return { key: func }
예제 #8
0
def get_interval_annotation(key: str) -> Dict[str, Any]:
    map: Dict[str, Any] = {
        "minute": functions.TruncMinute("timestamp"),
        "hour": functions.TruncHour("timestamp"),
        "day": functions.TruncDay("timestamp"),
        "week": functions.TruncWeek("timestamp"),
        "month": functions.TruncMonth("timestamp"),
    }
    func = map.get(key)
    if func is None:
        return {"day": map.get("day")}  # default

    return {key: func}
예제 #9
0
def get_interval_annotation(key: str) -> Dict[str, Any]:
    map: Dict[str, Any] = {
        "minute": functions.TruncMinute("timestamp"),
        "hour": functions.TruncHour("timestamp"),
        "day": functions.TruncDay("timestamp"),
        "week": functions.TruncWeek(
            ExpressionWrapper(F("timestamp") + datetime.timedelta(days=1), output_field=DateTimeField())
        ),
        "month": functions.TruncMonth("timestamp"),
    }
    func = map.get(key)
    if func is None:
        return {"day": map.get("day")}  # default

    return {key: func}
예제 #10
0
    def retrieve(self, request, *args, **kwargs):
        '''
        override to serializer more user data
        '''
        employee = self.get_object()
        past_12_months = timezone.now() - timedelta(days=365)

        tasks_associated = Task.objects.filter(assignee=employee)
        tasks_time = calculate_completed_tasks_time_spent(tasks_associated)

        workflows_associated = Workflow.objects.filter(tasks__assignee=employee).distinct()
        workflows_time = self.get_workflows_time(tasks_associated)
        self.insert_workflow(workflows_time)
        times_spent_on_worflows = [x['total_time_spent'] for x in workflows_time] or [timedelta(0)]

        data = {
            'first_name': employee.user.first_name,
            'last_name': employee.user.last_name,
            'email': employee.user.email,
            'time_spent_on_workflows': workflows_time
        }

        data['number_of_workflows_assigned'] = workflows_associated.count()
        data['number_of_tasks'] = tasks_associated.count()
        data['total_time_spent_on_tasks'] = tasks_time.aggregate(total_time=Sum('time_spent'))[
            'total_time'] or timedelta(0)
        data['avg_time_spent_on_tasks'] = tasks_time.aggregate(avg_time=Avg('time_spent'))['avg_time'] or timedelta(0)
        data['min_time_spent_on_tasks'] = tasks_time.aggregate(min_time=Min('time_spent'))['min_time'] or timedelta(0)
        data['max_time_spent_on_tasks'] = tasks_time.aggregate(max_time=Max('time_spent'))['max_time'] or timedelta(0)
        data['total_time_spent_on_workflows'] = functools.reduce(
            lambda a, b: a+b['total_time_spent'], workflows_time, timedelta(0)
        )
        data['avg_time_spent_on_workflows'] = data['total_time_spent_on_workflows']/max(len(workflows_time), 1)
        data['max_time_spent_on_workflows'] = max(times_spent_on_worflows)
        data['min_time_spent_on_workflows'] = min(times_spent_on_worflows)
        data['last_task_completed'] = tasks_associated.order_by('-completed_at').first()
        data['last_workflow_completed'] = workflows_associated.order_by('-completed_at').first()

        data['workflows_completed_monthly'] = workflows_associated.filter(
            status=common_constant.WORKFLOW_STATUS.COMPLETE,
            completed_at__gt=past_12_months
        ).annotate(
            month=db_functions.TruncMonth('completed_at')
        ).values('month').annotate(count=Count('id')).values('count', 'month')

        serializer = self.get_serializer(data)
        return Response(serializer.data)
예제 #11
0
def _get_django_function(name):
    mapping = {
        "year": (functions.ExtractYear, YearType),
        "quarter": (functions.ExtractQuarter, NumberType),
        "month": (functions.ExtractMonth, MonthType),
        "month_start":
        (lambda x: functions.TruncMonth(x, DateField()), DateType),
        "day": (functions.ExtractDay, NumberType),
        "week_day": (functions.ExtractWeekDay, WeekDayType),
        "hour": (functions.ExtractHour, NumberType),
        "minute": (functions.ExtractMinute, NumberType),
        "second": (functions.ExtractSecond, NumberType),
        "date": (functions.TruncDate, DateType),
        "is_null": (IsNull, IsNullType),
    }
    if django.VERSION >= (2, 2):  # pragma: no branch
        mapping.update({
            "iso_year": (functions.ExtractIsoYear, YearType),
            "iso_week": (functions.ExtractWeek, NumberType),
            "week_start":
            (lambda x: functions.TruncWeek(x, DateField()), DateType),
        })
    return mapping[name]
예제 #12
0
 def trunc_month(self):
     """
     Truncates date or datetime at a whole month.
     """
     return functions.TruncMonth(self._name)
예제 #13
0
 def get_monthly_count_data(self, employees):
     data = employees.annotate(
         month=db_functions.TruncMonth('join_at')
     ).values('month').annotate(count=Count('id')).values('count', 'month')
     return self.get_serializer(data, many=True).data