Ejemplo n.º 1
0
def page_menu(context):
    role_name = context['role']

    if context['role'] == 'admin' or context['role'] == 'corporate':
        if 'market_id' in context['request'].session:
            market_id = context['request'].session['market_id']
        else:
            market = get_user_market_or_main_market(context['request'].user)
            market_id = context['request'].session['market_id'] = market.pk
    else:
        market = get_user_market_or_main_market(context['request'].user)
        market_id = market.pk

    if context['role'] == 'corporate':
        role = Roles.objects.filter(name='coordinator').get()
        role_id = role.pk
    else: 
        role = Roles.objects.filter(name=role_name).get()
        role_id = role.pk

    role = Roles.objects.filter(name='all').get()
    role_id_all = role.pk

    query_set = Category.objects.prefetch_related('pages').order_by('name')

    if context['role'] == 'admin':
        query_set = query_set.filter(market_id=market_id, is_active=True)
    elif context['role'] == 'trainee':
        query_set = query_set.filter(market_id=market_id, role_id=role_id, is_active=True)
    else:
        query_set = query_set.filter(
            market_id=market_id, is_active=True, role_id__in=[role_id, role_id_all]
        )

    return {'categories': query_set, 'context': context}
Ejemplo n.º 2
0
def update_network(request, role=None):
    data = json.loads(request.body)
    if not role:
        role = get_role(request.user)

    id = data.get('id')
    url = data.get('url')
    active = data.get('active')
    type = data.get('type')

    if id == 0:
        if role == 'corporate':
            if 'market_id' in request.session:
                market_id = request.session['market_id']
                market = Market.objects.filter(pk=market_id).get()
            else:
                market = get_user_market_or_main_market(request.user)
        else:
            market = get_user_market_or_main_market(request.user)
        network = SocialNetwork(market=market, type_id=type)
    else:
        network = SocialNetwork.objects.get(pk=id)

    network.active = active
    network.url = url
    network.save()

    response = {
        'id': network.pk,
        'url': network.url,
        'active': network.active,
        'type': network.type_id
    }

    return JsonResponse(response)
Ejemplo n.º 3
0
def programs_list(request):
    role = request.user.role
    menu_type = request.GET.get('menu_type', 'finance')

    if role.code == 'corporate':
        market = get_market_or_main_market(request, menu_type)
        # add role finance
    elif role.code == 'admin' or 'finance':
        if 'market_id' in request.session:
            market_id = request.session['market_id']
            market = Market.objects.filter(pk=market_id).get()
        else:
            market = get_user_market_or_main_market(request.user)
    else:
        market = get_user_market_or_main_market(request.user)

    programs = (Program.objects.select_related(
        'program_base__city__state__country',
        'program_base__category').is_visible_by_role(
            role.code).by_market(market).is_active().annotate(
                total=Count('id')))
    # add market
    context = {'programs': programs, 'menu_type': menu_type, 'market': market}

    return render(request, 'programs/programs_list.html', context)
Ejemplo n.º 4
0
def program_permission(user, market, program_query):
    if user.is_authenticated:
        role = get_role(user)

        if role == "admin":
            if market:
                program_query = filter_by_market_name(program_query, market)
            else:
                market_obj = get_user_market_or_main_market(user)
                program_query = program_query.filter(markets=market_obj)

        else:
            market_obj = get_user_market_or_main_market(user)
            if market_obj.name.lower() == market or not market:
                program_query = program_query.is_visible_by_role(role).filter(
                    markets=market_obj)
            else:
                program_query = []
    else:
        if market:
            program_query = filter_by_market_name(program_query, market)
        else:
            market_program = Market.objects.get(main_market=True)
            program_query = program_query.filter(markets=market_program)

    return program_query
Ejemplo n.º 5
0
def change_log_index(request):
    request_data = json.loads(request.body)

    newest_id = request_data.get('newest_id', 0)
    latest_id = request_data.get('latest_id', 0)

    market = get_user_market_or_main_market(request.user)

    update_query_set = ChangeLog.objects.filter(
        Q(program__markets=market) |
        Q(page_attachment__page__market=market)
    )

    if latest_id:
        update_query_set = update_query_set.filter(id__lt=latest_id)

    updates = update_query_set.prefetch_related(
        'program', 'category', 'page_attachment__page__category',
        'page_attachment__category', 'page_attachment__country',
        'page_attachment__visa_type'
    ).order_by('-id')[:10]

    response = {
        'updates': updates.as_dict_list()
    }

    return JsonResponse(response, status=200)
Ejemplo n.º 6
0
def social_networks_json(request):
    role = get_role(request.user)

    if role in ['corporate', 'admin']:
        market_id = request.session['market_id']
        market = Market.objects.filter(pk=market_id).get()
    else:
        market = get_user_market_or_main_market(request.user)

    social_models = SocialNetworkTypes.objects.prefetch_related(
        Prefetch("social_networks",
                 queryset=SocialNetwork.objects.filter(market=market),
                 to_attr="networks"))

    networks = []
    for social in social_models:
        network = {
            'id': 0,
            'active': False,
            'url': "",
            'type_id': social.pk,
            'social': social.name,
            'icon': social.icon.url,
        }

        if len(social.networks) > 0:
            network['id'] = social.networks[0].pk
            network['active'] = social.networks[0].active
            network['url'] = social.networks[0].url

        networks.append(network)

    response = {'data': networks}

    return JsonResponse(response)
Ejemplo n.º 7
0
def home(request):
    role = get_role(request.user)

    tags = Tag.objects.all()

    posts = Post.objects.prefetch_related('author')
    if role not in ['admin', 'coordinator', 'corporate']:
        posts = posts.filter(Q(status=1) | Q(author=request.user))
    else:
        posts = posts.exclude(Q(status=2))

    posts = posts.order_by('-id')

    if not role == "coordinator":
        market = get_user_market_or_main_market(request.user)
        coordinators = ConsultantProfile.objects.select_related(
            'consultant').get_coordinator_by_market(market)
    else:
        coordinators = None

    context = {
        'role': role,
        'posts': output_posts(request, role, posts),
        'tags': tags,
        'coordinators': coordinators,
        'user': request.user,
        'user_name': request.user.person.get_full_name()
    }

    if role == "corporate":
        context['menu_type'] = 'general'

    return render(request, 'board/board.html', context)
Ejemplo n.º 8
0
def market_session(request):
    if 'market_id' in request.session:
        market_id = request.session['market_id']
    else:
        market = get_user_market_or_main_market(request.user)
        market_id = market.pk
    
    market = Market.objects.filter(pk=market_id).get()
    return market
