Exemplo n.º 1
0
 def check_permissions(self, request, *args, **kwargs):
     # проверяем, что начался новый год и нет распределений
     return (
         super(StartDistributionYear, self).check_permissions(request, *args, **kwargs)
         and get_current_distribution_year() != get_distribution_year()
         and not Distribution.objects.active()
     )
Exemplo n.º 2
0
def get_distribution_statistics_data():
    statistic = []
    distribution_year = get_current_distribution_year()
    distributions = Distribution.objects.filter(
        year__year=distribution_year.year)
    context = {'distributions_names': [distribution.start_datetime.date()
        for distribution in distributions]}
    age_groups = AgeGroup.objects.all()
    total = [{'number_of_distributed':0, 'places_decision':0}
        for age_group in age_groups]
    context.update({'age_groups_names': [age_group.name for age_group
                                            in age_groups]})
    #            проходимся по всем распределениям
    for distribution in distributions:
        distribution_data = []
        #                выборка статистики по возрастным группам
        for i, age_group in enumerate(age_groups):
            vacancies = Vacancies.objects.filter(
                distribution=distribution, sadik_group__age_group=age_group)
            places_decision = vacancies.filter(
                status__in=(VACANCY_STATUS_PROVIDED, VACANCY_STATUS_DISTRIBUTED)).count()
            number_of_distributed = vacancies.filter(
                status=VACANCY_STATUS_DISTRIBUTED).count()
            distribution_data.append(
                    {'number_of_distributed': number_of_distributed,
                     'places_decision': places_decision})
            total[i]['number_of_distributed'] += number_of_distributed
            total[i]['places_decision'] += places_decision
            # Накопление итогов
        statistic.append(distribution_data)
#            добавляем данные об общем количестве
    statistic.append(total)
    context.update({'statistic': statistic})
    return context
Exemplo n.º 3
0
 def get(self, request, sadik_id):
     sadik = get_object_or_404(Sadik, id=sadik_id)
     requestions = Requestion.objects.filter(
         pref_sadiks=sadik,
         status__in=(STATUS_REQUESTER, STATUS_ON_DISTRIBUTION)
     )
     lowest_category = BenefitCategory.objects.category_without_benefits()
     requestions_statistics = {
         'prefer_requestions_number': requestions.count(),
         'prefer_benefit_requestions_number': requestions.filter(
             benefit_category__priority__gt=lowest_category.priority).count()
     }
     age_groups = AgeGroup.objects.all()
     requestions_numbers_by_groups = []
     current_distribution_year = get_current_distribution_year()
     for group in age_groups:
         requestions_numbers_by_groups.append(requestions.filter_for_age(
             min_birth_date=group.min_birth_date(
                 current_distribution_year=current_distribution_year),
             max_birth_date=group.max_birth_date(
                 current_distribution_year=current_distribution_year)
         ).count())
    # список распределенных заявок с путевками в работающие группы этого ДОУ
     groups_with_distributed_requestions = sadik.get_groups_with_distributed_requestions()
     return self.render_to_response({
         'sadik': sadik,
         'requestions_statistics': requestions_statistics,
         'requestions_numbers_by_groups': requestions_numbers_by_groups,
         'groups': age_groups,
         'groups_with_distributed_requestions': groups_with_distributed_requestions,
     })
Exemplo n.º 4
0
 def get_context_data(self, **kwargs):
     context = super(DistributionYearInfo, self).get_context_data(**kwargs)
     context.update({
         'current_distribution_year': get_current_distribution_year(),
         'not_distributed_requestions_number':
             Requestion.objects.enrollment_in_progress().count()})
     return context
Exemplo n.º 5
0
 def post(self, request, sadik_id):
     data = json.loads(request.body)
     year = get_current_distribution_year()
     kg = get_object_or_404(Sadik, pk=sadik_id)
     for sg_data in data:
         age_group = AgeGroup.objects.get(pk=sg_data['ageGroupId'])
         if sg_data['id']:
             sadik_group = SadikGroup.objects.get(pk=sg_data['id'])
         else:
             try:
                 sadik_group = SadikGroup.objects.get(
                     sadik=kg, active=True, age_group=age_group)
             except ObjectDoesNotExist:
                 sadik_group = SadikGroup(
                     sadik=kg, active=True, age_group=age_group, year=year)
                 sadik_group.set_default_age(age_group)
         places = int(sg_data["capacity"])
         sadik_group.free_places = places
         sadik_group.capacity = places
         sadik_group.save()
         Logger.objects.create_for_action(
             CHANGE_SADIK_GROUP_PLACES,
             context_dict={'sadik_group': sadik_group},
             extra={
                 'user': request.user,
                 'obj': sadik_group,
                 'age_group': sadik_group.age_group
             })
     sgs = SadikGroup.objects.filter(active=True, sadik=sadik_id)
     return JSONResponse(SadikGroupSerializer(sgs, many=True).data)
