def document_template_listing(request):
    if not request.user.is_authenticated():
        return redirect('kir.views.index')

    t = env.get_template('document_templates.html')

    services    = searcher.front_page_search(request.user, 'service')[0]
    servicetags = searcher.front_page_search(request.user, 'servicetag')[0]
    periods     = searcher.front_page_search(request.user, 'period')[0]
    persons     = searcher.front_page_search(request.user, 'person', sort='last_name,first_name')[0]

    context = {
        'services': services,
        'service_count': len(services),
        'servicetags': servicetags,
        'servicetag_count': len(servicetags),
        'periods': periods,
        'period_count': len(periods),
        'persons': persons,
        'person_count': len(persons),
        'limit': 5,
        'teaser': teaser
        }

    s = template_render(t, context)
    return HttpResponse(s)
def index(request, entity_id=None):
    current_step = 1
    docs = []
    only_one = False

    if not request.user.is_authenticated():
        login_required = True
    else:
        login_required = False
        current_step = 2

    doc_id = entity_id
    selected_id = None
    selected_library = None

    if doc_id:
        selected_doc = get_doc_from_index(
                settings.INDEX_NAME, 'organisation', doc_id)
        if selected_doc:
            selected_library = get_source(selected_doc)
            selected_id=doc_id
            current_step = 3

            if selected_library['organisation_type'] != 'library':
                family_tree = searcher.search_family_tree(user=request.user)
                member = family_tree.get(doc_id)
                if member:
                    selected_library['children'] = [
                        (cid, cname) for cid, cname in
                        zip(member['children'], member['children_names'])]

                    parents = member['parent_names']
                    parents.reverse()
                    selected_library['parents'] = ' → '.join(parents)
    else:
        if not login_required:
            request.session.set_expiry(12*60*60)
            current_step = 2

        required_fields = ['organisation_type',
                           'contact.street_address.municipality_fi',
                           'name_fi',
                           'parent_organisation',
                           'meta.modified']

        if request.user.is_authenticated():
            if request.user.is_superuser:
                results = searcher.search(
                    # todo: remove size
                    searcher.ALL_LIBS, size = 10000, fields = required_fields)
            else:
                results = searcher.front_page_search(
                    request.user, size = 500, fields = required_fields)

            family_tree = searcher.search_family_tree(user=request.user)

            for doc in results[0]:
                if 'organisation_type' not in doc:
                    print(doc)

                if (doc['organisation_type'] in
                    ['branchlibrary', 'unit', 'library']):
                    family_member = family_tree.get(doc['_id'])

                    if family_member:
                        parents = family_member['parent_names']
                        children = family_member['children_names']
                        children_ids = family_member['children']

                        if len(parents):
                            parents.reverse()
                            doc['parents'] = ' → '.join(parents)

                        if len(children):
                            doc['children'] = [(cid, cname) for cid, cname in
                                               zip(children_ids, children)]

                if (doc['organisation_type'] not in ['department',
                                                     'mobile_stop']):
                    docs.append(doc)


            if not login_required and len(docs) == 1:
                current_step = 3
                selected_library = docs[0]
                selected_id = selected_library['_id']
                only_one = True

    t = env.get_template('index.html')

    note_filter_date = dt.datetime.now() - dt.timedelta(days=7)
    notifications = models.Notification.objects.unread(request.user, note_filter_date)

    context = {
        'login_required'      : login_required,
        'docs'                : docs,
        'library_count'       : len(docs),
        'username'            : request.user.username,
        'access_to_templates' : (
            not login_required and
            request.user.has_perm('sites.access_to_templates')),

        'summary'             : teaser('organisation'),
        'selected_library'    : selected_library,
        'selected_id'         : selected_id ,
        'frontpage_url'       : frontpage_url,
        'editpage_url'        : editpage_url,
        'current_step'        : current_step,
        'only_one'            : only_one,
        'library_limit'       : 5,
        'username_string'     : _("Username"),
        'password_string'     : _("Password"),
        'login_string'        : _("Log in"),
        'notifications'       : notifications,
        'can_export'          : user_has_group(request.user, 'export')
        }

    context.update(csrf(request)) # todo: better way?

    s = template_render(t, context)

    return HttpResponse(s)