Ejemplo n.º 9
0
def market_name_session(request):
    import unidecode
    if 'market_id' in request.session:
        market_id = request.session['market_id']
        marketSelected = Market.objects.filter(pk=market_id).get()
    else:
        marketSelected = get_user_market_or_main_market(request.user)
    market = unidecode.unidecode(marketSelected.name)
    return market
Ejemplo n.º 10
0
def get_grades(request):
    market_id = request.GET.get('market_id', 0)

    if market_id == 0:
        market_id = get_user_market_or_main_market(request.user)

    grades = Grades.objects.filter(market=market_id)

    if not grades:
        market_id = get_user_market_or_main_market(request.user)
        grades = Grades.objects.filter(market=market_id)

    results = []
    for grade in grades:
        grades_dict = {'id': grade.pk, 'name': grade.name}
        results.append(grades_dict)

    return JsonResponse(results, safe=False)
Ejemplo n.º 11
0
def create_post(request):
    role = get_role(request.user)

    tags = Tag.objects.all()
    form = PostForm()
    if request.method == 'POST':
        form = PostForm(data=request.POST, files=request.FILES)
        if form.is_valid():
            market = get_user_market_or_main_market(request.user)

            post = form.save(commit=False)
            post.author = request.user
            post.market = market
            if role == "coordinator" or role == "admin":
                post.status = 1

            post.save()

            short_title = (post.title[:25] +
                           '..') if len(post.title) > 25 else post.title
            details = (post.content[:100] +
                       '..') if len(post.content) > 100 else post.content
            description = u'New board created - {}'.format(short_title)

            notification = create_notification_from(post)
            notification.type = 3
            notification.creator = request.user
            notification.description = description
            notification.details = details
            notification.save()

            coordinators_ids = (
                ConsultantProfile.objects.prefetch_related('consultant').
                get_coordinator_by_market(market).is_active().values_list(
                    'consultant__id', flat=True))

            bulk_receiver_creation(notification, coordinators_ids)

            if role == "coordinator" or role == "admin":
                messages.success(request, 'Post successfully created.')
            else:
                messages.success(
                    request,
                    'Post successfully created. An administrator will review it shortly.'
                )
            return redirect('/board/')
        else:
            messages.error(
                request,
                'There was a problem creating the post. Please correct the errors and try again.'
            )

    if role == 'corporate':
        menu_type = 'general'

    return render(request, 'board/create.html', locals())
Ejemplo n.º 12
0
def school_grade_validate(request):
    role = get_role(request.user)

    if role == 'admin':
        if 'market_id' in request.session:
            market_id = request.session['market_id']
            market = Market.objects.filter(pk=market_id).get()
        else:
            market = get_user_market_or_main_market(request.user)
    else:
        market = get_user_market_or_main_market(request.user)

    grades = Grades.objects.filter(market=market)
    if not grades:
        school_grade = False
    else:
        school_grade = True

    return school_grade
Ejemplo n.º 13
0
def supervisor_consultant_list(request):
    """
    Retrieve the supervisor consultant list
    """
    role = request.user.role

    consultants = get_user_model().objects.select_related(
        'person__profile__address__city',
        'person__profile__address__state',
        'person__profile__address__country',
        'consultantprofile',
    ).filter(is_active=True).can_create_register().annotate(
        registrations_count=Count(
            'registrations',
            filter=Q(registrations__helper_creator=request.user)))

    if role.code in ['admin', 'coordinator', 'info', 'corporate']:
        if role.code in ['coordinator', 'info']:
            market = get_user_market_or_main_market(request.user)
        else:
            if 'market_id' in request.session:
                market_id = request.session['market_id']
            else:
                market = get_user_market_or_main_market(request.user)
                market_id = market.pk

            market = Market.objects.filter(pk=market_id).get()

        consultants = consultants.filter(consultantprofile__market=market)
    else:
        consultants = consultants.filter(
            consultantprofile__supervisor=request.user)

    context = {
        'consultants': consultants,
    }

    if role.code == 'corporate':
        context['menu_type'] = 'general'

    return render(request, 'profiles/supervisor_consultant_list.html', context)
Ejemplo n.º 14
0
def image_preview(request, uuid):
    """
    Return card rendered as image
    """

    user = get_user_model().objects.get(username=uuid)
    market = get_user_market_or_main_market(user)
    card_template, created = CardTemplate.objects.get_or_create(market=market)

    # Adjust width size to fit template
    width = 382
    if card_template.enabled == 2:
        width = 618

    url = '{}?iframe=True&template={}'.format(
        request.build_absolute_uri(
            reverse('cards:view_usercard', args=[user.username])),
        card_template.enabled)

    options = {'width': width, 'xvfb': '', 'format': 'png', 'quiet': ''}
    img = imgkit.from_url(url, False, options=options)
    return HttpResponse(img, content_type='image/png')
Ejemplo n.º 15
0
def pagesMarkets(request):
    market = get_user_market_or_main_market(request.user)
    markets = Market.objects.all().exclude(pk=14).order_by('name')
    context = {'menu_type': 'administration', 'markets': markets}

    return render(request, 'catalogs/pages_markets.html', context)
