From 7406904c51131389464a1240edf370e829307092 Mon Sep 17 00:00:00 2001 From: MaiteHdezRivas Date: Fri, 22 Jan 2016 09:50:17 +0100 Subject: [PATCH] adding suggest with coffescript --- app/assets/javascripts/application.js | 2 + app/assets/javascripts/show_results.js.coffee | 15 +++++++ .../concerns/commentable_actions.rb | 6 +++ app/controllers/debates_controller.rb | 2 +- app/controllers/proposals_controller.rb | 2 +- app/models/abilities/common.rb | 3 ++ app/views/debates/_form.html.erb | 5 +-- app/views/debates/suggest.html.erb | 25 +++++++++++ app/views/proposals/_form.html.erb | 3 +- app/views/proposals/suggest.html.erb | 25 +++++++++++ config/locales/en.yml | 12 +++++ config/locales/es.yml | 45 ++++++++++++++++--- config/routes.rb | 6 +++ db/schema.rb | 25 ++++++----- spec/features/debates_spec.rb | 42 ++++++++++++++++- spec/features/proposals_spec.rb | 39 ++++++++++++++++ 16 files changed, 233 insertions(+), 24 deletions(-) create mode 100644 app/assets/javascripts/show_results.js.coffee create mode 100644 app/views/debates/suggest.html.erb create mode 100644 app/views/proposals/suggest.html.erb mode change 100644 => 100755 config/locales/es.yml diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js index e7d288088..5fe006af7 100644 --- a/app/assets/javascripts/application.js +++ b/app/assets/javascripts/application.js @@ -35,6 +35,7 @@ //= require users //= require votes //= require annotatable +//= require show_results var initialize_modules = function() { @@ -48,6 +49,7 @@ var initialize_modules = function() { App.PreventDoubleSubmission.initialize(); App.IeAlert.initialize(); App.Annotatable.initialize(); + App.ShowResults.initialize(); }; $(function(){ diff --git a/app/assets/javascripts/show_results.js.coffee b/app/assets/javascripts/show_results.js.coffee new file mode 100644 index 000000000..b0c4c1dad --- /dev/null +++ b/app/assets/javascripts/show_results.js.coffee @@ -0,0 +1,15 @@ +App.ShowResults = + show: (ajax_show, ajax_url, query) -> + $.ajax + url: ajax_url, + data: {search: query}, + type: 'GET', + dataType: 'html' + success: (stHtml) -> + $(ajax_show).html(stHtml) + error: (xhr, status) -> + complete: (xhr, status) -> + + initialize: -> + $('[data-ajax-target]').on('blur',(event) -> + App.ShowResults.show($(this).data('ajax-show'), $(this).data('ajax-url'), $(this).val()) ) \ No newline at end of file diff --git a/app/controllers/concerns/commentable_actions.rb b/app/controllers/concerns/commentable_actions.rb index e04b275d1..a2384fec6 100644 --- a/app/controllers/concerns/commentable_actions.rb +++ b/app/controllers/concerns/commentable_actions.rb @@ -27,6 +27,12 @@ module CommentableActions load_featured_tags end + def suggest + @resources = @search_terms.present? ? resource_model.search(@search_terms).sort_by_confidence_score: nil + set_resources_instance + render :layout => false + end + def create @resource = resource_model.new(strong_params) @resource.author = current_user diff --git a/app/controllers/debates_controller.rb b/app/controllers/debates_controller.rb index 824118c8d..80c2659ec 100644 --- a/app/controllers/debates_controller.rb +++ b/app/controllers/debates_controller.rb @@ -2,7 +2,7 @@ class DebatesController < ApplicationController include CommentableActions include FlagActions - before_action :parse_search_terms, only: :index + before_action :parse_search_terms, only: [:index, :suggest] before_action :parse_tag_filter, only: :index before_action :set_search_order, only: :index before_action :authenticate_user!, except: [:index, :show] diff --git a/app/controllers/proposals_controller.rb b/app/controllers/proposals_controller.rb index 4a5e17af3..8e7f7d822 100644 --- a/app/controllers/proposals_controller.rb +++ b/app/controllers/proposals_controller.rb @@ -2,7 +2,7 @@ class ProposalsController < ApplicationController include CommentableActions include FlagActions - before_action :parse_search_terms, only: :index + before_action :parse_search_terms, only: [:index, :suggest] before_action :parse_tag_filter, only: :index before_action :set_search_order, only: :index before_action :authenticate_user!, except: [:index, :show] diff --git a/app/models/abilities/common.rb b/app/models/abilities/common.rb index 4d74ce375..002518dac 100644 --- a/app/models/abilities/common.rb +++ b/app/models/abilities/common.rb @@ -23,6 +23,9 @@ module Abilities can :create, Debate can :create, Proposal + can :suggest, Debate + can :suggest, Proposal + can [:flag, :unflag], Comment cannot [:flag, :unflag], Comment, user_id: user.id diff --git a/app/views/debates/_form.html.erb b/app/views/debates/_form.html.erb index adf7c432d..4ed1da9a0 100644 --- a/app/views/debates/_form.html.erb +++ b/app/views/debates/_form.html.erb @@ -1,12 +1,11 @@ <%= form_for(@debate) do |f| %> <%= render 'shared/errors', resource: @debate %> -
<%= f.label :title, t("debates.form.debate_title") %> - <%= f.text_field :title, maxlength: Debate.title_max_length, placeholder: t("debates.form.debate_title"), label: false %> + <%= f.text_field :title, maxlength: Debate.title_max_length, placeholder: t("debates.form.debate_title"), label: false, data: {ajax_target: "ajax_suggest", ajax_show: "#ajax_suggest_show", ajax_url: suggest_debates_path}%>
- +
<%= f.label :description, t("debates.form.debate_text") %> <%= f.cktext_area :description, maxlength: Debate.description_max_length, ckeditor: { language: I18n.locale }, label: false %> diff --git a/app/views/debates/suggest.html.erb b/app/views/debates/suggest.html.erb new file mode 100644 index 000000000..1143741fb --- /dev/null +++ b/app/views/debates/suggest.html.erb @@ -0,0 +1,25 @@ +
+ <% if @search_terms && @debates.count >0 %> + <% debates_count = @debates.count %> + <% query = @search_terms %> + <% limit = 5 %> +
+