Exemplo n.º 6
0
    def post(self, request):
        if request.POST.get('confirmation') == 'yes':
            # инициируем зачисление
            distribution = Distribution.objects.create(
                year=get_current_distribution_year())
            distribution.start_datetime = datetime.datetime.now()
            distribution.save()
            Vacancies.objects.filter(
                distribution__isnull=True,
                status__isnull=True).update(distribution=distribution)
            Logger.objects.create_for_action(
                DISTRIBUTION_INIT,
                extra={'user': request.user, 'obj': distribution})

            # сохраняем изначальный статус
            Requestion.objects.filter(status__in=[
                STATUS_REQUESTER, STATUS_SHORT_STAY
            ]).update(previous_status=F('status'))
            # обновляем статус на "На распределении"
            Requestion.objects.filter(status__in=[
                STATUS_REQUESTER, STATUS_SHORT_STAY
            ]).update(status=STATUS_ON_DISTRIBUTION)

            for requestion in Requestion.objects.filter(
                    status=STATUS_TEMP_DISTRIBUTED):
                requestion.change_status(STATUS_ON_TEMP_DISTRIBUTION)
        return HttpResponseRedirect(reverse('decision_manager'))
Exemplo n.º 7
0
 def create_statistic_record(self, type):
     from sadiki.statistics.views import STATISTIC_HANDLER_FOR_TYPE
     data = json.dumps(STATISTIC_HANDLER_FOR_TYPE[type](), cls=DjangoJSONEncoder)
     year = get_current_distribution_year()
     statistic_record = self.create(record_type=type,
         data=data, year=year)
     return statistic_record
Exemplo n.º 8
0
 def save(self, commit=True):
     free_places = self.cleaned_data.get('free_places')
     self.instance.capacity = free_places
     if not self.initial:
         # Создание новой группы
         self.instance.year = get_current_distribution_year()
         self.instance.min_birth_date = self.cleaned_data['age_group'].min_birth_date()
         self.instance.max_birth_date = self.cleaned_data['age_group'].max_birth_date()
     return super(SadikGroupForm, self).save(commit)
Exemplo n.º 9
0
def create_age_groups_for_sadik(kidgdn):
    current_distribution_year = utils.get_current_distribution_year()
    for age_group in AgeGroup.objects.all():
        group_min_birth_date = age_group.min_birth_date()
        group_max_birth_date = age_group.max_birth_date()
        SadikGroup.objects.create(
            free_places=2,
            capacity=2,
            age_group=age_group, sadik=kidgdn,
            year=current_distribution_year,
            min_birth_date=group_min_birth_date,
            max_birth_date=group_max_birth_date)
Exemplo n.º 10
0
    def get_context_data(self, **kwargs):
        queryset = kwargs.pop('object_list')
        # Отработать форму фильтрации
        page_number = self.request.GET.get('page', None)

        # Обработать фильтры, если они есть
        self.queryset, form = self.process_filter_form(queryset, self.request.GET)

        # Разбить на страницы
        page_size = self.paginate_by
        paginator, page, queryset, is_paginated = self.paginate_queryset(
            self.queryset, page_size, page_number)
#        для всех заявок получаем возрастные группы, которые подходят для них
        age_groups = AgeGroup.objects.all()
        current_distribution_year = get_current_distribution_year()
        for requestion in queryset:
            requestion.age_groups_calculated = requestion.age_groups(
                age_groups=age_groups,
                current_distribution_year=current_distribution_year)
#        для анонимного и авторизованного пользвоателя нужно отобразить какие особые действия совершались с заявкой
        requestions_dict = OrderedDict([(requestion.id, requestion) for requestion in queryset])
#        нам нужны не все логи, а только с определенными действиями
        if queryset:
