Example #1
0
def search():
    '''The search results page for scout

    In order to create permalinks to each search/filter result combination,
    POST methods have their form arguments popped off and then are immediately
    redirected to GET methods.

    .. seealso ::
        * :py:mod:`purchasing.data.searches` for more on the search query
        * :py:class:`~purchasing.scout.forms.SearchForm` for the search form construction
        * :py:func:`~purchasing.scout.util.build_filter` for how filters are built
        * :py:func:`~purchasing.scout.util.build_cases` for how case statements are built

    :status 200: Render the search template with the given results
    :status 302: Pop the passed form arguments to the request URL
        and redirect to the search view
    '''
    if request.method == 'POST':
        args = request.form.to_dict()
        if args.get('contract_type') == '__None':
            del args['contract_type']

        return redirect(url_for('scout.search', **args))

    department = request.args.get('department')
    if department and department not in ['', 'None']:
        return redirect(url_for('scout.filter', department=department))

    search_form = SearchForm()
    search_for = request.args.get('q') or ''
    search_form.q.data = search_for

    # strip out "crazy" characters
    search_for = re.sub(CRAZY_CHARS, '', search_for)
    search_for = ' | '.join(search_for.split())

    pagination_per_page = current_app.config.get('PER_PAGE', 50)
    page = int(request.args.get('page', 1))
    lower_bound_result = (page - 1) * pagination_per_page
    upper_bound_result = lower_bound_result + pagination_per_page

    filter_or = build_filter(
        request.args, FILTER_FIELDS, search_for, search_form,
        not any([request.args.get(name) for name, _, _ in FILTER_FIELDS])
    )

    filter_and = []
    if request.args.get('contract_type') is not None:
        filter_and = [
            ContractBase.contract_type_id == int(request.args.get('contract_type'))
        ]
        search_form.contract_type.data = ContractType.query.get(int(request.args.get('contract_type')))

    found_in_case = build_cases(
        request.args, FILTER_FIELDS, search_for,
        not any([request.args.get(name) for name, _, _ in FILTER_FIELDS])
    )

    # determine if we are getting archived contracts
    if request.args.get('archived') == 'y':
        search_form['archived'].checked = True
        archived = True
    else:
        archived = False

    if search_for != '':
        contracts = find_contract_metadata(
            search_for, found_in_case, filter_or, filter_and,
            archived
        )
    else:
        contracts = return_all_contracts(
            filter_and, archived
        )

    pagination = SimplePagination(page, pagination_per_page, len(contracts))

    current_app.logger.info('WEXSEARCH - {search_for}: {user} searched for "{search_for}"'.format(
        search_for=search_for,
        user=current_user.email if not current_user.is_anonymous() else 'anonymous'
    ))

    user_follows = [] if current_user.is_anonymous() else current_user.get_following()

    return render_template(
        'scout/search.html',
        current_user=current_user,
        user_follows=user_follows,
        search_for=search_for,
        results=contracts[lower_bound_result:upper_bound_result],
        pagination=pagination,
        search_form=search_form,
        choices=Department.choices(),
        path='{path}?{query}'.format(
            path=request.path, query=request.query_string
        )
    )
def search():
    '''
    The search results page for scout
    '''
    if request.method == 'POST':
        args = request.form.to_dict()
        if args.get('contract_type') == '__None':
            del args['contract_type']

        return redirect(url_for('wexplorer.search', **args))

    department = request.args.get('department')
    if department and department not in ['', 'None']:
        return redirect(url_for('wexplorer.filter', department=department))

    search_form = SearchForm()
    search_for = request.args.get('q') or ''
    search_form.q.data = search_for

    # strip out "crazy" characters
    search_for = re.sub(CRAZY_CHARS, '', search_for)
    search_for = ' | '.join(search_for.split())

    pagination_per_page = current_app.config.get('PER_PAGE', 50)
    page = int(request.args.get('page', 1))
    lower_bound_result = (page - 1) * pagination_per_page
    upper_bound_result = lower_bound_result + pagination_per_page

    # build filter and filter form
    fields = [
        ('company_name', 'Company Name', SearchView.tsv_company_name),
        ('line_item', 'Line Item', SearchView.tsv_line_item_description),
        ('contract_description', 'Contract Description', SearchView.tsv_contract_description),
        ('contract_detail', 'Contract Detail', SearchView.tsv_detail_value),
        ('financial_id', 'Controller Number', SearchView.financial_id),
    ]

    filter_or = build_filter(
        request.args, fields, search_for, search_form,
        not any([request.args.get(name) for name, _, _ in fields])
    )

    filter_and = []
    if request.args.get('contract_type') is not None:
        filter_and = [
            ContractBase.contract_type_id == int(request.args.get('contract_type'))
        ]
        search_form.contract_type.data = ContractType.query.get(int(request.args.get('contract_type')))

    found_in_case = build_cases(
        request.args, fields, search_for,
        not any([request.args.get(name) for name, _, _ in fields])
    )

    # determine if we are getting archived contracts
    if request.args.get('archived') == 'y':
        search_form['archived'].checked = True
        archived = True
    else:
        archived = False

    if search_for != '':
        contracts = find_contract_metadata(
            search_for, found_in_case, filter_or, filter_and,
            archived
        )
    else:
        contracts = return_all_contracts(
            filter_and, archived
        )

    pagination = SimplePagination(page, pagination_per_page, len(contracts))

    current_app.logger.info('WEXSEARCH - {search_for}: {user} searched for "{search_for}"'.format(
        search_for=search_for,
        user=current_user.email if not current_user.is_anonymous() else 'anonymous'
    ))

    user_follows = [] if current_user.is_anonymous() else current_user.get_following()

    return render_template(
        'wexplorer/search.html',
        current_user=current_user,
        user_follows=user_follows,
        search_for=search_for,
        results=contracts[lower_bound_result:upper_bound_result],
        pagination=pagination,
        search_form=search_form,
        choices=Department.choices(),
        path='{path}?{query}'.format(
            path=request.path, query=request.query_string
        )
    )