+ <%= t("debates.new.suggestions.found", count: debates_count, query: query)%> +

+
    + <% @debates.take(limit).each do |debate| %> +
  • <%= link_to debate.title, debate %>
  • + <% end %> +
+ <% if debates_count > limit %> +

+ <%= t("debates.new.suggestions.message", count: debates_count, + query: query, + limit: limit)%> + <%= link_to t("debates.new.suggestions.see_all"), debates_path(:search => query)%> +

+ <% end %> +
+ <% end %> +
\ No newline at end of file diff --git a/app/views/proposals/_form.html.erb b/app/views/proposals/_form.html.erb index 97e1ecb6b..a018d4486 100644 --- a/app/views/proposals/_form.html.erb +++ b/app/views/proposals/_form.html.erb @@ -4,8 +4,9 @@
<%= f.label :title, t("proposals.form.proposal_title") %> - <%= f.text_field :title, maxlength: Proposal.title_max_length, placeholder: t("proposals.form.proposal_title"), label: false %> + <%= f.text_field :title, maxlength: Proposal.title_max_length, placeholder: t("proposals.form.proposal_title"), label: false, data: {ajax_target: "ajax_suggest", ajax_show: "#ajax_suggest_show", ajax_url: suggest_proposals_path}%>
+
<%= f.label :question, t("proposals.form.proposal_question") %> diff --git a/app/views/proposals/suggest.html.erb b/app/views/proposals/suggest.html.erb new file mode 100644 index 000000000..4d66be41f --- /dev/null +++ b/app/views/proposals/suggest.html.erb @@ -0,0 +1,25 @@ +
+ <% if @search_terms && @proposals.count >0 %> + <% proposals_count = @proposals.count %> + <% query = @search_terms %> + <% limit = 5 %> +
+

+ <%= t("proposals.new.suggestions.found", count: proposals_count, query: query)%> +

+
    + <% @proposals.take(limit).each do |proposal| %> +
  • <%= link_to proposal.title, proposal %>
  • + <% end %> +
+ <% if proposals_count > limit %> +

+ <%= t("proposals.new.suggestions.message", count: proposals_count, + query: query, + limit: limit)%> + <%= link_to t("proposals.new.suggestions.see_all"), proposals_path(:search => query)%> +