Ejemplo n.º 16
0
def index(request):
    role = get_role(request.user)

    start_date = datetime.fromisoformat(request.GET.get('start')).astimezone(
        pytz.utc).strftime("%Y-%m-%d %H:%M:%S")
    end_date = datetime.fromisoformat(request.GET.get('end')).astimezone(
        pytz.utc).strftime("%Y-%m-%d %H:%M:%S")

    if role in ['admin', 'corporate', 'finance']:
        if 'market_id' in request.session:
            market_id = request.session['market_id']
        else:
            market = get_user_market_or_main_market(request.user)
            market_id = market.pk
    else:
        market = get_user_market_or_main_market(request.user)
        market_id = market.pk

    sql = (
        "SELECT distinct(ee.id) FROM events_event ee " +
        "LEFT JOIN events_event_markets eem on ee.id = eem.event_id "
        "LEFT JOIN events_eventusers eeu on ee.id = eeu.event_id and eeu.user_id = %s "
        + "WHERE (" + "(ee.start >= %s and ee.end <= %s) or " +
        "(ee.start >= %s and ee.start <= %s and ee.end is null)" + ") and (" +
        "(" + "visibility = 5 and (" +
        "(eem.market_id = %s and eeu.user_id = %s and eeu.hide = false) or" +
        "(eem.market_id is null and eeu.user_id = %s and eeu.hide = false) or "
        + "(eeu.hide is null and eem.market_id = %s) or " +
        "(not ee.user_id = eeu.user_id and eeu.user_id = %s and eeu.hide = false)"
        + ")" + ") or " +
        "(visibility = 4 and (eeu.hide = false or eeu.hide is null)) or "
        "(visibility = 2 and ee.user_id = %s) or "
        "(visibility is null and ee.user_id = %s) or "
        "ee.user_id = %s"
        ")")

    events = Event.objects.filter(
        pk__in=RawSQL(sql, (request.user.pk, start_date, end_date, start_date,
                            end_date, market_id, request.user.pk,
                            request.user.pk, market_id, request.user.pk,
                            request.user.pk, request.user.pk,
                            request.user.pk)))

    data = []
    for event in events:
        item = {
            'id': event.id,
            'title': event.title,
            'start': localtime(event.start).isoformat() if event.start else '',
            'end': localtime(event.end).isoformat() if event.end else '',
            'eventColor': event.color,
            'description': event.description,
            'url': event.url,
            'allDay': event.all_day,
            'userId': int(0 if event.user is None else event.user.id),
            'reminderId': event.reminder_id if event.reminder_id else '',
            'isOwner': (event.user_id == request.user.pk)
        }

        if event.reminder_id:
            item['reminder'] = {
                'id':
                event.reminder.pk,
                'registrationId':
                event.reminder.registration_id
                if event.reminder.registration_id else ''
            }

        data.append(item)

    return JsonResponse(data, safe=False)
Ejemplo n.º 17
0
def usercard(request, uuid, iframe, signature, preview, template):

    iframe = request.GET.get('iframe', False)
    signature = request.GET.get('signature', False)
    preview_signature = request.GET.get('preview_signature', False)
    current_signature = request.GET.get('current_signature', False)
    role_id = request.GET.get('role_id')
    preview = request.GET.get('preview', False)
    template = request.GET.get('template', 1)

    try:
        user = get_user_model().objects.select_related('person').get(
            username=uuid)
    except Exception:
        return render(request, 'inactive_card.html')

    market = get_user_market_or_main_market(user)
    role = user.role.name

    card_market, created = CardMarket.objects.get_or_create(market=market)
    card_template, created = CardTemplate.objects.get_or_create(market=market)
    enabled_card = card_market.is_enabled_card(market)

    base_url = request.build_absolute_uri()

    common_name = user.common_name
    business_card_name = user.business_card_name
    phone_mobile = user.person.profile.get_phone_mobile()

    try:
        city = user.person.profile.address.city.name
    except Exception:
        city = ''

    networks = SocialNetwork.objects.filter(market=market,
                                            active=True).select_related('type')

    try:
        country = user.person.profile.address.country.name
    except Exception:
        country = ''

    # Calculate offset to social_networks
    offset = 2
    if networks:
        count = len(networks)
        offset = int(12 / count)

    # Card with horizontal layout
    card_layout = 'vertical'
    if card_template.enabled == 2:
        card_layout = 'horizontal'

    context = {
        'user': user,
        'role': role,
        'common_name': common_name,
        'business_card_name': business_card_name,
        'phone_mobile': phone_mobile,
        'city': city,
        'market': market,
        'country': country,
        'offset': offset,
        'card_url': base_url,
        'iframe_url': base_url + '?iframe=True',
        'social_networks': networks,
        'card_layout': card_layout,
        'preview': preview,
    }

    # Render image with management command in corporate template settings
    # python manage.py card_previews
    if iframe and preview:
        t = "cards/template{}_iframe.html".format(template)
        return render(request, t, context)

    # To render in card public home
    if iframe and not preview:
        t = "cards/template{}_iframe.html".format(card_template.enabled)
        return render(request, t, context)

    if signature:
        return render(request, 'cards/signature_iframe.html', context)

    if preview_signature or current_signature:
        # Signature settings detail
        if preview_signature:
            elements_list = []
            signature_elements = PreviewEmailSignature.objects.filter(
                role__pk=role_id)
            image_element = PreviewImageAsElementSignature.objects.filter(
                role__pk=role_id).last()

        # List current signatures by role
        if current_signature:
            elements_list = []
            signature_elements = EmailSignature.objects.filter(
                role__pk=role_id)
            image_element = ImageAsElementSignature.objects.filter(
                role__pk=role_id).last()

        # Add extra element variables to context
        try:
            context['image'] = image_element.file.url
        except Exception:
            context['image'] = None

        for element in signature_elements:
            elements_list.append(element.as_rendered_dict(context))

        context['elements'] = elements_list

        return render(request, 'cards/signature_base.html', context)

    if not enabled_card or not user.is_active:
        return render(request, 'inactive_card.html')

    home_count = CardCountVisit()
    home_count.user = user
    home_count.click_type = 1
    home_count.save()

    return render(request, 'cards/card_home.html', context)