#            если получать логи при пустом queryset, то все упадет, паджинатор возвращает queryset[0:0] с пустым query
            logs = Logger.objects.filter(content_type=ContentType.objects.get_for_model(Requestion),
                object_id__in=queryset.values_list('id', flat=True), action_flag__in=SPECIAL_TRANSITIONS)
            relation_dict = {}
            for log in logs:
                requestion_log = relation_dict.get(log.object_id)
    #            если для данной заявки не задан лог или он более старый
                if not requestion_log or requestion_log.datetime < log.datetime:
                    relation_dict[log.object_id] = log
            for id, log in relation_dict.items():
                requestions_dict[id].action_log = log
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'requestions_dict': requestions_dict,
            'form': form,
            'target_requestion': self.requestion,
            'offset': (page.number - 1) * page_size,
            'STATUS_DECISION': STATUS_DECISION,
            'import_finished': Preference.objects.filter(
                key=PREFERENCE_IMPORT_FINISHED).exists()
        }

        context.update(kwargs)
        return context
Exemplo n.º 11
0
    def post(self, request):
        if request.POST.get('confirmation') == 'yes':
#            инициируем зачисление
            distribution = Distribution.objects.create(
                year=get_current_distribution_year())
            Vacancies.objects.filter(distribution__isnull=True,
                status__isnull=True).update(distribution=distribution)
            Logger.objects.create_for_action(DISTRIBUTION_INIT,
                 extra={'user': request.user, 'obj': distribution})
            Requestion.objects.filter(status=STATUS_REQUESTER).update(
                status=STATUS_ON_DISTRIBUTION)
            Requestion.objects.filter(status=STATUS_TEMP_DISTRIBUTED).update(
                status=STATUS_ON_TEMP_DISTRIBUTION)
            Requestion.objects.filter(status=STATUS_WANT_TO_CHANGE_SADIK).update(
                status=STATUS_ON_TRANSFER_DISTRIBUTION)
        return HttpResponseRedirect(reverse('decision_manager'))
Exemplo n.º 12
0
def after_distribution_by_resolution(sender, **kwargs):
    transition = kwargs['transition']
    request = kwargs['request']
    form = kwargs['form']
    requestion = kwargs['requestion']
    sadik = form.cleaned_data.get('sadik')
    sadik.create_default_sadikgroups()
    sadik_group = requestion.get_sadik_groups(sadik).filter(
        year=get_current_distribution_year())[0]
    vacancy = Vacancies.objects.create(
        sadik_group=sadik_group, status=VACANCY_STATUS_PROVIDED)
    requestion.distributed_in_vacancy = vacancy
    requestion.save()
    Logger.objects.create_for_action(
        transition.index, context_dict=form.cleaned_data,
        extra={'user': request.user, 'obj': requestion, },
        reason=form.cleaned_data.get('reason'))
def requestions_statistics():
    requestions = Requestion.objects.filter(status__in=(STATUS_REQUESTER,
                                                        STATUS_ON_DISTRIBUTION))
    age_groups = AgeGroup.objects.all()
    requestions_numbers_by_groups = []
    current_distribution_year = get_current_distribution_year()
    for group in age_groups:
        requestions_numbers_by_groups.append(
            requestions.filter_for_age(min_birth_date=group.min_birth_date(current_distribution_year),
                                       max_birth_date=group.max_birth_date(current_distribution_year)).count())
    context = {
        'requestions_number': requestions.count(),
        'benefit_requestions_number': requestions.filter(
            benefit_category__priority__gt=0).count(),
        'groups': age_groups,
        'requestions_numbers_by_groups': requestions_numbers_by_groups
    }
    return context
Exemplo n.º 14
0
    def get_context_data(self, **kwargs):
        queryset = kwargs.pop('object_list')
        # Отработать форму фильтрации
        page_number = self.request.GET.get('page', None)

        # Обработать фильтры, если они есть
        self.queryset, form = self.process_filter_form(queryset, self.request.GET)
        # Разбить на страницы
        page_size = self.paginate_by
        paginator, page, queryset, is_paginated = self.paginate_queryset(
            self.queryset, page_size, page_number)
        # для всех заявок получаем возрастные группы, которые подходят для них
        age_groups = AgeGroup.objects.all()
        current_distribution_year = get_current_distribution_year()
        requestions = queryset
        for requestion in requestions:
            requestion.age_groups_calculated = requestion.age_groups(
                age_groups=age_groups,
                current_distribution_year=current_distribution_year)
        # для анонимного и авторизованного пользователя нужно отобразить
        # какие особые действия совершались с заявкой
        if requestions:
        # если получать логи при пустом queryset, то все упадет,
        # паджинатор возвращает queryset[0:0] с пустым query
            requestions = add_special_transitions_to_requestions(requestions)
        context = {
            'paginator': paginator,
            'page_obj': page,
            'is_paginated': is_paginated,
            'requestions': requestions,
            'form': form,
            'target_requestion': self.requestion,
            'offset': (page.number - 1) * page_size,
            'STATUS_DECISION': STATUS_DECISION,
            'NOT_APPEAR_STATUSES': [STATUS_NOT_APPEAR, ],
            'STATUS_DISTIRIBUTED': STATUS_DISTRIBUTED,
            'import_finished': Preference.objects.filter(
                key=PREFERENCE_IMPORT_FINISHED).exists()
        }

        context.update(kwargs)
        return context