def search():
    """The search results page for scout

    In order to create permalinks to each search/filter result combination,
    POST methods have their form arguments popped off and then are immediately
    redirected to GET methods.

    .. seealso ::
        * :py:mod:`purchasing.data.searches` for more on the search query
        * :py:class:`~purchasing.scout.forms.SearchForm` for the search form construction
        * :py:func:`~purchasing.scout.util.build_filter` for how filters are built
        * :py:func:`~purchasing.scout.util.build_cases` for how case statements are built
    """
    if request.method == "POST":
        args = request.form.to_dict()
        if args.get("contract_type") == "__None":
            del args["contract_type"]

        return redirect(url_for("scout.search", **args))

    department = request.args.get("department")
    if department and department not in ["", "None"]:
        return redirect(url_for("scout.filter", department=department))

    search_form = SearchForm()
    search_for = request.args.get("q") or ""
    search_form.q.data = search_for

    # strip out "crazy" characters
    search_for = re.sub(CRAZY_CHARS, "", search_for)
    search_for = " | ".join(search_for.split())

    pagination_per_page = current_app.config.get("PER_PAGE", 50)
    page = int(request.args.get("page", 1))
    lower_bound_result = (page - 1) * pagination_per_page
    upper_bound_result = lower_bound_result + pagination_per_page

    filter_or = build_filter(
        request.args,
        FILTER_FIELDS,
        search_for,
        search_form,
        not any([request.args.get(name) for name, _, _ in FILTER_FIELDS]),
    )

    filter_and = []
    if request.args.get("contract_type") is not None:
        filter_and = [ContractBase.contract_type_id == int(request.args.get("contract_type"))]
        search_form.contract_type.data = ContractType.query.get(int(request.args.get("contract_type")))

    found_in_case = build_cases(
        request.args, FILTER_FIELDS, search_for, not any([request.args.get(name) for name, _, _ in FILTER_FIELDS])
    )

    # determine if we are getting archived contracts
    if request.args.get("archived") == "y":
        search_form["archived"].checked = True
        archived = True
    else:
        archived = False

    if search_for != "":
        contracts = find_contract_metadata(search_for, found_in_case, filter_or, filter_and, archived)
    else:
        contracts = return_all_contracts(filter_and, archived)

    pagination = SimplePagination(page, pagination_per_page, len(contracts))

    current_app.logger.info(
        'WEXSEARCH - {search_for}: {user} searched for "{search_for}"'.format(
            search_for=search_for, user=current_user.email if not current_user.is_anonymous() else "anonymous"
        )
    )

    user_follows = [] if current_user.is_anonymous() else current_user.get_following()

    return render_template(
        "scout/search.html",
        current_user=current_user,
        user_follows=user_follows,
        search_for=search_for,
        results=contracts[lower_bound_result:upper_bound_result],
        pagination=pagination,
        search_form=search_form,
        choices=Department.choices(),
        path="{path}?{query}".format(path=request.path, query=request.query_string),
    )
def search():
    '''
    The search results page for wexplorer. Renders the "side search"
    along with paginated results.
    '''
    department = request.args.get('department')
    if department and department not in ['', 'None']:
        return redirect(url_for('wexplorer.filter', department=department))

    search_form = SearchForm(request.form)
    search_for = request.args.get('q', '')

    pagination_per_page = current_app.config.get('PER_PAGE', 50)
    page = int(request.args.get('page', 1))
    lower_bound_result = (page - 1) * pagination_per_page
    upper_bound_result = lower_bound_result + pagination_per_page

    # build filter and filter form
    filter_form = FilterForm()
    fields = [
        ('company_name', 'Company Name', SearchView.tsv_company_name),
        ('line_item', 'Line Item', SearchView.tsv_line_item_description),
        ('contract_description', 'Contract Description',
         SearchView.tsv_contract_description),
        ('contract_detail', 'Contract Detail', SearchView.tsv_detail_value),
    ]

    filter_where = build_filter(
        request.args, fields, search_for, filter_form,
        not any([request.args.get(name) for name, _, _ in fields]))

    found_in_case = build_cases(
        request.args, fields, search_for,
        not any([request.args.get(name) for name, _, _ in fields]))

    # determine if we are getting archived contracts
    if request.args.get('archived') == 'y':
        filter_form['archived'].checked = True
        archived = True
    else:
        archived = False

    if search_for != '':
        contracts = find_contract_metadata(search_for, found_in_case,
                                           filter_where, archived)
    else:
        contracts = return_all_contracts(archived)

    pagination = SimplePagination(page, pagination_per_page, len(contracts))

    current_app.logger.info(
        'WEXSEARCH - {search_for}: {user} searched for "{search_for}"'.format(
            search_for=search_for,
            user=current_user.email
            if not current_user.is_anonymous() else 'anonymous'))

    user_starred = [] if current_user.is_anonymous(
    ) else current_user.get_starred()
    user_follows = [] if current_user.is_anonymous(
    ) else current_user.get_following()

    return render_template(
        'wexplorer/search.html',
        current_user=current_user,
        filter_form=filter_form,
        user_starred=user_starred,
        user_follows=user_follows,
        search_for=search_for,
        results=contracts[lower_bound_result:upper_bound_result],
        pagination=pagination,
        search_form=search_form,
        choices=DEPARTMENT_CHOICES[1:],
        path='{path}?{query}'.format(path=request.path,
                                     query=request.query_string))