Ejemplo n.º 18
0
def calendar_dashboard(request, role=None):
    activities = []
    users_list = []
    markets_dict = []

    if not role:
        role = get_role(request.user)

    if role in ['corporate', 'admin', 'finance']:
        if 'market_id' in request.session:
            market_id = request.session['market_id']
            market = Market.objects.filter(pk=market_id).get()
        else:
            market = get_user_market_or_main_market(request.user)
    else:
        market = get_user_market_or_main_market(request.user)
    roles = ['corporate', 'coordinator', 'admin', 'finance']
    if role in roles:
        users = get_user_model().objects.prefetch_related(
            'consultantprofile__market', 'person').filter(
                Q(groups__name='new markets coordinator')
                | Q(groups__name='supervisors') | Q(groups__name='free agents')
                | Q(groups__name='consultants') | Q(groups__name='info')
                | Q(groups__name='corporate admin')
                | Q(groups__name='super admin')
                | Q(groups__name='finances')).exclude(
                    Q(pk=request.user.pk)).filter(is_active=True)

        if role == 'coordinator':
            users = users.filter(consultantprofile__market=market)
            markets_dict.append(market.as_dict())
        else:
            markets_dict = Market.objects.filter(is_active=True).as_dict_list()

        for user in users.distinct():
            users_list.append({
                'id': user.pk,
                'common_name': user.common_name,
                'email': user.person.email
            })

    pages = Page.objects.all()

    default_period = AcademicPeriod.objects.next_to_current_period()

    update_query_set = ChangeLog.objects.filter(
        Q(program__markets=market)
        | Q(page_attachment__page__market=market)).filter(
            program__visibility=True, program__is_active=True)

    updates = update_query_set.prefetch_related(
        'program__program_base', 'category', 'page_attachment__page__category',
        'page_attachment__category', 'page_attachment__country',
        'page_attachment__visa_type').order_by('-id')[:10]

    if role in ['consultant', 'free_agent', 'supervisor']:
        tracing_query_set = Registration.objects.filter(
            status=1,
            consultant=request.user,
            tracing__completed_date__isnull=True).exclude(
                academic_period__start_date__year='2015', ).annotate(
                    student_full_name=Concat(
                        'costumer__first_name', Value(' '),
                        'costumer__last_name'), ).select_related(
                            'costumer', 'tracing__lead').prefetch_related(
                                'tracing__follow_ups', 'tracing__meetings',
                                'tracing__decision_makings')

        for registration in tracing_query_set.all():
            student_full_name = registration.student_full_name.strip()
            current_step = registration.tracing.get_current_step()
            next_step = registration.tracing.get_next_step()

            if next_step['id'] != current_step['id']:
                continue

            activities.append({
                'id':
                registration.pk,
                'studentFullName':
                student_full_name if student_full_name else 'NO NAME',
                'step':
                current_step['step'],
                'datetime':
                '' if current_step['step'] == 1 else current_step['date']
            })

    request_context = {
        'role':
        role,
        'pages':
        pages,
        'total_comission':
        0,
        'timezone':
        settings.TIME_ZONE,
        'updates_count':
        update_query_set.count(),
        'default_period':
        default_period,
        'market':
        market,
        'updates_json':
        json.dumps({
            'updates': updates.as_dict_list(),
            'count': update_query_set.count()
        })
    }

    context_json = {
        'activities': activities,
        'defaultPeriod': {
            'id': default_period.pk,
            'startDate': default_period.start_date.strftime('%Y-%m-%d'),
            'endDate': default_period.end_date.strftime('%Y-%m-%d')
        },
        'steps': tuple_as_dict(STEP_CHOICES),
        'reminderOptions': tuple_as_dict(REMINDER_CHOICES),
        'byOptions': tuple_as_dict(BY_CHOICES),
        'timezone': settings.TIME_ZONE,
        'marketId': market.pk,
        'market': market.as_dict(),
        'markets': markets_dict,
        'user': request.user.as_dict(),
        'usersList': users_list,
        'urls': {
            'changeLogIndex': reverse('api_activities:change_log_index'),
            'chartSalesTarget':
            reverse('api_registrations:chart_sales_target'),
            'chartProspects': reverse('api_registrations:chart_prospects'),
            'chartCustomers': reverse('api_registrations:chart_customers'),
            'registrationCards': reverse('registration:cards_show', args=[0]),
            'events': reverse('api_events:index'),
            'eventRemove': reverse('api_events:remove'),
            'eventCreateEdit': reverse('api_events:create_edit'),
            'event': reverse('api_events:event')
        }
    }

    if role == 'corporate':
        request_context['menu_type'] = 'general'

    if role:
        request_context['markets'] = Market.objects.all()

    request_context['context_json'] = json.dumps(context_json)

    return render(request, 'events/dashboard.html', request_context)
Ejemplo n.º 19
0
def dt_get_registrations_consultant_list(request):
    academic_period_id = request.POST.get('academic_period_id', None)
    status_id = request.POST.get('status_id', None)
    results = []
    role = get_role(request.user)

    columns = {
        'academic_period': 'academic_period',
        'status': 'status',
        'student_name': 'student_full_name',
        'consultant': 'consultant__common_name',
        'created': 'created',
        'registration_date': 'registration_date',
        'finance_date': 'finance_date',
        'customer_date': 'customer_date',
        'follow_up': 'costumer',
    }

    data_table = DataTable(request.POST, columns)

    market = get_user_market_or_main_market(request.user)

    query_set = Registration.objects.select_related(
        'costumer', 'consultant',
        'academic_period').active().annotate(student_full_name=Concat(
            'costumer__first_name', Value(' '),
            'costumer__last_name'), ).exclude(
                academic_period__start_date__year='2015')

    if role == 'corporate' or role == 'finance':
        pass
    elif role in ['coordinator', 'info']:
        query_set = query_set.by_consultantprofile_market(market)
    elif role in ['admin']:
        if 'market_id' in request.session:
            market_id = request.session['market_id']
            market = Market.objects.filter(pk=market_id).get()
            query_set = query_set.by_consultantprofile_market(market)
    else:
        query_set = query_set.filter(consultant=request.user)

    registration_list = []
    notes_dict = {}
    if role == "info" or role == "coordinator":
        # for info and coordinator roles we added last notes in each registration that can cause a lot of extra queries
        notes_values = Note.objects.values('registration_id').annotate(
            max_id=Max('id'))
        recent_notes_ids = [k['max_id'] for k in notes_values]

        notes = Note.objects.filter(id__in=recent_notes_ids)

        for note in notes:
            notes_dict[note.registration_id] = note

    default_period = AcademicPeriod.objects.next_to_current_period()

    total = query_set.count()

    if data_table.search_value != "":
        try:
            query_set = query_set.filter(
                Q(student_full_name__icontains=data_table.search_value)
                | Q(consultant__common_name__icontains=data_table.search_value)
            )
        except ValueError:
            query_set = query_set.filter(
                Q(costumer__icontains=data_table.search_value))

    if academic_period_id:
        query_set = query_set.filter(academic_period_id=academic_period_id)

    if status_id:
        query_set = query_set.filter(status=status_id)
    else:
        query_set = query_set.filter(status__in=['1', '2', '3', '4'])

    records_filtered = query_set.count()

    query_set = query_set.order_by(*data_table.get_orderings())

    registrations = query_set[data_table.start:data_table.limit]

    extra_note = ''

    for registration in registrations:
        if registration.pk in notes_dict:
            extra_note = notes_dict[registration.pk].description

        result = {
            'id':
            registration.pk,
            'academic_period':
            registration.academic_period.get_year(),
            'status':
            registration.get_status_display(),
            'student_name':
            registration.costumer.get_full_name()
            if registration.costumer.get_full_name() else u'No Name',
            'consultant':
            registration.consultant.common_name,
            'created':
            registration.created.strftime("%Y-%m-%d")
            if registration.created else '',
            'registration_date':
            registration.registration_date.strftime("%Y-%m-%d")
            if registration.registration_date else '',
            'finance_date':
            registration.finance_date.strftime("%Y-%m-%d")
            if registration.finance_date else '',
            'customer_date':
            registration.customer_date.strftime("%Y-%m-%d")
            if registration.customer_date else '',
            'follow_up':
            extra_note if extra_note else ''
        }

        results.append(result)

    response = {
        'draw': data_table.draw,
        'recordsTotal': total,
        'recordsFiltered': records_filtered,
        'data': results
    }

    return JsonResponse(response, status=200)
