Ejemplo n.º 1
0
def get_emp_id(employees, current_user, agency_pages):

    emp_id_html = []
    for i in employees:
        if check_struct_access_to_page(current_user, i.agency.headquater,
                                       i.agency, agency_pages, 'read'):
            emp_id_html.append(
                f"<a href='/employee/{str(i.id)}'> <b style='color: #FFD700'> Редактировать </b>"
            )
        else:
            emp_id_html.append(f"<b style='color: #FFD700'> {str(i.id)} </b>")

        print('get_emp:', emp_id_html)
    if len(employees) == 1:
        emp_id_html = emp_id_html[0]

    return emp_id_html
Ejemplo n.º 2
0
def get_medical_docs(request,
                     employee_list,
                     agency_pages=None,
                     client_pages=None,
                     unit_headquarter=None):
    current_user = request.user
    docs_service = get_verme_docs()
    if not docs_service:
        return make_error_response('Undefined: docs_service')

    start = request.GET.get('start')
    end = request.GET.get('end')
    month = request.GET.get('month')

    if unit_headquarter:
        headquarter_max_files_count = Config.objects.filter(
            headquater=unit_headquarter, key='max_files_from_docs').first()
        max_files_count = int(headquarter_max_files_count.value
                              ) if headquarter_max_files_count else 200
    else:
        max_files_count = 200

    doc_guids = list()
    added_files_count = 0

    if isinstance(employee_list, list):
        employee_list = AgencyEmployee.objects.filter(id__in=employee_list)

    # Если передан период
    if (start and end) or month:
        employee_docs = EmployeeDoc.objects.filter(
            doc_type__code='medical', agency_employee__in=employee_list)
        if start and end:
            start = datetime.datetime.strptime(start, '%Y-%m-%d').date()
            end = datetime.datetime.strptime(end, '%Y-%m-%d').date()
            employee_docs = employee_docs.filter(start__lte=start,
                                                 end__gte=end)
        if month:
            month_start = datetime.datetime.strptime(month, '%Y-%m-%d').date()
            month_max_day = calendar.monthrange(month_start.year,
                                                month_start.month)[1]
            month_end = month_start.replace(day=month_max_day)
            employee_docs = employee_docs.filter(start__lte=month_start,
                                                 end__gte=month_end)
        employee_docs = employee_docs.select_related('agency_employee').order_by('agency_employee_id', '-end'). \
            distinct('agency_employee_id')

        for doc in employee_docs:
            # ПРОВЕРКА ПРАВ ДОСТУПА
            has_access = False
            # - проврка доступа для сотрудника агентства
            if check_struct_access_to_page(
                    current_user, doc.agency_employee.agency.headquater,
                    doc.agency_employee.agency, agency_pages, 'read'):
                has_access = True
            # - проверка доступа для сотрудника клиента
            if not has_access:
                clients = employee_clients(doc.agency_employee)
                for client_headquarter in clients:
                    if check_struct_access_to_page(current_user,
                                                   client_headquarter, None,
                                                   client_pages, 'read'):
                        has_access = True
                        break
            if not has_access:
                return make_error_response('AccessDenied')

            if added_files_count > max_files_count:
                return Response({
                    'type': 'error',
                    'message': 'maxFilesCountLimit'
                })
            doc_guids.append(str(doc.guid))
            added_files_count += 1
    else:
        # Если не передан период, возвращаем на текущую дату документ с максимальным сроком действия
        # Последовательно обходим переданных сотрудников и запрашиваем по ним документы
        for employee in employee_list:
            # ПРОВЕРКА ПРАВ ДОСТУПА
            has_access = False
            # - проврка доступа для сотрудника агентства
            if check_struct_access_to_page(current_user,
                                           employee.agency.headquater,
                                           employee.agency, agency_pages,
                                           'read'):
                has_access = True
            # - проверка доступа для сотрудника клиента
            if not has_access:
                clients = employee_clients(employee)
                for client_headquarter in clients:
                    if check_struct_access_to_page(current_user,
                                                   client_headquarter, None,
                                                   client_pages, 'read'):
                        has_access = True
                        break
            if not has_access:
                return make_error_response('AccessDenied')

            # Для каждого сотрудника находим мед книжку с максимальным сроком действия
            if employee.last_medical_guid:
                if added_files_count > max_files_count:
                    return Response({
                        'type': 'error',
                        'message': 'maxFilesCountLimit'
                    })
                doc_guids.append(employee.last_medical_guid)
                added_files_count += 1

    if not doc_guids:
        return Response({'type': 'error', 'message': 'noEntityGuids'})

    # Формируем и отправляем запрос на сервис docs со списком guid требуемых документов
    str_guids = ','.join(doc_guids)
    docs_params = make_docs_params(current_user, str_guids)
    response = docs_service.send_sync_json_request(
        docs_params,
        'archive',
        entity_guids=json.dumps(doc_guids),
        ip=request.META.get('HTTP_X_REAL_IP'),
        format='json')
    return Response(response)