Exemplo n.º 15
0
 def get(self, request, year=None):
     current_distribution_year = get_current_distribution_year().year
     years = [year_date.year for year_date in StatisticsArchive.objects.filter(
         record_type=self.record_type).order_by('year').dates('year', 'year')]
     if current_distribution_year not in years:
         years = [current_distribution_year, ] + years
     if not year:
         year = current_distribution_year
     else:
         year = int(year)
     if year not in years:
         raise Http404
     if year == current_distribution_year:
         context = STATISTIC_HANDLER_FOR_TYPE[self.record_type]()
     else:
         statistic_record = StatisticsArchive.objects.filter(
             record_type=DECISION_STATISTICS, year__year=year)[0]
         context = json.loads(statistic_record.data)
     context.update({'current_year': year, 'years': years})
     return self.render_to_response(context)
Exemplo n.º 16
0
    def get_queue_data(self, requestion):
        before = Requestion.objects.queue().active_queue().requestions_before(requestion)
        benefits_before = before.benefits().count()
        confirmed_before = before.confirmed().count()
        requestions_before = before.count()
        benefits_after = Requestion.objects.active_queue().benefits().count() - benefits_before
        confirmed_after = Requestion.objects.active_queue().confirmed().count() - confirmed_before
        requestions_after = Requestion.objects.active_queue().count() - requestions_before
        offset = max(0, requestions_before - 20)
        queue_chunk = Requestion.objects.queue().hide_distributed().add_distributed_sadiks()[offset:requestions_before + 20]
        queue_chunk = add_special_transitions_to_requestions(queue_chunk)

        # Вычесть свою заявку
        requestions_after -= 1
        if requestion.benefit_category.priority > 0:
            benefits_after -= 1
        if requestion.status == STATUS_REQUESTER:
            confirmed_after -= 1

        # для заявок вычисляем возрастные группы
        age_groups = AgeGroup.objects.all()
        current_distribution_year = get_current_distribution_year()
        for req in queue_chunk:
            req.age_groups_calculated = req.age_groups(
                age_groups=age_groups,
                current_distribution_year=current_distribution_year)
        return {
            'benefits_before': benefits_before,
            'benefits_after': benefits_after,
            'confirmed_before': confirmed_before,
            'confirmed_after': confirmed_after,
            'requestions_before': requestions_before,
            'requestions_after': requestions_after,
            'queue': queue_chunk,
            'offset': offset,
        }