Ejemplo n.º 20
0
def image(request, uuid, filetype, preview, template):
    """
    Return card rendered as image
    """
    import os
    from pyvirtualdisplay import Display

    filetype = request.GET.get('filetype', 'png')
    preview = request.GET.get('preview', False)
    template = request.GET.get('template', '1')

    user = get_user_model().objects.get(username=uuid)
    market = get_user_market_or_main_market(user)
    card_template, created = CardTemplate.objects.get_or_create(market=market)

    # Adjust width size to fit template
    width = 382
    if card_template.enabled == 2 or template == '2':
        width = 618

    base_url = request.build_absolute_uri(
        reverse('cards:view_usercard', args=[user.username]))

    iframe_url = base_url + '?iframe=True'
    if preview:
        iframe_url = base_url + '?iframe=True&preview=True&template={}'.format(
            template)

    filename = 'Ad_Astra_{}.{}'.format(
        user.business_card_name.strip().replace(' ', '_'), filetype)

    options = {'width': width, 'xvfb': ''}
    xephyr = Display(visible=0, size=(650, 650))
    xephyr.start()

    try:
        imgkit.from_url(iframe_url, filename, options=options)
    except Exception as e:
        print(e)
        xephyr.stop()
        return JsonResponse('Error rendering image', safe=False)

    image_data = open(filename, 'rb')

    content_type = 'image/{}'.format(filetype)
    response = HttpResponse(image_data.read(), content_type=content_type)
    response['Content-Disposition'] = 'attachment; filename=%s' % filename

    if preview:
        response['Content-Disposition'] = 'inline'

    xephyr.stop()
    image_data.close()
    os.remove(filename)

    if not preview:
        image_count = CardCountVisit()
        image_count.user = user
        image_count.click_type = 3
        image_count.save()

    return response
Ejemplo n.º 21
0
def card_stats(request):
    role = get_role(request.user)
    market = get_user_market_or_main_market(request.user)

    if role not in ['admin', 'coordinator', 'corporate']:
        return redirect('/')

    start_date = request.GET.get('start_date', None)
    end_date = request.GET.get('end_date', None)

    if start_date:
        start_date_obj = datetime.strptime(start_date, '%d-%m-%Y').date()
    if end_date:
        end_date_obj = datetime.strptime(end_date, '%d-%m-%Y').date()

    month = datetime.now().month
    year = datetime.now().year
    month_representation = calendar.month_name[month]

    @register.filter
    def get_item(dictionary, key):
        return dictionary.get(key)

    social_list = []
    social_networks_types = SocialNetworkTypes.objects.all()
    for social_network_type in social_networks_types:
        social_list.append(social_network_type.as_dict())

    count_year = CardCountVisit.objects.filter(created_at__year=year,
                                               click_type=1).count()
    count_month = CardCountVisit.objects.filter(created_at__month=month,
                                                click_type=1).count()

    if start_date and end_date:
        total_home = CardCountVisit.objects.filter(
            click_type=1,
            created_at__gte=start_date_obj,
            created_at__lte=end_date_obj,
        ).count()
        total_contact = CardCountVisit.objects.filter(
            click_type=2,
            created_at__gte=start_date_obj,
            created_at__lte=end_date_obj,
        ).count()

        total_networks = CardSocialNetworkCountVisit.objects \
            .filter(
                created_at__gte=start_date_obj,
                created_at__lte=end_date_obj,
            ) \
            .order_by('network') \
            .values('network_id') \
            .annotate(count=Count('network_id'))
        total_social = {c['network_id']: c['count'] for c in total_networks}
    else:
        total_home = CardCountVisit.objects.filter(created_at__year=year,
                                                   click_type=1).count()
        total_contact = CardCountVisit.objects.filter(created_at__year=year,
                                                      click_type=2).count()
        total_networks = CardSocialNetworkCountVisit.objects \
            .all() \
            .order_by('network') \
            .values('network_id') \
            .annotate(count=Count('network_id'))
        total_social = {c['network_id']: c['count'] for c in total_networks}

    total_counts = {
        'year': count_year,
        'month': count_month,
        'home': total_home,
        'contact': total_contact,
        'social': total_social
    }

    current_year = year
    current_month = month_representation

    users = get_user_model().objects.prefetch_related(
        'consultantprofile',
        'consultantprofile__market',
    ).filter(
        Q(groups__name="new markets coordinator") |  # noqa
        Q(groups__name="finances") |  # noqa
        Q(groups__name="supervisors") |  # noqa
        Q(groups__name="free agents") |  # noqa
        Q(groups__name="consultants") |  # noqa
        Q(groups__name="info") |  # noqa
        Q(groups__name="visas") |  # noqa
        Q(groups__name="corporate admin") |  # noqa
        Q(groups__name="super admin")).distinct()

    if role == 'coordinator':
        users = users.filter(consultantprofile__market__id=market.id)

    users_list = []
    for user in list(users):
        if start_date and end_date:
            home_visit = CardCountVisit.objects.filter(
                user=user,
                click_type=1,
                created_at__gte=start_date_obj,
                created_at__lte=end_date_obj,
            ).count()
            contact_download = CardCountVisit.objects.filter(
                user=user,
                click_type=2,
                created_at__gte=start_date_obj,
                created_at__lte=end_date_obj,
            ).count()
            card_networks = CardSocialNetworkCountVisit.objects \
                .filter(
                    user=user,
                    created_at__gte=start_date_obj,
                    created_at__lte=end_date_obj,
                ) \
                .order_by('network') \
                .values('network_id') \
                .annotate(count=Count('network_id'))
            social_count = {c['network_id']: c['count'] for c in card_networks}
        else:
            home_visit = CardCountVisit.objects.filter(
                user=user,
                click_type=1,
            ).count()
            contact_download = CardCountVisit.objects.filter(
                user=user,
                click_type=2,
            ).count()
            card_networks = CardSocialNetworkCountVisit.objects \
                .filter(user=user) \
                .order_by('network') \
                .values('network_id') \
                .annotate(count=Count('network_id'))
            social_count = {c['network_id']: c['count'] for c in card_networks}

        user_dict = {
            'id': user.pk,
            'common_name': user.common_name,
            'home_visit': home_visit,
            'social_count': social_count,
            'contact_download': contact_download,
            'consultantprofile': {
                'market_name': '',
            }
        }
        if hasattr(user, 'consultantprofile'):
            market = list(user.consultantprofile.market.all())
            if len(market) > 0:
                user_dict['consultantprofile']['market_name'] = market[0].name

        users_list.append(user_dict)

    context = {
        'menu_type': 'administration',
        'total_counts': total_counts,
        'current_year': current_year,
        'current_month': current_month,
        'social_networks': social_list,
        'users': users_list,
    }

    return render(request, 'cards/card_stats.html', context)