Ejemplo n.º 3
0
def api_quota_volume(request):
    """
    API endpoint, работает в следующих двух режимах:
    - GET - вывод информации о ограничении квоты
    - POST - создание / редактирование одной или нескольких ограничений квот
    - DELETE - удаление ограничения квоты
    """
    current_user = request.user
    page_codes = ['hq_quotas_volume_list']

    # GET - Получение данных по выбранной квоте
    if request.method == 'GET':
        # Поиск объекта квоты
        quota_volume = open_quota_volume(request.GET.get('quota_volume_id', None))
        if not quota_volume:
            return HttpResponseBadRequest("Undefined: quota_volume_id")
        # ПРОВЕРКА ПРАВ ДОСТУПА
        if not check_struct_access_to_page(current_user, quota_volume.store.headquater, quota_volume.store, page_codes,
                                           'read'):
            return HttpResponseBadRequest("AccessDenied")
        # Формируем ответное сообщение
        return Response({"quota": QuotaVolume(quota_volume, many=False).data})

    # POST - Создание, редактирование
    elif request.method == 'POST':
        # Проверка переданных параметров
        serializer = QuotaVolumeWriteSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        # ПРОВЕРКА ПРАВ ДОСТУП
        store = serializer.validated_data['store']
        if not check_struct_access_to_page(current_user, store.headquater, store, page_codes, "write"):
            return make_error_response('AccessDenied')

        # РЕДАКТИРОВАНИЕ
        instance = open_quota_volume(request.data.get('quota_volume_id', None))
        previous_instance = copy(instance)
        if instance:
            # Режим работы: apply - изменение, check - проверка возможности
            mode = request.data.get('mode', None)
            if not mode:
                return make_error_response('Undefined: mode')
            # Применение изменений
            if mode == 'apply':
                instance = serializer.update(instance, serializer.validated_data, current_user)
                instance = open_quota_volume(instance.id)
                instance_diff = instance.get_diff(previous_instance)
                log_handler = log_quota_volume_edit
                log_handler(user_id=request.user.id,
                            entity_id=instance.id,
                            headquarter=instance.store.headquater_id,
                            organization=instance.store_id,
                            start=instance.start,
                            end=instance.end,
                            source_info=None,
                            diff=instance_diff,
                            store_area=instance.area.name
                            )
                return Response('Successfully updated', status=status.HTTP_202_ACCEPTED)
            # Проверка
            else:
                # Получаем список связанных смен
                value = serializer.validated_data['value']
                if value < instance.value:
                    # TODO валидация предупреждения
                    result_count = get_quota_volume_related_quotas(instance).count()
                else:
                    result_count = 0
                return Response({'result': result_count}, status=status.HTTP_200_OK)
        # СОЗДАНИЕ
        else:
            quota_volume = serializer.save()
            log_handler = log_quota_volume_new
            instance_diff = {}
            log_handler(user_id=request.user.id,
                        entity_id=quota_volume.id,
                        headquarter=quota_volume.store.headquater_id,
                        organization=quota_volume.store_id,
                        start=quota_volume.start,
                        end=quota_volume.end,
                        source_info=None,
                        diff=instance_diff,
                        store_area=quota_volume.area.name
                        )
            return Response('Successfully created', status=status.HTTP_201_CREATED)

    # DELETE - Удаление квот
    elif request.method == 'DELETE':
        # Список удаляемых ограничений квот
        quotas_volume_list = json.loads(request.data['quota_volume_ids']) if 'quota_volume_ids' in request.data else []
        # Режиме работы: apply - удаление, check - проверка возможности
        mode = request.data.get('mode', None)
        if not mode:
            return make_error_response('Undefined: mode')

        # Удаление ограничений квот из переданного списка
        result_count = 0
        for quota_volume_id in quotas_volume_list:
            quota_volume = open_quota_volume(quota_volume_id)
            if not quota_volume:
                continue
            # Проверка прав доступа
            if not check_struct_access_to_page(current_user, quota_volume.store.headquater, quota_volume.store,
                                               page_codes, "write"):
                return make_error_response('AccessDenied')
            # Удаляем квоту
            if mode == 'apply':
                log_handler = log_quota_volume_del
                instance_diff = {}
                log_handler(user_id=request.user.id,
                            entity_id=quota_volume.id,
                            headquarter=quota_volume.store.headquater_id,
                            organization=quota_volume.store_id,
                            start=quota_volume.start,
                            end=quota_volume.end,
                            source_info=None,
                            diff=instance_diff,
                            store_area=quota_volume.area.name
                            )
                remove_quota_volume(quota_volume)
                result_count += 1
            # Подсчитываем количество квот, на которые действует ограничение квоты
            else:
                result_count += get_quota_volume_related_quotas(quota_volume).count()

        # Формируем ответ
        if mode == 'apply':
            return Response(f'Successfully deleted: {result_count}', status=status.HTTP_204_NO_CONTENT)
        else:
            return Response({'result': result_count}, status=status.HTTP_200_OK)

    # Неизвестный метод
    return make_error_response('UnknownError')