Exemplo n.º 17
0
    def queue_info(self):
        u"""Собирается информация о очереди"""
        info_dict = {}
        distribution = Distribution.objects.filter(status=DISTRIBUTION_STATUS_INITIAL)
        full_queue = Requestion.objects.queue().confirmed().filter(Q(
            status__in=(STATUS_ON_DISTRIBUTION, STATUS_ON_TEMP_DISTRIBUTION),
        ) | Q(
            status=STATUS_DECISION,
            distributed_in_vacancy__distribution=distribution
        )).select_related('benefit_category')
        free_places = SadikGroup.objects.active().aggregate(Sum('free_places'))['free_places__sum']
        queue = []
        distributed_requestions = Requestion.objects.decision_requestions().filter(
            distributed_in_vacancy__distribution=distribution)
        if distributed_requestions.exists():
            last_distributed_requestion = distributed_requestions.reverse()[0]
        else:
            last_distributed_requestion = None
        distributed_requestions_number = distributed_requestions.count()
        current_distribution_year = get_current_distribution_year()
        if free_places:
            # ищем первую заявку, которая может быть распределена
            age_groups = AgeGroup.objects.filter(
                sadikgroup__free_places__gt=0).distinct()
            # первая, распределяемая заявка
            # выставляем в None для дальнейшего сравнения
            current_requestion_exp = None
            # проходимся по всем группам в которых есть места
            for age_group in age_groups:
                # фильтруем по возрастной группе
                query_for_group = Q(birth_date__lte=age_group.max_birth_date(
                    current_distribution_year=current_distribution_year)) & \
                    Q(birth_date__gt=age_group.min_birth_date(
                        current_distribution_year=current_distribution_year))
                # должны быть места в приоритетных ДОУ
                query_for_pref_sadiks = Q(
                    pref_sadiks__groups__free_places__gt=0,
                    pref_sadiks__groups__age_group=age_group,
                    pref_sadiks__groups__active=True)
                # либо указана возможность зачисления в любой ДОУ и в выбранной
                # области есть ДОУ с местами или не указана область
                query_for_any_sadiks = Q(
                    areas__sadik__groups__free_places__gt=0,
                    areas__sadik__groups__age_group=age_group,
                    areas__sadik__groups__active=True)

                # ищем заявку по приоритетным садикам, сравниваем с первой
                requestions_pref_sadiks = full_queue.exclude(
                    status=STATUS_DECISION).exclude(
                        admission_date__gt=datetime.date.today(),).filter(
                            Q(query_for_group & query_for_pref_sadiks))
                try:
                    requestion_pref_sadiks = requestions_pref_sadiks[0]
                    if current_requestion_exp and (
                            requestion_pref_sadiks.position_in_queue() <
                            current_requestion_exp.position_in_queue()):
                        current_requestion_exp = requestion_pref_sadiks
                    elif current_requestion_exp is None:
                        current_requestion_exp = requestion_pref_sadiks
                except IndexError:
                    pass

                # ищем заявку по группам ДОУ, сравниваем с первой
                requestions_any_sadiks = full_queue.exclude(
                    status=STATUS_DECISION).exclude(
                        admission_date__gt=datetime.date.today(),).filter(
                            Q(query_for_group & query_for_any_sadiks))
                try:
                    requestion_any_sadiks = requestions_any_sadiks[0]
                    if current_requestion_exp and (
                            requestion_any_sadiks.position_in_queue() <
                            current_requestion_exp.position_in_queue()):
                        current_requestion_exp = requestion_any_sadiks
                    elif current_requestion_exp is None:
                        current_requestion_exp = requestion_any_sadiks
                except IndexError:
                    pass

            # список заявок, которые могут быть зачислены
            if current_requestion_exp:
                current_requestion = current_requestion_exp
                info_dict.update({'current_requestion': current_requestion,
                    'location_not_verified': current_requestion.location_not_verified,
                    'location_form': ChangeLocationForm(instance=current_requestion),
                    'current_requestion_age_groups': current_requestion.age_groups(
                        current_distribution_year=current_distribution_year)})
                current_requestion_index = full_queue.requestions_before(
                    current_requestion).count()
                if last_distributed_requestion:
                    last_distributed_index = full_queue.requestions_before(
                        last_distributed_requestion).count()
                    inactive_queue = full_queue[last_distributed_index:current_requestion_index]
                    queue = full_queue[current_requestion_index:current_requestion_index + 10]
                else:
                    inactive_queue = full_queue[:current_requestion_index]
                    queue = full_queue[current_requestion_index:current_requestion_index + 10]
            else:
                inactive_queue = []
            info_dict.update({'inactive_queue': inactive_queue})
        info_dict.update({'distribution': distribution, 'queue': queue,
            'free_places': free_places, 'decision_status': STATUS_DECISION,
            'last_distributed_requestion': last_distributed_requestion,
            'distributed_requestions_number': distributed_requestions_number})
        return info_dict