Ejemplo n.º 22
0
def pages(request):
    if request.method == 'GET':
        role = get_role(request.user)
        market = get_user_market_or_main_market(request.user)

        # categories with subcategories
        categories_available_list = Category.objects.filter(
            is_active=True).values_list('id', flat=True).annotate(
                Count('id')).filter(market=market,
                                    id__count__gt=0,
                                    pages__id__isnull=False)

        categories_available = len(categories_available_list) > 0

        categories_ids = []
        if categories_available:
            for id in categories_available_list:
                categories_ids.append(id)

        attachments = Attachment.objects.prefetch_related(
            'page__category').filter(page__category__market=market)
        categories = Category.objects.filter(
            id__in=categories_ids).order_by('name')

        attachment_categories = AttachmentCategory.objects.all()
        visas_country = VisasCountry.objects.all()
        visas_types = VisasType.objects.all()

        context = {
            'role': role,
            'categories_available': categories_available,
            'attachments': attachments,
            'categories': categories,
            'attachment_categories': attachment_categories,
            'visas_country': visas_country,
            'visas_types': visas_types
        }

        if role == 'corporate':
            context['menu_type'] = 'general'

        return render(request, 'static_pages/pages_view.html', context)

    if request.method == 'POST' and request.is_ajax():

        page_id = request.POST.get('pageId', None)

        page = Page.objects.select_related('category').filter(
            pk=page_id).first()
        if not page:
            return JsonResponse({}, status=400)

        name = request.POST.get('name', None)
        link = request.POST.get('link', None)
        type_id = request.POST.get('type_id', None)
        country_id = request.POST.get('country_id', None)
        category_id = request.POST.get('category_id', None)
        archive = request.FILES.get('file', None)
        icon_new = request.POST.get('icon_new', None)
        icon_name = request.POST.get('icon_name', None)
        icon_attachment = request.FILES.get('icon_attachment', None)
        input_view_icon = request.POST.get('input_view_icon', None)
        input_view_image = request.POST.get('input_view_image', None)
        iframe_link = request.POST.get('iframe_link', None)
        category = None

        if page.type == 1 and not (link or archive):
            return JsonResponse({}, status=400)
        if page.type == 3 and not (link or archive):
            return JsonResponse({}, status=400)
        if page.type == 4 and not archive:
            return JsonResponse({}, status=400)

        if category_id:
            category = AttachmentCategory.objects.filter(
                pk=category_id).first()
            if not category:
                return JsonResponse({}, status=400)

        attachment = Attachment()
        attachment.name = name
        attachment.page = page

        attachment.visa_type_id = type_id
        attachment.country_id = country_id

        if category:
            attachment.category = category

        attachment.active = True
        attachment.url = link
        attachment.file = archive

        if iframe_link:
            attachment.view = iframe_link

        attachment.save()

        response = {
            'id': attachment.pk,
            'name': attachment.name if attachment.name else '',
            'categoryName': page.category.name if page.category.name else '',
            'subcategoryName': page.title if page.title else '',
            'date': attachment.created.strftime("%d/%m/%Y"),
            'sortDate': attachment.created.strftime("%Y-%m-%d %H:%M:%S"),
            'link': attachment.url if attachment.url else '',
            'url': attachment.file.url if attachment.file else '',
        }

        add_change_log_by_page_attachment(page_attachment=attachment)

        return JsonResponse(response, status=200)