Ejemplo n.º 4
0
def api_quotas_volume_list(request):
    """
    API-endpoint для получения списка ограничения принимает параметры:
    - area_id - ID категории товара (фильтра, опциональный)
    - organization_id - ID магазина (Фильтр, опциональный)
    возвращает список ограничений квот (QuotaVolume), на основе переданных параметров
    """
    page_codes = ['hq_quotas_volume_list']
    current_user = request.user

    """Определяем орг. единицу"""
    unit_headquarter, unit = open_orgunit(request.GET.get('orgunit', None))
    if not unit_headquarter:
        return make_error_response('Undefined: orgunit')

    """ Проверка прав доступа """
    if not check_struct_access_to_page(current_user, unit_headquarter, unit, page_codes, 'read'):
        return make_error_response('AccessDenied')

    """Получаем organization_id из запроса и фильтруем queryset на основе organization"""
    organization = open_organization(request.GET.get('organization_id', None))

    """Получаем area_id из запроса и фильтруем queryset на основе store_area"""
    store_area = open_storearea(request.GET.get('area_id', None))

    """Получаем дату из запроса"""
    date = request.GET.get('month', None)

    """Формирование queryset для запроса"""
    query_set = make_quotas_volume_queryset(unit_headquarter, unit, date)

    """Копия базового запроса для фильтров"""
    filter_query_set = query_set

    """Ограничиваем запрос по магазину"""
    if organization:
        query_set = query_set.filter(store=organization)

    """Ограничиваем запрос по зоне магазина"""
    if store_area:
        query_set = query_set.filter(area=store_area)

    """Фильтры"""
    # Список магазинов - формируем полный список, т.к. иначе не будет работать выбор в окне добавления новой квоты
    organization_list = Organization.objects.filter(headquater=unit_headquarter, kind='store')
    if unit:
        organization_list = organization_list.filter(Q(id=unit.id) | Q(parent_id=unit.id))
    organization_list = organization_list.order_by('name').annotate(text=F('name')).values('id', 'text')
    area_list = filter_query_set.order_by('area_id').distinct('area_id').values('area_id', 'area__name'). \
        annotate(id=F('area_id'), text=F('area__name')).values('id', 'text')

    """Сортировка"""
    sort_fields = ['store__parent__name', 'store__name', 'area__name', 'value']
    query_set = make_sort(query_set, sort_fields, request.GET.get(u'sort[field]', None),
                          request.GET.get(u'sort[sort]', 'desc'))

    # Выгрузка в Excel
    export = request.GET.get('xlsexport', None)
    if export:
        return get_report_by_code('quota_volume', query_set)

    """Пагинация"""
    query_set, meta = make_pagination(
        query_set,
        request.GET.get('pagination[page]', 1),
        request.GET.get('pagination[perpage]', 10)
    )

    # Формируем ответное сообщение
    ref_data = dict()
    ref_data['meta'] = meta
    ref_data['data'] = QuotaVolumeReadSerializer(query_set, many=True).data
    ref_data['organization_list'] = list(organization_list)
    ref_data['area_list'] = list(area_list)

    return Response(ref_data)