Exemplo n.º 18
0
 def queue_info(self):
     u"""Собирается информация о очереди"""
     info_dict = {}
     distribution = Distribution.objects.filter(status=DISTRIBUTION_STATUS_INITIAL)
     full_queue = Requestion.objects.queue().confirmed().filter(Q(
         status__in=(STATUS_ON_DISTRIBUTION, STATUS_ON_TEMP_DISTRIBUTION,
             STATUS_ON_TRANSFER_DISTRIBUTION),
     ) | Q(
         status=STATUS_DECISION,
         distributed_in_vacancy__distribution=distribution
     )).select_related('benefit_category')
     free_places = SadikGroup.objects.active().aggregate(Sum('free_places'))['free_places__sum']
     queue = []
     distributed_requestions = Requestion.objects.decision_requestions().filter(
         distributed_in_vacancy__distribution=distribution)
     if distributed_requestions.exists():
         last_distributed_requestion = distributed_requestions.reverse()[0]
     else:
         last_distributed_requestion = None
     distributed_requestions_number = distributed_requestions.count()
     current_distribution_year = get_current_distribution_year()
     if free_places:
         #    ищем первую заявку, которая может быть распределена
         age_groups = AgeGroup.objects.filter(sadikgroup__free_places__gt=0
             ).distinct()
         requestions_with_places_query = Q()
     #    проходимся по всем группам в которых есть места и формируем запрос
         for age_group in age_groups:
     #        фильтруем по возрастной группе
             query_for_group = Q(birth_date__lte=age_group.max_birth_date(
                 current_distribution_year=current_distribution_year)) & \
                 Q(birth_date__gt=age_group.min_birth_date(
                     current_distribution_year=current_distribution_year))
     #        должны быть места в приоритетных ДОУ
             query_for_pref_sadiks = Q(pref_sadiks__groups__free_places__gt=0,
                                     pref_sadiks__groups__age_group=age_group,
                                     pref_sadiks__groups__active=True)
     #        либо указана возможность зачисления в любой ДОУ и в выбранной области есть ДОУ с местами
     #        или не указана область
             query_for_any_sadiks = Q(distribute_in_any_sadik=True) & (
                 Q(areas__isnull=True) | Q(areas__sadik__groups__free_places__gt=0,
                                         areas__sadik__groups__age_group=age_group,
                                         areas__sadik__groups__active=True))
     #        собираем все в один запрос
             requestions_with_places_query |= query_for_group & (query_for_pref_sadiks | query_for_any_sadiks)
     #    список заявок, которые могут быть зачислены
         requestions_with_places = full_queue.exclude(status=STATUS_DECISION
             ).exclude(admission_date__gt=datetime.date.today(),
             ).filter(requestions_with_places_query)
         if requestions_with_places.exists():
             current_requestion = requestions_with_places[0]
             info_dict.update({'current_requestion': current_requestion,
                 'current_requestion_age_groups': current_requestion.age_groups(
                     current_distribution_year=current_distribution_year)})
             current_requestion_index = full_queue.requestions_before(
                 current_requestion).count()
             if last_distributed_requestion:
                 last_distributed_index = full_queue.requestions_before(
                     last_distributed_requestion).count()
                 inactive_queue = full_queue[last_distributed_index:current_requestion_index]
                 queue = full_queue[current_requestion_index:current_requestion_index + 10]
             else:
                 inactive_queue = full_queue[:current_requestion_index]
                 queue = full_queue[current_requestion_index:current_requestion_index + 10]
         else:
             inactive_queue = []
         info_dict.update({'inactive_queue': inactive_queue})
     info_dict.update({'distribution': distribution, 'queue': queue,
         'free_places': free_places, 'decision_status': STATUS_DECISION,
         'last_distributed_requestion': last_distributed_requestion,
         'distributed_requestions_number': distributed_requestions_number})
     return info_dict