+ <% end %> +
+ <% end %> +
\ No newline at end of file diff --git a/config/locales/en.yml b/config/locales/en.yml index dd62006d5..e5fa01e12 100755 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -121,6 +121,12 @@ en: recommendation_two: Any debate or comment suggesting illegal action will be deleted, as well as those intending to sabotage the debate spaces. Anything else is allowed. recommendations_title: Recommendations for creating a debate start_new: Start a debate + suggestions: + found: + one: "There is a debate with the term '%{query}', you can participate in it instead of opening a new one." + other: "There are debates with the term '%{query}', you can participate in them instead of opening a new one." + message: "You are seeing %{limit} of %{count} debates containing the term %{query}" + see_all: "See all" show: author_deleted: User deleted back_link: Go back @@ -296,6 +302,12 @@ en: recommendation_two: Any proposal or comment suggesting illegal action will be deleted, as well as those intending to sabotage the debate spaces. Anything else is allowed. recommendations_title: Recommendations for creating a proposal start_new: Create new proposal + suggestions: + found: + one: "There is a proposal by the term '%{query}', you can contribute to it instead of creating a new" + other: "There are proposals by the term '%{query}', you can contribute to them instead of creating a new" + message: "You are seeing %{limit} of %{count} proposals containing the term %{query}" + see_all: "See all" proposal: already_supported: You have already supported this proposal. Share it! comments: diff --git a/config/locales/es.yml b/config/locales/es.yml old mode 100644 new mode 100755 index 6bcb7c4af..8210505d3 --- a/config/locales/es.yml +++ b/config/locales/es.yml @@ -26,7 +26,8 @@ es: user_permission_votes: Participar en las votaciones finales* username_label: Nombre de usuario verified_account: Cuenta verificada - verify_my_account: Verificar mi cuenta + verify_my_account: Verificar mi cuentaquer + application: close: Cerrar menu: Menú @@ -86,7 +87,7 @@ es: debate_title: Título del debate tags_instructions: Etiqueta este debate. Puedes elegir entre nuestras propuestas o introducir las que desees. tags_label: Temas - tags_placeholder: Escribe las etiquetas que desees separadas por coma (',') + tags_placeholder: "Escribe las etiquetas que desees separadas por coma (',')" index: featured_debates: Destacados filter_topic: @@ -121,6 +122,12 @@ es: recommendation_two: Cualquier debate o comentario que implique una acción ilegal será eliminado, también los que tengan la intención de sabotear los espacios de debate, todo lo demás está permitido. recommendations_title: Recomendaciones para crear un debate start_new: Empezar un debate + suggestions: + found: + one: "Existe un debate con el término '%{query}', puedes participar en él en vez de abrir uno nuevo." + other: "Existen debates con el término '%{query}', puedes participar en ellos en vez de abrir uno nuevo." + message: "Estás viendo %{limit} de %{count} debates que contienen el término %{query}" + see_all: "Ver todos" show: author_deleted: Usuario eliminado back_link: Volver @@ -184,7 +191,6 @@ es: administration: Administrar debates: Debates external_link_blog: Blog - external_link_blog_url: "/blog" external_link_opendata: Datos abiertos external_link_opendata_url: http://datos.madrid.es external_link_transparency: Transparencia @@ -204,7 +210,6 @@ es: open_city_title: La ciudad que quieres será la ciudad que quieras. open_data: Datos abiertos open_gov: Gobierno %{open} - participation_html: Madrid Decide proposals: Propuestas see_all: Ver propuestas spending_proposals: Presupuestos ciudadanos @@ -263,7 +268,7 @@ es: proposal_video_url_note: Puedes añadir un enlace a YouTube o Vimeo tags_instructions: Etiqueta esta propuesta. Puedes elegir entre nuestras sugerencias o introducir las que desees. tags_label: Temas - tags_placeholder: Escribe las etiquetas que desees separadas por una coma (',') + tags_placeholder: "Escribe las etiquetas que desees separadas por una coma (',')" index: featured_proposals: Destacadas filter_topic: @@ -296,6 +301,12 @@ es: recommendation_two: Cualquier propuesta o comentario que implique una acción ilegal será eliminada, también las que tengan la intención de sabotear los espacios de propuesta, todo lo demás está permitido. recommendations_title: Recomendaciones para crear una propuesta start_new: Crear una propuesta + suggestions: + found: + one: "Existe un debate con el término '%{query}', puedes participar en él en vez de abrir uno nuevo." + other: "Existen debates con el término '%{query}', puedes participar en ellos en vez de abrir uno nuevo." + message: "Estás viendo %{limit} de %{count} debates que contienen el término %{query}" + see_all: "Ver todos" proposal: already_supported: "¡Ya has apoyado esta propuesta, compártela!" comments: @@ -329,6 +340,28 @@ es: form: submit_button: Guardar cambios shared: + advanced_search: + author_type: 'Por categoría de autor' + author_type_blank: 'Elige una categoría' + author_type_1: 'Empleado público' + author_type_2: 'Organización Municipal' + author_type_3: 'Director general' + author_type_4: 'Concejal' + author_type_5: 'Alcaldesa' + date: 'Por fecha' + date_placeholder: 'DD/MM/AAAA' + date_range_blank: 'Elige una fecha' + date_1: 'Últimas 24 horas' + date_2: 'Última semana' + date_3: 'Último mes' + date_4: 'Último año' + date_5: 'Personalizada' + from: 'Desde' + general: 'Con el texto' + general_placeholder: 'Escribe el texto' + search: 'Filtrar' + title: 'Búsqueda avanzada' + to: 'Hasta' author_info: author_deleted: Usuario eliminado check: Seleccionar @@ -381,7 +414,7 @@ es: unauthorized: default: No tienes permiso para acceder a esta página. manage: - all: No tienes permiso para realizar la acción '%{action}' sobre %{subject}. + all: "No tienes permiso para realizar la acción '%{action}' sobre %{subject}." users: show: deleted: Eliminado diff --git a/config/routes.rb b/config/routes.rb index d0fa9f576..8da7294cf 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -42,6 +42,9 @@ Rails.application.routes.draw do put :flag put :unflag end + collection do + get :suggest + end end resources :proposals do @@ -51,6 +54,9 @@ Rails.application.routes.draw do put :flag put :unflag end + collection do + get :suggest + end end resources :comments, only: [:create, :show], shallow: true do diff --git a/db/schema.rb b/db/schema.rb index 2924fed64..28f9dc91d 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -103,21 +103,22 @@ ActiveRecord::Schema.define(version: 20160114110933) do t.string "title", limit: 80 t.text "description" t.integer "author_id" - t.datetime "created_at", null: false - t.datetime "updated_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false t.string "visit_id" t.datetime "hidden_at" - t.integer "flags_count", default: 0 + t.integer "flags_count", default: 0 + t.integer "cached_votes_total", default: 0 + t.integer "cached_votes_up", default: 0 + t.integer "cached_votes_down", default: 0 t.datetime "ignored_flag_at" - t.integer "cached_votes_total", default: 0 - t.integer "cached_votes_up", default: 0 - t.integer "cached_votes_down", default: 0 - t.integer "comments_count", default: 0 + t.integer "comments_count", default: 0 t.datetime "confirmed_hide_at" - t.integer "cached_anonymous_votes_total", default: 0 - t.integer "cached_votes_score", default: 0 - t.integer "hot_score", limit: 8, default: 0 - t.integer "confidence_score", default: 0 + t.integer "cached_anonymous_votes_total", default: 0 + t.integer "cached_votes_score", default: 0 + t.integer "hot_score", limit: 8, default: 0 + t.integer "confidence_score", default: 0 + t.string "external_link", limit: 100 end add_index "debates", ["author_id", "hidden_at"], name: "index_debates_on_author_id_and_hidden_at", using: :btree @@ -127,6 +128,7 @@ ActiveRecord::Schema.define(version: 20160114110933) do add_index "debates", ["cached_votes_total"], name: "index_debates_on_cached_votes_total", using: :btree add_index "debates", ["cached_votes_up"], name: "index_debates_on_cached_votes_up", using: :btree add_index "debates", ["confidence_score"], name: "index_debates_on_confidence_score", using: :btree + add_index "debates", ["description"], name: "index_debates_on_description", using: :btree add_index "debates", ["hidden_at"], name: "index_debates_on_hidden_at", using: :btree add_index "debates", ["hot_score"], name: "index_debates_on_hot_score", using: :btree add_index "debates", ["title"], name: "index_debates_on_title", using: :btree @@ -258,6 +260,7 @@ ActiveRecord::Schema.define(version: 20160114110933) do add_index "proposals", ["author_id"], name: "index_proposals_on_author_id", using: :btree add_index "proposals", ["cached_votes_up"], name: "index_proposals_on_cached_votes_up", using: :btree add_index "proposals", ["confidence_score"], name: "index_proposals_on_confidence_score", using: :btree + add_index "proposals", ["description"], name: "index_proposals_on_description", using: :btree add_index "proposals", ["hidden_at"], name: "index_proposals_on_hidden_at", using: :btree add_index "proposals", ["hot_score"], name: "index_proposals_on_hot_score", using: :btree add_index "proposals", ["question"], name: "index_proposals_on_question", using: :btree diff --git a/spec/features/debates_spec.rb b/spec/features/debates_spec.rb index 6ef03d06e..a98983871 100644 --- a/spec/features/debates_spec.rb +++ b/spec/features/debates_spec.rb @@ -560,4 +560,44 @@ feature 'Debates' do visit debate_path(debate) expect(page).to have_content('User deleted') end -end + + context 'Suggesting debates' do + + scenario 'Shows up to 5 suggestions per debate', :js do + author = create(:user) + login_as(author) + + debate1 = create(:debate, title: "1 - El Quijote: En un lugar de la Mancha", cached_votes_up: 1) + debate2 = create(:debate, title: "2 - El Quijote: de cuyo nombre no quiero acordarme", cached_votes_up: 2) + debate3 = create(:debate, title: "3 - El Quijote: no ha mucho tiempo que vivía ", cached_votes_up: 3) + debate4 = create(:debate, title: "4 - un hidalgo de los de lanza en astillero", description: "El Quijote un hidalgo de los de lanza en astillero", cached_votes_up: 4) + debate5 = create(:debate, title: "5 - El Quijote: adarga antigua, rocín flaco y galgo corredor", cached_votes_up: 5) + debate6 = create(:debate, title: "6 - Una olla de algo más vaca que carnero", description: 'El Quijote', cached_votes_up: 6) + debate7 = create(:debate, title: "7 - No se sugiere", cached_votes_up: 7) + + visit new_debate_path + fill_in 'debate_title', with: 'Quijote' + page.find("body").click + + within('div#ajax_suggest_show') do + expect(page.html).to have_content ("You are seeing 5 of 6 debates containing the term Quijote") + end + end + + scenario 'No found suggestions for debate', :js do + author = create(:user) + login_as(author) + + debate1 = create(:debate, title: "El Quijote: En un lugar de la Mancha", cached_votes_up: 10) + debate2 = create(:debate, title: "El Quijote: de cuyo nombre no quiero acordarme") + + visit new_debate_path + fill_in 'debate_title', with: 'La Celestina' + page.find("body").click + + within('div#ajax_suggest_show') do + expect(page.html).to_not have_content ('You are seeing') + end + end + end +end \ No newline at end of file diff --git a/spec/features/proposals_spec.rb b/spec/features/proposals_spec.rb index e6938a432..6bdfa793f 100644 --- a/spec/features/proposals_spec.rb +++ b/spec/features/proposals_spec.rb @@ -662,4 +662,43 @@ feature 'Proposals' do visit proposals_path expect(page).to have_content('User deleted') end + + context 'Suggesting proposals' do + + scenario 'Shows up to 5 suggestions per proposal', :js do + author = create(:user) + login_as(author) + + create(:proposal, title: 'First proposal').update_column(:confidence_score, 10) + create(:proposal, title: 'Second proposal').update_column(:confidence_score, 8) + create(:proposal, title: 'Third proposal').update_column(:confidence_score, 6) + create(:proposal, title: 'Fourth proposal').update_column(:confidence_score, 4) + create(:proposal, title: 'Fifth proposal').update_column(:confidence_score, 3) + create(:proposal, title: 'Sixth proposal').update_column(:confidence_score, 1) + + visit new_proposal_path + fill_in 'proposal_title', with: 'proposal' + page.find("body").click + + within('div#ajax_suggest_show') do + expect(page.html).to have_content ("You are seeing 5 of 6 proposals containing the term proposal") + end + end + + scenario 'No found suggestions for debate', :js do + author = create(:user) + login_as(author) + + create(:proposal, title: 'First proposal').update_column(:confidence_score, 10) + create(:proposal, title: 'Second proposal').update_column(:confidence_score, 8) + + visit new_proposal_path + fill_in 'proposal_title', with: 'debate' + page.find("body").click + + within('div#ajax_suggest_show') do + expect(page.html).to_not have_content ('You are seeing') + end + end + end end