Ejemplo n.º 23
0
def supervisor_consultant_detail(request, consultant_id):
    role = request.user.role
    menu_type = request.GET.get('menu_type', '')
    is_same_user = int(consultant_id) == request.user.pk

    users = []

    user_viewed = get_user_model().objects.select_related(
        'role',
        'person').prefetch_related('consultantprofile__supervisor').filter(
            pk=consultant_id).first()

    if not user_viewed or role.code == 'info':
        return redirect('/')

    if role.code in ['consultant'] and not request.user.pk == user_viewed.pk:
        return redirect('/')

    if role.code == 'supervisor' and (
            not request.user.pk == user_viewed.consultantprofile.supervisor_id
            and not is_same_user):
        return redirect('/')

    currency = Currency.objects.filter(main=True).first()
    if not currency:
        return redirect('/')

    if role.code == 'corporate':
        market = get_corporate_market_filter(request)
    else:
        market = get_user_market_or_main_market(request.user)

    previous_period = AcademicPeriod.objects.active_period()
    current_period = AcademicPeriod.objects.next_to_current_period()
    main_currency = Currency.objects.filter(main=True).first()

    common_query_set = Registration.objects.exclude(
        Q(status='5') | Q(academic_period__start_date__year='2015'))

    market_by_filter = (role.code in ['corporate', 'coordinator']
                        and is_same_user)

    if market_by_filter:
        registrations = common_query_set.filter(
            consultant__consultantprofile__market=market)
    else:
        registrations = common_query_set.filter(consultant=user_viewed)

    def find_by_status(status, elements):
        return next(
            (x['status__count'] for x in elements if x['status'] == status), 0)

    # region Registration Cycles
    if user_viewed.role.code == 'trainee' or role.code == 'trainee':
        cycle_query_set = common_query_set.filter(
            academic_period=current_period)
        cycle_counts = {
            'lead_trainee': cycle_query_set.filter(status='9').count(),
            'lead': cycle_query_set.filter(helper_creator=user_viewed).count()
        }
    else:
        cycle_query_set = registrations.filter(academic_period=current_period)
        results = cycle_query_set.values('status').filter(
            status__in=['1', '2', '3', '4']).annotate(Count('status'))

        cycle_counts = {
            'lead': find_by_status('1', results),
            'registration': find_by_status('2', results),
            'finance': find_by_status('3', results),
            'customer': find_by_status('4', results),
        }
    # endregion

    # region Total Counts
    if user_viewed.role.code == 'trainee':
        total_counts = {
            'lead_trainee': common_query_set.filter(status='9').count(),
            'lead':
            common_query_set.filter(helper_creator=user_viewed).count(),
        }
    else:
        registrations_total = registrations.values('status').filter(
            status__in=['1', '4']).annotate(Count('status'))

        total_counts = {
            'lead': find_by_status('1', registrations_total),
            'customer': find_by_status('4', registrations_total),
        }
    # endregion

    prev_cycle = [{'currency': main_currency.code, 'amount': Decimal('0.00')}]
    current_cycle = [{
        'currency': main_currency.code,
        'amount': Decimal('0.00')
    }]
    total_cycles = []

    common_query_set = RegistrationCommission.objects.filter(
        registration__academic_period__start_date__year__lte=current_period.
        start_date.year,
        registration__status__in=[2, 3, 4],
        registration__registrationfinance__commission_currency__isnull=False
    ).exclude(registration__academic_period__start_date__year='2015').annotate(
        currency=F(
            'registration__registrationfinance__commission_currency__code'))

    if market_by_filter:
        commission_accumulated = User.objects.can_register().market(
            market).aggregate(total=Sum('consultantprofile__commission_start'))

        total_cycles.append({
            'currency': main_currency.code,
            'amount': commission_accumulated['total']
        })

        cycles = common_query_set.filter(
            is_special=False, registration__program__markets=market).values(
                'currency', 'registration__academic_period_id').annotate(
                    academic_period_id=F('registration__academic_period_id'),
                    amount=Sum('amount'))

        users = User.objects.select_related('person').can_register().filter(
            is_active=True, consultantprofile__market=market).exclude(
                pk=user_viewed.pk).order_and_annotate_full_name()
    else:
        total_cycles.append({
            'currency':
            main_currency.code,
            'amount':
            user_viewed.consultantprofile.commission_start
        })

        cycles = common_query_set.filter(user=user_viewed, ).values(
            'currency', 'registration__academic_period_id').annotate(
                academic_period_id=F('registration__academic_period_id'),
                amount=Sum('amount'))

    for cycle in cycles:
        if cycle['academic_period_id'] == current_period.pk:
            target_cycle = current_cycle
        elif cycle['academic_period_id'] == previous_period.pk:
            target_cycle = prev_cycle
        else:
            target_cycle = total_cycles

        has_currency = False
        for total in target_cycle:
            if total['currency'] == cycle['currency']:
                has_currency = True
                total['amount'] = total['amount'] + cycle['amount']
                break

        if not has_currency:
            target_cycle.append({
                'currency': cycle['currency'],
                'amount': cycle['amount']
            })

    request_context = {
        'role':
        role.code,
        'currency':
        currency,
        'default_period':
        current_period,
        'user_viewed':
        user_viewed,
        'periods_json':
        AcademicPeriod.objects.exclude(start_date__year='2015').as_json(),
        'cycle_counts':
        cycle_counts,
        'total_counts':
        total_counts,
        'prev_cycle':
        prev_cycle,
        'current_cycle':
        current_cycle,
        'total_cycles':
        total_cycles,
        'enable_targes':
        False,
        'menu_type':
        menu_type,
        'timezone':
        settings.TIME_ZONE,
        'users':
        users,
        'market':
        market,
        'market_by_filter':
        market_by_filter
    }

    return render(request, 'profiles/supervisor_consultant_detail.html',
                  request_context)
Ejemplo n.º 24
0
def index(request):
    if request.method == 'GET':
        role = request.user.role
        user = request.user
        menu_type = request.GET.get('menu_type', '')

        markets = Market.objects.filter(is_active=True).order_by('name')

        if role.code == 'program':
            # TODO  add custom permission to get this users instead of hardcode the username
            program_user_options = get_user_model().objects.select_related('person').filter(
                username__in=['*****@*****.**', '*****@*****.**', '*****@*****.**']
            )

            program_profile = ProgramProfile.objects.prefetch_related('markets').filter(user=user).first()
            if not program_profile:
                markets = []
            else:
                markets = program_profile.markets.all()

        received_notifications = []
        if role.code == 'corporate' and menu_type == 'general':
            if 'market_id' in request.session:
                market_id = request.session['market_id']
            else:
                market = get_user_market_or_main_market(request.user)
                market_id = market.pk

            consultant_by_market = ConsultantProfile.objects.select_related(
                'consultant'
            ).get_coordinator_by_market(market_id).first()

            if consultant_by_market:
                consultant_id = consultant_by_market.consultant.pk
                received_notifications = NotificationReceiver.objects.prefetch_related('notification').filter(
                    receiver=consultant_id
                )
        else:
            received_notifications = NotificationReceiver.objects.prefetch_related('notification').filter(
                receiver=request.user
            )

        unseen_ids = []
        notifications_data = []
        for received in received_notifications:
            n = {
                'id': received.pk,
                'description': received.notification.description,
                'comment': received.notification.comment,
                'viewed': received.viewed,
                'backed_up': received.backed_up,
                'created': received.notification.created,
                'notification_id': received.notification.pk,
            }
            notifications_data.append(n)

            if not received.viewed:
                unseen_ids.append(received.pk)

        NotificationReceiver.objects.filter(pk__in=unseen_ids).update(viewed=True)

        context = {
            'user': user,
            'role': role.code,
            'notifications': notifications_data,
            'markets': markets,
            'user_name': request.user.person.get_full_name(),
            'menu_type': menu_type
        }

        if role.code == 'program':
            context['program_user_options'] = program_user_options

        query_set = User.objects.order_and_annotate_common_name_or_username().filter(
            is_active=True,
        )

        if role.code in ['coordinator', 'consultant', 'free_agent', 'supervisor', 'info']:
            market = get_user_market_or_main_market(request.user)

            context['users'] = query_set.can_create_register().filter(
                consultantprofile__market=market
            ).exclude(pk=request.user.pk)

        elif role.code == 'finance':
            context['users'] = query_set.acs_users().exclude(pk=request.user.pk)

        elif role.code == 'corporate':
            if menu_type == 'general':
                market = Market.objects.filter(pk=market_id).get()
                context['users'] = query_set.filter(
                    role__code='coordinator',
                    consultantprofile__market=market
                ).exclude(pk=request.user.pk)
            else:
                context['users'] = query_set.acs_users().exclude(pk=request.user.pk)

        elif role.code in ['admin', 'finance']:
            market = get_market(request)
            context['users'] = query_set.can_create_register().filter(
                consultantprofile__market=market
            ).exclude(
                pk=request.user.pk
            )

        elif role.code == 'trainee':
            context['users'] = query_set.filter(pk=request.user.consultantprofile.supervisor_id)

        return render(request, 'notifications/notifications.html', context)