def show_wait_time_statistics():
    cursor = connection.cursor()
    max_child_age_months = settings.MAX_CHILD_AGE * 12
    current_datetime = datetime.datetime.now()
    current_distribution_year = get_current_distribution_year()
    groups = [{"name": age_group.name, 'short_name': age_group.short_name,
               'min_birth_date': age_group.min_birth_date(current_distribution_year),
               'max_birth_date': age_group.max_birth_date(current_distribution_year), } for age_group
              in AgeGroup.objects.all()]
    wait_intervals = []
    from_months = 0
    for months in xrange(3, max_child_age_months + 1, 3):
        interval = {'name': '%s-%s' % (from_months, months - 1),
                    'from_months': from_months, 'to_months': months, }
        wait_intervals.append(interval)
        from_months = months
    requestions_numbers_by_groups = []
    distributed_requestions_numbers_by_groups = []
    total_requestions_numbers_by_groups = [0] * len(groups)
    # проходим по всем интервалам времени ожидания
    for interval in wait_intervals:
        from_months = interval['from_months']
        to_months = interval['to_months']
        requestions_numbers = []
        distributed_requestions_numbers = []
        # пробегаемся по группам и определяем кол-во заявок
        registration_datetime_max = current_datetime - relativedelta(months=from_months)
        registration_datetime_min = current_datetime - relativedelta(months=to_months)
        for i, group in enumerate(groups):
            delta = relativedelta(
                current_datetime.date(), group['min_birth_date'])
            # если для данной возрастной группы не может быть такого времени ожидания
            if from_months > delta.years * 12 + delta.months or (from_months == delta.years * 12 + delta.months
                                                                 and delta.days == 0):
                requestions_numbers.append(None)
                distributed_requestions_numbers.append(None)
            else:
                # подсчитываем кол-во заявок в очереди для данной группы и для данного интервала
                cursor.execute("""SELECT COUNT(*) FROM "core_requestion"
                    WHERE ("core_requestion"."birth_date" > %(min_birth_date)s AND
                            "core_requestion"."birth_date" <= %(max_birth_date)s) AND
                        ("core_requestion"."registration_datetime" <= %(registration_datetime_max)s AND
                            "core_requestion"."registration_datetime" > %(registration_datetime_min)s) AND
                        "core_requestion"."status" IN %(statuses)s
                    """, {"min_birth_date": group["min_birth_date"], "max_birth_date": group["max_birth_date"],
                          "registration_datetime_max": registration_datetime_max,
                          "registration_datetime_min": registration_datetime_min,
                          "statuses": (STATUS_REQUESTER, STATUS_ON_DISTRIBUTION)})
                requestions_number = cursor.fetchone()[0]
                requestions_numbers.append(requestions_number)
                # для группы прибавляем общее кол-во заявок в ней
                total_requestions_numbers_by_groups[i] += requestions_number
                # кол-во распределенных заявок
                cursor.execute("""SELECT COUNT(*) FROM "core_requestion"
                    WHERE ("core_requestion"."birth_date" > %(min_birth_date)s AND
                            "core_requestion"."birth_date" <= %(max_birth_date)s) AND
                        ("core_requestion"."registration_datetime" <=
                                ("core_requestion"."decision_datetime" - interval '%(from_days)s months') AND
                            "core_requestion"."registration_datetime" >
                                ("core_requestion"."decision_datetime" - interval '%(to_days)s months')) AND
                        "core_requestion"."status" IN (13, 6, 9, 15, 54, 16, 53)
                    """, {"min_birth_date": group["min_birth_date"], "max_birth_date": group["max_birth_date"],
                          "from_days": from_months,
                          "to_days": to_months,
                          "statuses": (STATUS_DISTRIBUTED, ) + DISTRIBUTION_PROCESS_STATUSES})
                distributed_requestions_number = cursor.fetchone()[0]
                distributed_requestions_numbers.append(distributed_requestions_number)
        # для данного интервала список кол-ва заявок по группам
        requestions_numbers_by_groups.append(requestions_numbers)
        distributed_requestions_numbers_by_groups.append(distributed_requestions_numbers)
    total_requestions_number = sum(total_requestions_numbers_by_groups)
    return {
        'requestions_numbers_by_groups': requestions_numbers_by_groups,
        'total_requestions_numbers_by_groups': total_requestions_numbers_by_groups,
        'wait_intervals': wait_intervals,
        'groups': groups,
        'total_requestions_number': total_requestions_number,
        'json': {
            'requestions_numbers_by_groups': simplejson.dumps(requestions_numbers_by_groups),
            'distributed_requestions_numbers_by_groups': simplejson.dumps(distributed_requestions_numbers_by_groups),
            'wait_intervals': simplejson.dumps(wait_intervals),
        },
    }
