Verified Commit 931899d8 authored by Kaspar Vollenweider's avatar Kaspar Vollenweider
Browse files

remove old search js with autocomplete_rails gem

parent 8a067e26
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader
if (typeof define === 'function' && define.amd) {
define(factory)
registeredInModuleLoader = true
}
if (typeof exports === 'object') {
module.exports = factory()
registeredInModuleLoader = true
}
if (!registeredInModuleLoader) {
var OldCookies = window.Cookies
var api = (window.Cookies = factory())
api.noConflict = function () {
window.Cookies = OldCookies
return api
}
}
})(function () {
function extend() {
var i = 0
var result = {}
for (; i < arguments.length; i++) {
var attributes = arguments[i]
for (var key in attributes) {
result[key] = attributes[key]
}
}
return result
}
function init(converter) {
function api(key, value, attributes) {
if (typeof document === 'undefined') {
return
}
// Write
if (arguments.length > 1) {
attributes = extend(
{
path: '/',
},
api.defaults,
attributes
)
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(
new Date() * 1 + attributes.expires * 864e5
)
}
// We're using "expires" because "max-age" is not supported by IE
attributes.expires = attributes.expires
? attributes.expires.toUTCString()
: ''
try {
var result = JSON.stringify(value)
if (/^[\{\[]/.test(result)) {
value = result
}
} catch (e) {}
value = converter.write
? converter.write(value, key)
: encodeURIComponent(String(value)).replace(
/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,
decodeURIComponent
)
key = encodeURIComponent(String(key))
.replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent)
.replace(/[\(\)]/g, escape)
var stringifiedAttributes = ''
for (var attributeName in attributes) {
if (!attributes[attributeName]) {
continue
}
stringifiedAttributes += '; ' + attributeName
if (attributes[attributeName] === true) {
continue
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0]
}
return (document.cookie = key + '=' + value + stringifiedAttributes)
}
// Read
var jar = {}
var decode = function (s) {
return s.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
}
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : []
var i = 0
for (; i < cookies.length; i++) {
var parts = cookies[i].split('=')
var cookie = parts.slice(1).join('=')
if (!this.json && cookie.charAt(0) === '"') {
cookie = cookie.slice(1, -1)
}
try {
var name = decode(parts[0])
cookie = (converter.read || converter)(cookie, name) || decode(cookie)
if (this.json) {
try {
cookie = JSON.parse(cookie)
} catch (e) {}
}
jar[name] = cookie
if (key === name) {
break
}
} catch (e) {}
}
return key ? jar[key] : jar
}
api.set = api
api.get = function (key) {
return api.call(api, key)
}
api.getJSON = function (key) {
return api.call(
{
json: true,
},
key
)
}
api.remove = function (key, attributes) {
api(
key,
'',
extend(attributes, {
expires: -1,
})
)
}
api.defaults = {}
api.withConverter = init
return api
}
return init(function () {})
})
// $(() => {
// $('input[data-autocomplete]').each((_index, input) => {
// $(input).autocomplete({
// source: $(input).data('autocomplete'),
// close: handleCloseAutosuggest,
// focus: handleAutosuggestFocus,
// })
// // Select all text in input, for easier deleting of all content if desired
// $(input).on('focus', ({ target }) => $(target).select())
// })
// })
const handleCloseAutosuggest = ({ target }) => {
// if autocomplete placed value in field and closed submit the form
if (target.value.length > 4) {
$(target).parent('form').submit()
}
return false
}
const handleAutosuggestFocus = (event, ui) => {
$('#project').val(ui.item.label)
return false
}
......@@ -5,12 +5,26 @@
*/
$(() => {
const findSearchParam = (param) => {
const qParam = window.location.search
.slice(1)
.split('&')
.map((part) => part.split('='))
.find((parts) => decodeURIComponent(parts[0]) === param)
if (qParam && qParam.length === 2) {
return decodeURIComponent(qParam[1]).split('+').join(' ')
}
return null
}
$('.search-field-autocomplete').each((_index, field) => {
const searchField = $(field)
const fieldName = searchField.attr('name')
const { autocomplete } = searchField.data()
const { autocomplete, param } = searchField.data()
const delimitor = autocomplete.includes('?') ? '&' : '?'
const baseUrl = `${autocomplete}${delimitor}term=`
const searchParam = param || fieldName
const baseUrl = `${autocomplete}${delimitor}${searchParam}=`
searchField.devbridgeAutocomplete({
minChars: 2,
......@@ -18,7 +32,13 @@ $(() => {
lookup: (query, done) => {
$.get(baseUrl + query, (suggestions) => done({ suggestions }), 'json')
},
onSelect: () => searchField.closest('form').trigger('submit'),
onSelect: ({ data, value }) => {
const searchValue = findSearchParam(fieldName)
if (searchValue !== value) {
searchField.val(data.search)
searchField.closest('form').trigger('submit')
}
},
})
})
})
......@@ -29,7 +29,7 @@ class AssignmentsController < ApplicationController
def volunteer_search
authorize Assignment
@q = policy_scope(Assignment).ransack volunteer_contact_full_name_cont: params[:term]
@q = policy_scope(Assignment).ransack params[:q]
@q.sorts = ['period_end desc', 'period_start desc']
@assignments = @q.result distinct: true
respond_to do |format|
......@@ -39,7 +39,7 @@ class AssignmentsController < ApplicationController
def client_search
authorize Assignment
@q = policy_scope(Assignment).ransack client_contact_full_name_cont: params[:term]
@q = policy_scope(Assignment).ransack params[:q]
@q.sorts = ['period_end desc', 'period_start desc']
@assignments = @q.result distinct: true
respond_to do |format|
......
......@@ -23,7 +23,7 @@ class ClientsController < ApplicationController
def search
authorize Client
@q = policy_scope(Client).ransack contact_full_name_cont: params[:term]
@q = policy_scope(Client).ransack params[:q]
@q.sorts = ['acceptance asc']
@clients = @q.result distinct: true
respond_to do |format|
......
......@@ -17,9 +17,9 @@ class GroupOffersController < ApplicationController
def search
authorize GroupOffer
@q = policy_scope(GroupOffer).ransack search_volunteer_cont: params[:term]
@q = policy_scope(GroupOffer).ransack params[:q]
@q.sorts = ['active desc', 'created_at desc']
@group_offers = @q.result distinct: true
@group_offers = @q.result
respond_to do |format|
format.json
end
......@@ -42,7 +42,7 @@ class GroupOffersController < ApplicationController
def search_volunteer
@q = policy_scope(
Volunteer.candidates_for_group_offer(@group_offer)
).ransack(contact_full_name_cont: params[:term])
).ransack(params[:q])
@volunteers = @q.result distinct: true
respond_to do |format|
format.json
......
......@@ -16,7 +16,7 @@ class UsersController < ApplicationController
def search
authorize User
@q = User.ransack full_name_cont: params[:term]
@q = User.ransack params[:q]
@q.sorts = ['role asc']
@users = @q.result distinct: true
respond_to do |format|
......
......@@ -16,7 +16,7 @@ class VolunteersController < ApplicationController
def search
authorize Volunteer
@q = policy_scope(Volunteer).ransack contact_full_name_cont: params[:term]
@q = policy_scope(Volunteer).ransack params[:q]
@q.sorts = ['acceptance asc']
@volunteers = @q.result distinct: true
respond_to do |format|
......
json.array!(@assignments) do |assignment|
json.data do
json.category assignment.active? ? 'Tandem Aktiv' : 'Tandem Inaktiv'
json.search assignment.client.contact.full_name
end
context_info = if assignment.active? && assignment.period_start
context_info = if assignment.period_start && !assignment.period_end
" - Einsatzstart: #{l(assignment.period_start)}"
elsif !assignment.active? && assignment.period_end
elsif assignment.period_end
" - Einsatzende: #{l(assignment.period_start)}"
end
json.value "#{assignment.client.contact.full_name}#{context_info}"
......
json.array!(@assignments) do |assignment|
json.data do
json.category assignment.active? ? 'Tandem Aktiv' : 'Tandem Inaktiv'
json.search assignment.volunteer.contact.full_name
end
context_info = if assignment.active? && assignment.period_start
context_info = if assignment.period_start && !assignment.period_end
" - Einsatzstart: #{l(assignment.period_start)}"
elsif !assignment.active? && assignment.period_end
elsif assignment.period_end
" - Einsatzende: #{l(assignment.period_start)}"
end
json.value "#{assignment.volunteer.contact.full_name}#{context_info}"
......
json.array!(@clients) do |client|
json.data do
json.category client.t_enum(:acceptance)
json.search client.contact.full_name
end
json.value client.contact.full_name
end
......@@ -8,7 +8,7 @@ nav.navbar.section-navigation#filters
= f.search_field :search_volunteer_cont,
class: 'search-field-autocomplete',
data: { autocomplete: search_group_offers_path },
autofocus: true,
autofocus: !params[:q]&.fetch(:search_volunteer_cont, nil),
placeholder: 'Nach Freiwillige suchen'
= f.submit 'Suchen'
......
json.array!(@group_offers) do |group_offer|
json.data do
json.category group_offer.active? ? 'Gruppenangebot Aktiv' : 'Gruppenangebot Inaktiv'
end
volunteers = group_offer.volunteer_contacts.pluck(:full_name).select do |name|
name.match(/#{params[:term]}/i)
name.match(/#{params[:q][:search_volunteer_cont]}/i)
end.join('; ')
json.data do
json.search volunteers
end
json.value "#{volunteers} – #{group_offer.title}"
end
json.array!(@volunteers) do |volunteer|
json.data volunteer.id
json.data do
json.search volunteer.contact.full_name
end
json.value volunteer.contact.full_name
end
json.array!(@users) do |user|
json.data do
json.category t("role.#{user.role}")
json.search user.full_name
end
json.value "#{user.full_name}; #{user.email} - #{t("role.#{user.role}")}"
end
json.array!(@volunteers) do |volunteer|
json.data do
json.category volunteer.t_enum(:acceptance)
json.search volunteer.contact.full_name
end
json.value volunteer.contact.full_name
end
......@@ -99,21 +99,6 @@ class ApplicationSystemTestCase < ActionDispatch::SystemTestCase
end
end
def fill_autocomplete(name, options = {})
find("[name=\"#{name}\"]").native.send_keys options[:with], :down
wait_for_ajax
items = page.find_all('li.ui-menu-item')
if options[:items_expected]
assert_equal options[:items_expected], items.size
end
if options[:check_items].present?
items.each do |item|
assert_includes options[:check_items], item.text
end
end
find("[name=\"#{name}\"]").native.send_keys :down, :enter
end
def any_checked?(selector)
page.find_all(selector).any?(&:checked?)
end
......
......@@ -3,7 +3,7 @@ require 'test_helper'
class ClientsSearchSuggestionTest < ActionDispatch::IntegrationTest
test 'clients suggest json result is correct' do
superadmin = create :user
clients = ('a'..'z').to_a.map do |letter|
clients = ('a'..'e').to_a.map do |letter|
client_one = create :client
client_one.contact.update(first_name: (letter * 5) + client_one.contact.first_name)
client_two = create :client
......@@ -11,7 +11,7 @@ class ClientsSearchSuggestionTest < ActionDispatch::IntegrationTest
[client_one, client_two]
end
login_as superadmin
get search_clients_path, as: :json, params: { term: 'aaa' }
get search_clients_path, as: :json, params: { q: { contact_full_name_cont: 'aaa' } }
results = JSON.parse response.body
assert_equal 2, results.size
results.map { |result| result['value'] }.each do |result|
......
......@@ -3,43 +3,47 @@ require 'application_system_test_case'
class ClientSearchesTest < ApplicationSystemTestCase
def setup
@superadmin = create :user
@clients = ('a'..'z').to_a.map do |letter|
@clients = ('a'..'e').to_a.map do |letter|
client_one = create :client
client_one.contact.update(first_name: (letter * 5) + client_one.contact.first_name)
client_two = create :client
client_two.contact.update(last_name: (letter * 5) + client_two.contact.last_name)
[client_one, client_two]
end
[letter.to_sym, [client_one, client_two]]
end.to_h
login_as @superadmin
visit clients_path
end
test 'basic_non_suggests_search_works' do
fill_in name: 'q[contact_full_name_cont]', with: 'zzzz'
fill_in name: 'q[contact_full_name_cont]', with: 'eee'
wait_for_ajax
find_field(name: 'q[contact_full_name_cont]').native.send_keys(:tab, :enter)
assert_text @clients.last.first.contact.full_name
assert_text @clients.last.last.contact.full_name
assert_text @clients[:e].first.contact.full_name
assert_text @clients[:e].last.contact.full_name
end
test 'enter_search_text_brings_suggestions' do
fill_autocomplete(
'q[contact_full_name_cont]',
with: 'aaa',
items_expected: 2,
check_items: [@clients.first[0].contact.full_name, @clients.first[1].contact.full_name]
)
fill_in name: 'q[contact_full_name_cont]', with: 'aaa'
wait_for_ajax
within '.autocomplete-suggestions' do
assert_text @clients[:a].first.contact.full_name, normalize_ws: true
assert_text @clients[:a].last.contact.full_name, normalize_ws: true
refute_text @clients[:b].first.contact.full_name, normalize_ws: true,
wait: 0
refute_text @clients[:b].last.contact.full_name, normalize_ws: true,
wait: 0
end
end
test 'suggestions search triggers the search correctly' do
fill_autocomplete 'q[contact_full_name_cont]', with: 'aaa'
fill_in name: 'q[contact_full_name_cont]', with: 'aaa'
wait_for_ajax
find_field(name: 'q[contact_full_name_cont]').native.send_keys(:tab, :enter)
visit current_url
within 'tbody' do
assert page.has_text?(@clients.first[0].contact.full_name) ||
page.has_text?(@clients.first[1].contact.full_name)
assert_equal 1, find_all('tr').size
assert page.has_text?(@clients[:a][0].contact.full_name) ||
page.has_text?(@clients[:a][1].contact.full_name)
assert_equal 2, find_all('tr').size
end
end
end
......@@ -30,15 +30,18 @@ class GroupOffersVolunteerSearchesTest < ApplicationSystemTestCase
end
test 'enter_search_text_brings_suggestions' do
fill_autocomplete 'q[search_volunteer_cont]', with: 'Whi', items_expected: 1,
check_item: @group_offer_one.title
fill_in name: 'q[search_volunteer_cont]', with: 'Whi'
wait_for_ajax
within '.autocomplete-suggestions' do
assert_text @group_offer_one.title, normalize_ws: true
refute_text @group_offer_two.title, normalize_ws: true
end
end
test 'suggestions search triggers the search correctly' do
fill_autocomplete 'q[search_volunteer_cont]', with: 'Wal'
fill_in name: 'q[search_volunteer_cont]', with: 'Wal'
wait_for_ajax
page.find_field(name: 'q[search_volunteer_cont]').native.send_keys(:tab, :enter)
visit current_url
within 'tbody' do
assert page.has_text? @volunteer_one.contact.full_name
assert page.has_text? @group_offer_one.title
......
......@@ -35,10 +35,19 @@ class UserSearchesTest < ApplicationSystemTestCase
# with this test we check if the suggestions are correct, we don't check
# what happens in the body section,
# because travis selects somehow the first suggestion and then we run into errors.
# test 'enter_search_text_brings_suggestions' do
# fill_autocomplete 'q[full_name_cont]', with: 'Whi', items_expected: 2,
# check_item: [@superadmin.full_name, @social_worker.full_name]
# end
test 'enter_search_text_brings_suggestions' do
fill_in name: 'q[full_name_cont]', with: 'Whi'
wait_for_ajax
within '.autocomplete-suggestions' do
assert_text "#{@superadmin.full_name}; #{@superadmin.email}"\
" - #{I18n.t("role.#{@superadmin.role}")}",
normalize_ws: true
refute_text "#{@volunteer.full_name}; #{@volunteer.email}"\
" - #{I18n.t("role.#{@volunteer.role}")}",
normalize_ws: true,
wait: 0
end
end
test 'user with no profile is searchable with email' do
fill_in name: 'q[full_name_cont]', with: 'saul'
......@@ -46,9 +55,7 @@ class UserSearchesTest < ApplicationSystemTestCase
find_field(name: 'q[full_name_cont]').native.send_keys(:tab, :enter)
within 'tbody' do
assert_equal @department_manager.email, 'better_call_saul@good.man'
assert page.has_link? @department_manager.email
assert_link @department_manager.email
refute_text @superadmin.full_name, wait: 0
refute_text @social_worker.full_name, wait: 0
refute_text @volunteer.full_name, wait: 0
......
......@@ -3,39 +3,47 @@ require 'application_system_test_case'
class VolunteerSearchesTest < ApplicationSystemTestCase
def setup
@superadmin = create :user
@volunteers = ('a'..'z').to_a.map do |letter|
@volunteers = ('a'..'e').to_a.map do |letter|
volunteer_one = create :volunteer
volunteer_one.contact.update(first_name: (letter * 5) + volunteer_one.contact.first_name)
volunteer_two = create :volunteer
volunteer_two.contact.update(last_name: (letter * 5) + volunteer_two.contact.last_name)
[volunteer_one, volunteer_two]
end
[letter.to_sym, [volunteer_one, volunteer_two]]
end.to_h
login_as @superadmin
visit volunteers_path
end
test 'basic_non_suggests_search_works' do
fill_in name: 'q[contact_full_name_cont]', with: 'zzzz'
fill_in name: 'q[contact_full_name_cont]', with: 'eeee'
wait_for_ajax
page.find_field(name: 'q[contact_full_name_cont]').native.send_keys(:tab, :enter)
visit current_url
assert page.has_text? @volunteers.last.first.contact.full_name
assert page.has_text? @volunteers.last.last.contact.full_name
wait_for_ajax