Ejemplo n.º 5
0
def api_quotas_list(request):
    """
    API-endpoint для получения списка квотб принимает параметры:
    - headquater_id - ID компании клиента (обязательный параметр)
    - promo_id - ID агентства (фильтр, опциональный)
    - area_id - ID категории товара (фильтра, опциональный)
    - organization_id - ID магазина (Фильтр, опциональный)
    возвращает список квот, на основе переданных параметров
    """
    page_codes = ['hq_quotas_list']
    current_user = request.user

    """Определяем орг. единицу"""
    unit_headquarter, unit = open_orgunit(request.GET.get('orgunit', None))
    if not unit_headquarter:
        return make_error_response('Undefined: orgunit')

    """ Проверка прав доступа """
    if not check_struct_access_to_page(current_user, unit_headquarter, unit, page_codes, 'read'):
        return make_error_response('AccessDenied')

    """Получаем organization_id из запроса и фильтруем queryset на основе organization"""
    organization = open_organization(request.GET.get('organization_id', None))

    """Получаем promo_id из запроса и фильтруем queryset на основе promo"""
    promo = open_headquarter(request.GET.get('promo_id', None))

    """Получаем area_id из запроса и фильтруем queryset на основе store_area"""
    store_area = open_storearea(request.GET.get('area_id', None))

    """Получаем дату из запроса"""
    date = request.GET.get('month', None)

    """Определяем нарушения"""
    try:
        violations = json.loads(request.GET.get('violation_ids'))
    except:
        violations = []

    """Формирование queryset для запроса"""
    query_set = make_quotas_queryset(unit_headquarter, unit, date)

    """Копия базового запроса для фильтров"""
    filter_query_set = query_set

    """Ограничиваем запрос по промо агентству"""
    if promo:
        query_set = query_set.filter(promo=promo)

    """Ограничиваем запрос по магазину"""
    if organization:
        query_set = query_set.filter(store=organization)

    """Ограничиваем запрос по зоне магазина"""
    if store_area:
        query_set = query_set.filter(area=store_area)

    """Фильтры"""
    # Список магазинов - формируем полный список, т.к. иначе не будет работать выбор в окне добавления новой квоты
    organization_list = Organization.objects.filter(headquater=unit_headquarter, kind='store')
    if unit:
        organization_list = organization_list.filter(Q(id=unit.id) | Q(parent_id=unit.id))
    organization_list = organization_list.order_by('name').annotate(text=F('name')).values('id', 'text')
    area_list = filter_query_set.order_by('area_id').distinct('area_id').values('area_id', 'area__name'). \
        annotate(id=F('area_id'), text=F('area__name')).values('id', 'text')
    promo_list = filter_query_set.order_by('promo_id').distinct('promo_id').values('promo_id', 'promo__name'). \
        annotate(id=F('promo_id'), text=F('promo__name')).values('id', 'text')

    """Сортировка"""
    sort_fields = ['store__parent__name', 'store__name', 'area__name', 'value', 'value_ext']
    query_set = make_sort(query_set, sort_fields, request.GET.get(u'sort[field]', None),
                          request.GET.get(u'sort[sort]', 'desc'))

    """Фильтрация по нарушениям"""
    if violations:
        for violation_id in violations:
            violation = open_violation_level(violation_id)
            if violation:
                query_set = violation.check_queryset(query_set, date)

    # Выгрузка в Excel
    export = request.GET.get('xlsexport', None)
    if export:
        return get_report_by_code('quota', query_set)

    """Пагинация"""
    query_set, meta = make_pagination(
        query_set,
        request.GET.get('pagination[page]', 1),
        request.GET.get('pagination[perpage]', 10)
    )

    for quota in query_set:
        quota.max_value = quota.max_value(date)
        quota.free_value = quota.free_value(date)
        quota.is_active = quota.check_if_active(date)
        quota.shifts_count = quota.shifts_count(date)
        quota.open_shifts_count = quota.open_shifts_count(date)

    # Формируем ответное сообщение
    ref_data = dict()
    ref_data['meta'] = meta
    ref_data['data'] = QuotaReadSerializer(query_set, many=True).data
    ref_data['promo_list'] = list(promo_list)
    ref_data['organization_list'] = list(organization_list)
    ref_data['area_list'] = list(area_list)
    ref_data['violations_list'] = make_violations_data(page_codes, unit_headquarter.party)

    return Response(ref_data)