Exemplo n.º 20
0
    def test_distribution(self):
        management.call_command('generate_sadiks', 10)
        management.call_command('generate_requestions', 200,
                                distribute_in_any_sadik=True)
        Requestion.objects.all().update(status=STATUS_REQUESTER)
        # Requestion.objects.all().update(cast=3)
        current_datetime = datetime.date.today()
        current_distribution_year = get_current_distribution_year()
        for age_group in AgeGroup.objects.all():
            group_min_birth_date = age_group.min_birth_date()
            group_max_birth_date = age_group.max_birth_date()
            for sadik in Sadik.objects.all():
                SadikGroup.objects.create(
                    free_places=10,
                    capacity=10, age_group=age_group, sadik=sadik,
                    year=current_distribution_year,
                    min_birth_date=group_min_birth_date,
                    max_birth_date=group_max_birth_date)
        # группа заявок с датой распределения преывшающей текущую
        # они не должны быть распределены
        requestions_admission_date_ids = list(Requestion.objects.all(
        ).order_by('?')[:30].values_list('id', flat=True))
        try:
            admission_date = current_datetime.replace(
                year=current_datetime.year + 1)
        except ValueError:
            admission_date = current_datetime.replace(
                year=current_datetime.year + 1, day=current_datetime.day - 1)
        Requestion.objects.filter(
            id__in=requestions_admission_date_ids
        ).update(admission_date=admission_date)
        # добавим новые ДОУ без мест и заявки желающие распределиться только
        # в эти ДОУ
        existing_sadiks_ids = list(Sadik.objects.all().values_list(
            'id', flat=True))
        management.call_command('generate_sadiks', 5)
        new_sadiks = list(Sadik.objects.exclude(id__in=existing_sadiks_ids))
        # TODO: Исправить тест, с учетом distribute_in_any_sadik = True!!!
        requestions_pref_sadiks_ids = list(Requestion.objects.exclude(
            id__in=requestions_admission_date_ids
        ).order_by('?')[:30].values_list('id', flat=True))
        for requestion in Requestion.objects.filter(
                id__in=requestions_pref_sadiks_ids):
            requestion.pref_sadiks = new_sadiks
            requestion.distribute_in_any_sadik = True
            requestion.save()
        requestions_area_distribution_ids = list(Requestion.objects.exclude(
            id__in=requestions_admission_date_ids + requestions_pref_sadiks_ids
        )[:30].values_list('id', flat=True))
        Requestion.objects.filter(id__in=requestions_area_distribution_ids
        ).update(distribute_in_any_sadik=True)
        for requestion in Requestion.objects.filter(
                id__in=requestions_area_distribution_ids):
            requestion.areas = (random.choice(Area.objects.all()),)
            requestion.pref_sadiks = []
        client = Client()
        client.login(username=self.operator.username, password="******")
        client.post(reverse('distribution_init'), data={'confirmation': 'yes'},
                    follow=True)
        decision_manager = DecisionManager()
        last_distributed_requestion = None
        queue_info = decision_manager.queue_info()
        total = 0
        while queue_info['free_places'] and queue_info['queue']:
            requestion = queue_info['current_requestion']
            if last_distributed_requestion:
                self.assertEqual(last_distributed_requestion,
                                 queue_info['last_distributed_requestion'], )
            sadiks_for_requestion_dict = decision_manager.sadiks_for_requestion(
                requestion)
            sadiks_for_requestion = \
                sadiks_for_requestion_dict['pref_sadiks'] or \
                sadiks_for_requestion_dict['any_sadiks']
            sadik = sadiks_for_requestion[0]
            if requestion.cast == 1:
                response = client.post(
                    reverse('decision_manager'),
                    data={
                        'sadik': sadik.id,
                        'requestion_id': requestion.id,
                        'accept_location': True}
                )
            else:
                response = client.post(
                    reverse('decision_manager'),
                    data={'sadik': sadik.id, 'requestion_id': requestion.id})
            if response.status_code == 302:
                last_distributed_requestion = requestion
                total += 1
            queue_info = decision_manager.queue_info()

        # проверяем,что заявки с ЖДП, превышающим текущую дату и желающие
        # зачислиться в ДОУ без мест не распределены
        # закомментировал с учетом distribute_in_any_sadik = True
        requestions_not_decision_ids = list(requestions_admission_date_ids)
        # + list(requestions_pref_sadiks_ids)

        self.assertEqual(
            Requestion.objects.filter(
                id__in=requestions_not_decision_ids).filter(
                status=STATUS_DECISION).count(), 0)

        # проверяем, что заявка была зачислена в свою возрастную группу
        for requestion in Requestion.objects.filter(status=STATUS_DECISION):
            self.assertIn(
                requestion.distributed_in_vacancy.sadik_group.age_group,
                requestion.age_groups())

        # проверяем, что заявки, которые указали возможность зачисления в
        # любой ДОУ были зачислены в нужную территориальную область
        for requestion in Requestion.objects.filter(
                id__in=requestions_area_distribution_ids,
                distributed_in_vacancy__isnull=False):
            # проверяем, что заявка попадает в какую-нибудь возрастную группу и
            # может быть распределена
            if requestion.age_groups():
                self.assertEqual(
                    requestion.areas.all()[0],
                    requestion.distributed_in_vacancy.sadik_group.sadik.area)
Exemplo n.º 21
0
 def get_filter_dict(self):
     return {
         'admission_date__year__lte': get_current_distribution_year().year,
         'admission_date__isnull': True,
     }
Exemplo n.º 22
0
 def get_context_data(self, **kwargs):
     context = super(DistributionYearInfo, self).get_context_data(**kwargs)
     context.update({'current_distribution_year': get_current_distribution_year()})
     return context