Ejemplo n.º 25
0
def generate_excel(request):
    menu_type = request.GET.get('menu_type')
    if request.method == 'POST':
        date1 = request.POST['date1']
        date2 = request.POST['date2']
        status = request.POST.getlist('id_status[]')
        academic_period_id = request.POST['id_academic_period']
        reports = request.POST.getlist('id_reports[]')
        market_id = request.POST.get('market', None)
        full_year = to_boolean(request.POST.get('full_year', False))
        report_type = int(reports[0])
        role = get_role(request.user)

        today_end = utc_to_local(timezone.now()).replace(
            hour=0, minute=0, second=0, microsecond=0) + datetime.timedelta(
                days=1) - datetime.timedelta(seconds=1)

        if date1:
            date1 = unaware_to_local(
                datetime.datetime.strptime(date1, '%Y-%m-%d'))

        if date2:
            date2 = unaware_to_local(
                datetime.datetime.strptime(
                    date2, '%Y-%m-%d')) + datetime.timedelta(
                        days=1) - datetime.timedelta(seconds=1)

        # if report_type == 9 and not market_id and role in ['admin', 'corporate', 'finance']:
        #     return redirect('static_pages:reports_view')

        if role in ['admin', 'corporate', 'finance']:
            market_user = get_user_market_or_main_market(request.user)
            if role == 'corporate' and menu_type == 'general':
                market_filter = get_market_or_main_market(request, menu_type)
                market_user = market_filter
            else:
                if market_id:
                    market_filter = Market.objects.filter(pk=market_id).first()
                else:
                    market_filter = None
        elif role in ['info', 'visa']:
            market_user = None
            market_filter = None
        else:
            market_user = get_user_market_or_main_market(request.user)
            market_filter = market_user

        selected_report = ReportList().get_report(report_type)

        query = Registration.objects.select_related(
            'short_term', 'program__program_base', 'program__parent',
            'academic_period', 'costumer', 'costumer__profile',
            'payment_responsible', 'emergency_contact', 'consultant__person',
            'costumer__profile__address__city',
            'costumer__profile__address__state', 'registrationflight',
            'registrationfinance', 'grade').prefetch_related(
                'registrationvisa', 'program__program_base__category',
                'program__program_base__city__state__country', 'tutors',
                'tutors__profile__phone_set', 'note_set',
                'costumer__profile__address', 'costumer__profile__phone_set',
                'consultant__consultantprofile__supervisor__person')

        if date1 and date2:
            query = query.filter(created__range=[date1, date2])

        # review only admins should download all info , if not only their registrations
        if role in [
                'admin', 'corporate', 'finance', 'program_review', 'info',
                'visa'
        ] or report_type == 11:
            if role == 'coordinator':
                query = query.by_consultantprofile_market(market_user)
            elif role == 'corporate' and menu_type == 'general':
                market_filter = get_market_or_main_market(request, menu_type)
                query = query.by_consultantprofile_market(market_filter)
            else:
                pass

        elif role == 'coordinator':
            if report_type != 9:
                query = query.by_consultantprofile_market(market_user)

        # if user is supervisor, then only their consultant and his own
        elif role == 'supervisor':
            if not report_type == 12:
                query = query.filter(
                    Q(consultant__consultantprofile__supervisor=request.user)
                    | Q(consultant=request.user))
            else:
                query = query.filter(Q(consultant=request.user))

        # regular consultant
        else:
            query = query.filter(consultant=request.user)

        # filter by academic period ( if present )
        if academic_period_id != '' and selected_report.id != 9:
            query = query.filter(academic_period_id=academic_period_id)

        query_all_status = query
        # filter by status ( if present )
        if len(status) > 0:
            query = query.filter(status__in=status)

        today = datetime.datetime.today()
        month_abbrev, day, year_abbrev = (
            today.strftime('%b-%d-%y')).split('-')

        if role in ['admin', 'corporate', 'finance']:
            report_name = u'{}-{}'.format(
                selected_report.safe_name,
                u'{}.{}.{}'.format(month_abbrev, day, year_abbrev))
            password = u'AdastraALL{}!'.format(year_abbrev)
        elif role in ['info', 'visa']:
            report_name = u'{}-{}'.format(
                selected_report.safe_name,
                u'{}.{}.{}'.format(month_abbrev, day, year_abbrev))
            if role == 'info':
                password = u'Leads!'
            elif role == 'visa':
                # not defined
                password = u''
        else:
            report_name = u'{}-{}-{}'.format(
                selected_report.safe_name, market_user.code.upper(),
                u'{}.{}.{}'.format(month_abbrev, day, year_abbrev))
            password = u'Adastra{}{}!'.format(market_user.code.upper(),
                                              year_abbrev)

        class DTO(object):
            pass

        dto = DTO()
        dto.user = request.user
        dto.role = get_role(request.user)
        dto.academic_period_id = academic_period_id
        dto.market_id = market_id
        dto.status = status
        dto.timezone = request.POST['timezone']
        dto.market_user = market_user
        dto.market_filter = market_filter
        dto.start_date = date1 if date1 else None
        dto.end_date = date2 if date2 else None
        dto.now = timezone.now().replace(hour=23, minute=59, second=59)
        dto.today_end = today_end
        dto.full_year = full_year

        if selected_report.protected:
            compression_level = 5  # 1-9

            temp_dir = tempfile.gettempdir()
            dst_file = '{}.xlsx'.format(report_name)
            dst_dir = '{}/{}.zip'.format(temp_dir, report_name)
            src_dir = '{}/{}'.format(temp_dir, dst_file)

            xlsx_data = write_to_excel(query,
                                       selected_report.id,
                                       query_all_status,
                                       request,
                                       date1,
                                       date2,
                                       academic_period_id,
                                       dto,
                                       dest_dir=src_dir)

            pyminizip.compress(src_dir, None, dst_dir, password,
                               compression_level)

            f = open(dst_dir, 'rb')
            response = HttpResponse(f, content_type='application/zip')
            response[
                'Content-Disposition'] = 'attachment; filename={}.zip'.format(
                    report_name)
            return response
        else:
            response = HttpResponse(content_type='application/vnd.ms-excel')
            response[
                'Content-Disposition'] = 'attachment; filename={}.xlsx'.format(
                    report_name)
            xlsx_data = write_to_excel(query,
                                       selected_report.id,
                                       query_all_status,
                                       request,
                                       date1,
                                       date2,
                                       academic_period_id,
                                       dto,
                                       dest_dir=None)

            response.write(xlsx_data)
            return response
    else:
        return HttpResponse('{Only POST request allowed.}', status=200)