Ejemplo n.º 6
0
def api_get_claims(request):
    """API endpoint для получения списка претензий
    принимает параметры:
    agency_id или headquater_id типа int (1)
    возвращает список job_history [{'id':, 'job':, 'start':, 'end':}]
    """
    # Доступные страницы
    page_codes = ['claims_list', 'hq_claims_list', 'promo_claims_list', 'broker_claims_list']
    current_user = request.user

    """Определяем орг. единицу"""
    unit_headquarter, unit = open_orgunit(request.GET.get('orgunit', None))
    if not unit_headquarter:
        unit_headquarter = open_headquarter_by_code(request.GET.get('headquater_code', None))
        unit = open_organization_by_code(request.GET.get('orgunit_code', None), unit_headquarter)

    if not unit_headquarter:
        return make_error_response('Undefined: orgunit')

    """ Проверка прав доступа """
    if not check_struct_access_to_page(current_user, unit_headquarter, unit, page_codes, 'read'):
        return make_error_response('AccessDenied')

    """Получаем agency_id из запроса и фильтруем queryset на основе agency"""
    agency = open_agency(request.GET.get('agency_id', None))

    """Получаем headquater_id из запроса и фильтруем queryset на основе agency"""
    headquarter = open_headquarter(request.GET.get('headquater_id', None))

    """Получаем organization_id из запроса и фильтруем queryset на основе organization"""
    organization = open_organization(request.GET.get('organization_id', None))

    """Получаем дату из запроса"""
    date = request.GET.get('date', None)

    """Получаем period_start из запроса"""
    period_start = request.GET.get('period_start', None)

    """Получаем period_end из запроса"""
    period_end = request.GET.get('period_end', None)

    """Формирование queryset для запроса"""
    query_set = make_claims_queryset(unit_headquarter, unit, date, period_start, period_end)

    """Копия базового запроса для фильтров"""
    filter_query_set = query_set

    """Ограничиваем запрос по клиенту"""
    if headquarter:
        query_set = query_set.filter(headquater=headquarter)

    """Ограничиваем запрос по агентству"""
    if agency:
        query_set = query_set.filter(agency=agency)

    """Ограничиваем запрос по организации"""
    if organization:
        query_set = query_set.filter(organization=organization)

    """Ограничиваем по выбранному статусу заявки"""
    status = request.GET.get('status_code', 'all')
    if status != 'all':
        query_set = query_set.filter(status__code=status)

    """Фильтры"""
    agency_list = filter_query_set.order_by('agency_id').\
        distinct('agency_id').select_related('agency').values('agency_id', 'agency__name').\
        annotate(id=F('agency_id'), text=F('agency__name')).values('id', 'text')
    organization_list = filter_query_set.select_related('organization').order_by('organization_id').\
        distinct('organization_id').values('organization_id', 'organization__name').\
        annotate(id=F('organization_id'), text=F('organization__name')).values('id', 'text')

    """Сортировка"""
    sort_fields = [
        'number',
        'organization__name',
        'organization__parent__name',
        'agency__name',
        'claim_type',
        'status__name',
        'dt_created',
        'dt_updated',
        'dt_status_changed'
    ]
    query_set = make_sort(query_set, sort_fields, request.GET.get(u'sort[field]', None),
                          request.GET.get(u'sort[sort]', 'desc'))

    """Файлы и последнее сообщение по претензиям"""
    for claim in query_set:
        attachments = ClaimAttach.objects.filter(claim=claim, message__isnull=True)
        if attachments:
            attachments_list = []
            for attachment in attachments:
                attachments_list.append(attachment)
            claim.attachments = attachments_list
        last_message = ClaimMessage.objects.filter(claim=claim).order_by('dt_created').first()
        if last_message:
            claim.dt_last_message = last_message.dt_created

    # Выгрузка в Excel
    export = request.GET.get('xlsexport', None)
    if export:
        return get_report_by_code('claim', query_set)

    """Пагинация"""
    query_set, meta = make_pagination(
        query_set,
        request.GET.get('pagination[page]', 1),
        request.GET.get('pagination[perpage]', 10)
    )

    # Формируем ответное сообщение
    ref_data = dict()
    ref_data['meta'] = meta
    ref_data['data'] = ClaimSerializer(query_set, many=True).data
    ref_data['agency_list'] = list(agency_list)
    ref_data['org_list'] = list(organization_list)

    return Response(ref_data)