From c11dd13c387e3f3a0dc1d34d9759905f904ae285 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Wed, 14 Feb 2024 21:23:22 -0300 Subject: [PATCH 01/27] =?UTF-8?q?feat/adiciona=20m=C3=A9todo=20que=20orden?= =?UTF-8?q?a=20perfis?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit -ordena perfis por tipo de assinatura e depois por ordem alfabética --- app/controllers/api/v1/profiles_controller.rb | 4 +- app/models/profile.rb | 32 +++++++------ spec/factories/subscriptions.rb | 2 +- spec/models/profile_spec.rb | 31 ++++++++++++ .../v1/search_user_by_job_categories_spec.rb | 48 ++++++++++++++++--- spec/system/subscription/paid_user_spec.rb | 0 6 files changed, 93 insertions(+), 24 deletions(-) delete mode 100644 spec/system/subscription/paid_user_spec.rb diff --git a/app/controllers/api/v1/profiles_controller.rb b/app/controllers/api/v1/profiles_controller.rb index 0753494..258a979 100644 --- a/app/controllers/api/v1/profiles_controller.rb +++ b/app/controllers/api/v1/profiles_controller.rb @@ -3,10 +3,10 @@ module V1 class ProfilesController < ApiController def index if params[:search].blank? - profiles = Profile.active.open_to_work + profiles = Profile.active.open_to_work.order_by_premium profiles = profiles.map { |profile| format_profile(profile) } else - profiles = Profile.active.open_to_work.get_profile_job_categories_json(params[:search]) + profiles = Profile.active.open_to_work.order_by_premium.get_profile_job_categories_json(params[:search]) end render status: :ok, json: { data: profiles } end diff --git a/app/models/profile.rb b/app/models/profile.rb index 663de5e..510652a 100644 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -1,30 +1,30 @@ class Profile < ApplicationRecord belongs_to :user + + has_one_attached :photo has_one :personal_info, dependent: :destroy + has_many :professional_infos, dependent: :destroy has_many :education_infos, dependent: :destroy has_many :profile_job_categories, dependent: :destroy - - has_many :followers, class_name: 'Connection', foreign_key: :followed_profile_id, dependent: :destroy, - inverse_of: :follower - - has_many :followed_profiles, class_name: 'Connection', foreign_key: :follower_id, - dependent: :destroy, inverse_of: :followed_profile - - has_many :connections, foreign_key: :followed_profile_id, dependent: :destroy, inverse_of: :followed_profile - - has_many :job_categories, through: :profile_job_categories + has_many :invitations, dependent: :destroy + has_many :notifications, dependent: :destroy has_many :invitation_requests, dependent: :destroy - has_one_attached :photo - has_many :invitations, dependent: :destroy has_many :posts, through: :user - has_many :notifications, dependent: :destroy + has_many :job_categories, through: :profile_job_categories has_many :reports_submitted, class_name: 'Report', dependent: :destroy - has_many :reports_received, class_name: 'Report', as: :reportable, dependent: :destroy + has_many :connections, foreign_key: :followed_profile_id, dependent: :destroy, inverse_of: :followed_profile + + has_many :followers, class_name: 'Connection', foreign_key: :followed_profile_id, dependent: :destroy, + inverse_of: :follower + + has_many :followed_profiles, class_name: 'Connection', foreign_key: :follower_id, dependent: :destroy, + inverse_of: :followed_profile + accepts_nested_attributes_for :personal_info accepts_nested_attributes_for :professional_infos accepts_nested_attributes_for :education_infos @@ -40,6 +40,10 @@ class Profile < ApplicationRecord delegate :full_name, :email, to: :user + def self.order_by_premium + joins(user: :subscription).order('subscriptions.status DESC, users.full_name ASC') + end + def self.advanced_search(search_query) left_outer_joins(:job_categories, :personal_info, :user).where( 'job_categories.name LIKE :term OR diff --git a/spec/factories/subscriptions.rb b/spec/factories/subscriptions.rb index 61e6e6b..c93afed 100644 --- a/spec/factories/subscriptions.rb +++ b/spec/factories/subscriptions.rb @@ -1,7 +1,7 @@ FactoryBot.define do factory :subscription do user { nil } - start_date { "2024-02-14" } + start_date { '2024-02-14' } status { 1 } end end diff --git a/spec/models/profile_spec.rb b/spec/models/profile_spec.rb index 217d17f..5c2c04c 100644 --- a/spec/models/profile_spec.rb +++ b/spec/models/profile_spec.rb @@ -248,4 +248,35 @@ expect(Connection.active.count).to eq 2 end end + + describe '#order_by_premium' do + it 'retorna perfis premium primeiro e depois os perfis free' do + create(:user, :free, full_name: 'André Porteira') + create(:user, :free, full_name: 'Eliseu Ramos') + create(:user, full_name: 'Moisés Campus') + user_premium_inactive = create(:user, full_name: 'Joao Almeida') + user_premium_inactive.subscription.inactive! + + result = Profile.order_by_premium + + expect(result.first.full_name).to eq 'Moisés Campus' + expect(result.second.full_name).to eq 'André Porteira' + expect(result.third.full_name).to eq 'Eliseu Ramos' + expect(result.fourth.full_name).to eq 'Joao Almeida' + end + + it 'ordena por nome em caso de mesmo status de assinatura' do + create(:user, :free, full_name: 'André Almeida') + create(:user, :free, full_name: 'André Barbosa') + create(:user, full_name: 'André Campus') + create(:user, full_name: 'André Dias') + + result = Profile.order_by_premium + + expect(result.first.full_name).to eq 'André Campus' + expect(result.second.full_name).to eq 'André Dias' + expect(result.third.full_name).to eq 'André Almeida' + expect(result.fourth.full_name).to eq 'André Barbosa' + end + end end diff --git a/spec/requests/apis/v1/search_user_by_job_categories_spec.rb b/spec/requests/apis/v1/search_user_by_job_categories_spec.rb index b8a5ccb..4c821f1 100644 --- a/spec/requests/apis/v1/search_user_by_job_categories_spec.rb +++ b/spec/requests/apis/v1/search_user_by_job_categories_spec.rb @@ -67,13 +67,13 @@ expect(json_response['data'].class).to eq Array expect(json_response['data'].first.keys).not_to include 'created_at' expect(json_response['data'].first.keys).not_to include 'updated_at' - expect(json_response['data'].first['profile_id']).to eq 1 - expect(json_response['data'].first['full_name']).to eq 'Joao Almeida' - expect(json_response['data'].first['job_categories']).to eq [{ 'name' => 'Ruby on Rails', - 'description' => 'Especialista em Ruby.' }] - expect(json_response['data'].second['profile_id']).to eq 2 - expect(json_response['data'].second['full_name']).to eq 'André Porteira' - expect(json_response['data'].second['job_categories']).to eq [] + expect(json_response['data'].first['profile_id']).to eq 2 + expect(json_response['data'].first['full_name']).to eq 'André Porteira' + expect(json_response['data'].first['job_categories']).to eq [] + expect(json_response['data'].second['profile_id']).to eq 1 + expect(json_response['data'].second['full_name']).to eq 'Joao Almeida' + expect(json_response['data'].second['job_categories']).to eq [{ 'name' => 'Ruby on Rails', + 'description' => 'Especialista em Ruby.' }] end it 'retorna um erro interno do servidor' do @@ -86,5 +86,39 @@ expect(json_response.class).to eq Hash expect(json_response['error']).to eq 'Houve um erro interno no servidor ao processar sua solicitação.' end + + it 'retorna perfis premium primeiro e depois os perfis comuns' do + create(:user, :free, full_name: 'Eliseu Ramos') + create(:user, :free, full_name: 'André Porteira') + create(:user, full_name: 'Moisés Campus') + create(:user, full_name: 'Joao Almeida') + + get '/api/v1/profiles' + + expect(response.status).to eq 200 + json_response = JSON.parse(response.body) + expect(json_response['data'].count).to eq 4 + expect(json_response['data'].first['full_name']).to eq 'Joao Almeida' + expect(json_response['data'].second['full_name']).to eq 'Moisés Campus' + expect(json_response['data'].third['full_name']).to eq 'André Porteira' + expect(json_response['data'].fourth['full_name']).to eq 'Eliseu Ramos' + end + + it 'retorna perfis premium primeiro e depois os perfis free na busca com parâmetro' do + ruby = create(:job_category, name: 'Ruby on Rails') + + user_premium = create(:user, full_name: 'Moisés Campus') + user_premium.profile.profile_job_categories.create(job_category: ruby, description: 'Sou um especialista em Ruby') + user_free = create(:user, :free, full_name: 'André Almeida') + user_free.profile.profile_job_categories.create(job_category: ruby, description: 'Fiz um e-commerce em Ruby') + + get '/api/v1/profiles', params: { search: 'ruby' } + + expect(response.status).to eq 200 + json_response = JSON.parse(response.body) + expect(json_response['data'].count).to eq 2 + expect(json_response['data'].first['full_name']).to eq 'Moisés Campus' + expect(json_response['data'].second['full_name']).to eq 'André Almeida' + end end end diff --git a/spec/system/subscription/paid_user_spec.rb b/spec/system/subscription/paid_user_spec.rb deleted file mode 100644 index e69de29..0000000 From f6aaebb9f3686f9a8966aac266627f937f5073ad Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Wed, 14 Feb 2024 21:46:31 -0300 Subject: [PATCH 02/27] =?UTF-8?q?remove=20linhas=20n=C3=A3o=20usadas?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/projects_controller.rb | 10 +-- app/javascript/components/projects_vue.js | 1 - app/views/invitation_requests/index.html.erb | 84 +++++++++----------- app/views/projects/index.html.erb | 11 +-- app/views/shared/_navbar.html.erb | 6 +- config/locales/subscription.pt-BR.yml | 10 --- spec/models/subscription_spec.rb | 1 - spec/system/subscription/free_user_spec.rb | 27 ------- 8 files changed, 46 insertions(+), 104 deletions(-) delete mode 100644 config/locales/subscription.pt-BR.yml delete mode 100644 spec/system/subscription/free_user_spec.rb diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 73ba19a..836951b 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -1,12 +1,10 @@ class ProjectsController < ApplicationController before_action :authenticate_user! - before_action :authenticate_subscriber, only: :create_invitation_request def index @invitation_request = current_user.invitation_requests.build @invitation_requests = current_user.invitation_requests.pluck(:project_id).to_json @invitation_requests_projects_ids = current_user.invitation_requests.pluck(:project_id) - @free_user = current_user.subscription.inactive? end def create_invitation_request @@ -21,15 +19,9 @@ def create_invitation_request private - def authenticate_subscriber - return if current_user.subscription.active? - - redirect_to root_path, alert: t('alerts.unauthorized') - end - def invitation_request_params invitation_request_params = params.require(:invitation_request).permit(:message) invitation_request_params['project_id'] = params['project_id'] invitation_request_params end -end +end \ No newline at end of file diff --git a/app/javascript/components/projects_vue.js b/app/javascript/components/projects_vue.js index 264b1ba..de014f3 100644 --- a/app/javascript/components/projects_vue.js +++ b/app/javascript/components/projects_vue.js @@ -10,7 +10,6 @@ export default { showingForm: false, currentProjectId: null, invitationRequestsProjectsIds: window.invitationRequestsProjectsIds, - freeUser: window.freeUser, errorMsg: false, } }, diff --git a/app/views/invitation_requests/index.html.erb b/app/views/invitation_requests/index.html.erb index 5f997e1..187dc77 100644 --- a/app/views/invitation_requests/index.html.erb +++ b/app/views/invitation_requests/index.html.erb @@ -1,54 +1,48 @@

<%= InvitationRequest.model_name.human(count: @invitation_request_infos.length) %>

-<% if current_user.subscription.inactive? %> -
-

<%= t('subscriptions.become') %> <%= t('subscriptions.subscriber') %> <%= t('subscriptions.see_and_request') %>

-
-<% else %> -
-
- <%= form_with url: invitation_requests_path, method: :get, class: 'col-10 me-5 px-0' do |f| %> -
- <%= f.label :filter, class: 'd-none' %> - <%= f.select :filter, - invitation_request_filter_options, - { include_blank: 'Todas', selected: params[:filter] }, - class: 'form-select' %> - <%= f.submit t(:filter_btn ), class: 'btn btn-sm btn-primary' %> -
- <% end %> +
+
+ <%= form_with url: invitation_requests_path, method: :get, class: 'col-10 me-5 px-0' do |f| %> +
+ <%= f.label :filter, class: 'd-none' %> + <%= f.select :filter, + invitation_request_filter_options, + { include_blank: 'Todas', selected: params[:filter] }, + class: 'form-select' %> + <%= f.submit t(:filter_btn ), class: 'btn btn-sm btn-primary' %> +
+ <% end %> - <% if @invitation_request_infos.any? %> - <% @invitation_request_infos.each do |invitation_request| %> -
-
-
-
-

<%= invitation_request.project_title %>

-
-

<%= invitation_request.project_description %>

-

<%= invitation_request.project_category %>

-
-
-
-

- <%= t(:time_ago, time: time_ago_in_words(invitation_request.created_at)) %> -

-

- <%= InvitationRequest.human_attribute_name("status.#{invitation_request.status}") %> -

+ <% if @invitation_request_infos.any? %> + <% @invitation_request_infos.each do |invitation_request| %> +
+
+
+
+

<%= invitation_request.project_title %>

+
+

<%= invitation_request.project_description %>

+

<%= invitation_request.project_category %>

+
+

+ <%= t(:time_ago, time: time_ago_in_words(invitation_request.created_at)) %> +

+

+ <%= InvitationRequest.human_attribute_name("status.#{invitation_request.status}") %> +

+
- <% end %> - <% elsif @error %> -

<%= t(:project_api_error) %>

- <% elsif params[:filter].nil? || params[:filter].blank? %> -

<%= t(:no_invitation_request_msg) %>

- <% else %> -

<%= t(:no_filter_results_msg) %>

+
<% end %> -
+ <% elsif @error %> +

<%= t(:project_api_error) %>

+ <% elsif params[:filter].nil? || params[:filter].blank? %> +

<%= t(:no_invitation_request_msg) %>

+ <% else %> +

<%= t(:no_filter_results_msg) %>

+ <% end %>
-<% end %> +
\ No newline at end of file diff --git a/app/views/projects/index.html.erb b/app/views/projects/index.html.erb index 1d92514..b744574 100644 --- a/app/views/projects/index.html.erb +++ b/app/views/projects/index.html.erb @@ -1,11 +1,7 @@

<%= t('.index_title') %>

-
-

<%= t('subscriptions.become') %> <%= t('subscriptions.subscriber') %> <%= t('subscriptions.see_listed_projects') %>

-
- -
+

{{ emptyData }}

@@ -44,7 +40,7 @@

<%= t('.errors.no_result') %>

- +

{{ project.title }}

@@ -75,5 +71,4 @@ + \ No newline at end of file diff --git a/app/views/shared/_navbar.html.erb b/app/views/shared/_navbar.html.erb index 9703ba1..2192c4a 100644 --- a/app/views/shared/_navbar.html.erb +++ b/app/views/shared/_navbar.html.erb @@ -34,13 +34,13 @@ <%= link_to "#{current_user.description}", current_user.profile, class: 'nav-link' %>
- + \ No newline at end of file From ac2565c6ebd160d3823c8d22dffff11cd44f99e2 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Wed, 14 Feb 2024 21:52:16 -0300 Subject: [PATCH 04/27] fix/rubocop --- app/controllers/projects_controller.rb | 2 +- app/views/projects/index.html.erb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index 836951b..d0996a6 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -24,4 +24,4 @@ def invitation_request_params invitation_request_params['project_id'] = params['project_id'] invitation_request_params end -end \ No newline at end of file +end diff --git a/app/views/projects/index.html.erb b/app/views/projects/index.html.erb index b744574..4d36291 100644 --- a/app/views/projects/index.html.erb +++ b/app/views/projects/index.html.erb @@ -71,4 +71,4 @@ \ No newline at end of file + From 43fb3c31158e54a427f9bd6384714038d9c42ef9 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Wed, 14 Feb 2024 21:54:38 -0300 Subject: [PATCH 05/27] fix/rubocop --- app/views/invitation_requests/index.html.erb | 2 +- app/views/shared/_navbar.html.erb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/app/views/invitation_requests/index.html.erb b/app/views/invitation_requests/index.html.erb index 187dc77..bd101c2 100644 --- a/app/views/invitation_requests/index.html.erb +++ b/app/views/invitation_requests/index.html.erb @@ -45,4 +45,4 @@

<%= t(:no_filter_results_msg) %>

<% end %>
-
\ No newline at end of file +
diff --git a/app/views/shared/_navbar.html.erb b/app/views/shared/_navbar.html.erb index 4c78dc1..9f54c3e 100644 --- a/app/views/shared/_navbar.html.erb +++ b/app/views/shared/_navbar.html.erb @@ -83,4 +83,4 @@
- \ No newline at end of file + From 78ff119ddfcdeb3e8d77a7e3dee31abba42befeb Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Wed, 14 Feb 2024 22:12:13 -0300 Subject: [PATCH 06/27] =?UTF-8?q?remove=20arquivos=20n=C3=A3o=20usados?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- spec/factories/subscriptions.rb | 7 ------- spec/models/subscription_spec.rb | 4 ---- 2 files changed, 11 deletions(-) delete mode 100644 spec/factories/subscriptions.rb delete mode 100644 spec/models/subscription_spec.rb diff --git a/spec/factories/subscriptions.rb b/spec/factories/subscriptions.rb deleted file mode 100644 index c93afed..0000000 --- a/spec/factories/subscriptions.rb +++ /dev/null @@ -1,7 +0,0 @@ -FactoryBot.define do - factory :subscription do - user { nil } - start_date { '2024-02-14' } - status { 1 } - end -end diff --git a/spec/models/subscription_spec.rb b/spec/models/subscription_spec.rb deleted file mode 100644 index 67bb6fc..0000000 --- a/spec/models/subscription_spec.rb +++ /dev/null @@ -1,4 +0,0 @@ -require 'rails_helper' - -RSpec.describe Subscription, type: :model do -end From 8516be9fb2bfc8720f7964ec7065058bf8825ac4 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 10:40:34 -0300 Subject: [PATCH 07/27] =?UTF-8?q?Move=20chamadas=20de=20POST=20colabora/ap?= =?UTF-8?q?i/v1/proposals=20para=20servi=C3=A7o?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move toda lógica de requisições POST localhost:3000/api/v1/proposals para o serviço de InvitationRequest. Reduz a quantidade de parâmetros necessários para requisição no endpoint GET localhost:4000/api/v1/projects/request_invitation, para simplificar a lógica. Remove método #create_json_for_proposal_request do modelo InvitationRequest por tornar-se desnecessário na nova lógica. Altera parâmetros enviados pelo job RequestInvitationJob ao chamar a API do Portfoliorrr Ajusta testes para nova lógica. --- app/controllers/api/v1/projects_controller.rb | 9 +- .../invitation_requests_controller.rb | 2 +- app/jobs/request_invitation_job.rb | 2 +- app/models/invitation_request.rb | 8 -- app/services/invitation_request_service.rb | 35 +++++- spec/jobs/request_invitation_job_spec.rb | 30 +---- .../projects_request_invitations_api_spec.rb | 106 ++++++++---------- .../invitation_request_spec.rb | 6 +- 8 files changed, 90 insertions(+), 108 deletions(-) diff --git a/app/controllers/api/v1/projects_controller.rb b/app/controllers/api/v1/projects_controller.rb index 44685ba..ad1929a 100644 --- a/app/controllers/api/v1/projects_controller.rb +++ b/app/controllers/api/v1/projects_controller.rb @@ -13,9 +13,9 @@ def index end def request_invitation - data = proposal_params.as_json - connection = Faraday.new(url: 'http://localhost:3000', params: data) - response = connection.post('api/v1/proposals') + invitation_request_id = proposal_params.fetch('invitation_request_id').to_i + invitation_request = InvitationRequest.find(invitation_request_id) + response = InvitationRequestService::ColaBoraInvitationRequestPost.send(invitation_request) if response.status == 201 proposal = JSON.parse(response.body) @@ -29,8 +29,7 @@ def request_invitation private def proposal_params - proposal_attributes = %i[invitation_request_id email message profile_id project_id] - params.require(:data).permit(proposal: proposal_attributes) + params.permit(:invitation_request_id) end end end diff --git a/app/controllers/invitation_requests_controller.rb b/app/controllers/invitation_requests_controller.rb index 3637a96..068112e 100644 --- a/app/controllers/invitation_requests_controller.rb +++ b/app/controllers/invitation_requests_controller.rb @@ -7,7 +7,7 @@ def index @invitation_request_infos = [] begin - @invitation_request_infos = InvitationRequestService::InvitationRequest.send(invitation_requests) + @invitation_request_infos = InvitationRequestService::InvitationRequest.list(invitation_requests) rescue StandardError return @error = true end diff --git a/app/jobs/request_invitation_job.rb b/app/jobs/request_invitation_job.rb index 23b5659..b641ac3 100644 --- a/app/jobs/request_invitation_job.rb +++ b/app/jobs/request_invitation_job.rb @@ -6,7 +6,7 @@ class RequestInvitationJob < ApplicationJob end def perform(invitation_request:) - data = invitation_request.create_json_for_proposal_request + data = { invitation_request_id: invitation_request.id }.as_json response = Faraday.new(url: 'http://localhost:4000', params: data).get('/api/v1/projects/request_invitation') return raise Exceptions::PortfoliorrrAPIOffline if response.status == :internal_server_error diff --git a/app/models/invitation_request.rb b/app/models/invitation_request.rb index ac2723f..2edd0af 100644 --- a/app/models/invitation_request.rb +++ b/app/models/invitation_request.rb @@ -22,14 +22,6 @@ def process_colabora_api_response(response) end end - def create_json_for_proposal_request - { data: { proposal: { invitation_request_id: id, - project_id:, - profile_id: profile.id, - email: profile.email, - message: } } }.as_json - end - private def json_treated_response(response) diff --git a/app/services/invitation_request_service.rb b/app/services/invitation_request_service.rb index 85a38c5..1b34e8b 100644 --- a/app/services/invitation_request_service.rb +++ b/app/services/invitation_request_service.rb @@ -1,10 +1,12 @@ module InvitationRequestService - COLABORA_PROJECTS_URL = 'http://localhost:3000/api/v1/projects'.freeze - COLABORA_INVITATIONS_BASE_URL = 'http://localhost:3000/api/v1/invitations'.freeze + COLABORA_BASE_URL = 'http://localhost:3000'.freeze + COLABORA_API_V1_PROJECTS_URL = '/api/v1/projects'.freeze + COLABORA_API_V1_PROPOSALS_URL = '/api/v1/proposals'.freeze + COLABORA_API_V1_INVITATIONS_BASE_URL = '/api/v1/invitations'.freeze class ColaboraProject def self.send - @response = Faraday.get(COLABORA_PROJECTS_URL) + @response = Faraday.get("#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}") return build_projects if @response.success? raise StandardError @@ -26,7 +28,7 @@ def build_projects end class InvitationRequest - def self.send(requests) + def self.list(requests) return [] if requests.empty? projects = ColaboraProject.send @@ -37,4 +39,29 @@ def self.send(requests) end end end + + class ColaBoraInvitationRequestPost + def self.send(invitation_request) + @invitation_request = invitation_request + post_connection + + @response + end + + class << self + private + + def build_invitation_request_params(invitation_request) + { 'proposal': { 'invitation_request_id': invitation_request.id, 'email': invitation_request.profile.email, + 'message': invitation_request.message, 'profile_id': invitation_request.profile.id, + 'project_id': invitation_request.project_id } }.as_json + end + + def post_connection + url = "#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROPOSALS_URL}" + headers = { 'Content-Type': 'application/json' } + @response = Faraday.post(url, build_invitation_request_params(@invitation_request), headers) + end + end + end end diff --git a/spec/jobs/request_invitation_job_spec.rb b/spec/jobs/request_invitation_job_spec.rb index d72a645..7b97c16 100644 --- a/spec/jobs/request_invitation_job_spec.rb +++ b/spec/jobs/request_invitation_job_spec.rb @@ -3,11 +3,7 @@ RSpec.describe RequestInvitationJob, type: :job do it 'altera a solicitação de convite para pending caso receba uma confirmação de sucesso do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, - project_id: invitation_request.project_id, - profile_id: invitation_request.profile.id, - email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + invitation_request_params = { invitation_request_id: invitation_request.id }.as_json json_proposal_response = File.read(Rails.root.join('./spec/support/json/proposal_201.json')) fake_portfoliorrr_response = double('faraday_response', status: :ok, body: json_proposal_response) @@ -30,11 +26,7 @@ it 'enfileira um novo job caso receba um aviso de erro no servidor do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, - project_id: invitation_request.project_id, - profile_id: invitation_request.profile.id, - email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + invitation_request_params = { invitation_request_id: invitation_request.id }.as_json fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body) @@ -57,11 +49,7 @@ it 'altera a solicitação de convite para error caso receba um aviso de erro do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, - project_id: invitation_request.project_id, - profile_id: invitation_request.profile.id, - email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + invitation_request_params = { invitation_request_id: invitation_request.id }.as_json fake_colabora_response_body = { 'errors': ['Usuário já faz parte deste projeto'] }.as_json fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body) @@ -84,11 +72,7 @@ it 'altera a solicitação de convite para aborted se receber pela quinta vez um erro da API do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, - project_id: invitation_request.project_id, - profile_id: invitation_request.profile.id, - email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + invitation_request_params = { invitation_request_id: invitation_request.id }.as_json fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json fake_portfoliorrr_response = double('faraday_response', status: :ok, body: fake_colabora_response_body) @@ -114,11 +98,7 @@ it 'gera uma nova tentativa caso a API do Portfoliorrr esteja fora do ar, sem limite de tentativas' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, - project_id: invitation_request.project_id, - profile_id: invitation_request.profile.id, - email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + invitation_request_params = { invitation_request_id: invitation_request.id }.as_json fake_response_body = { 'error': 'Houve um erro interno no servidor ao processar sua solicitação.' }.as_json fake_portfoliorrr_response = double('faraday_response', status: :internal_server_error, body: fake_response_body) diff --git a/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb b/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb index c02a437..d5d6d47 100644 --- a/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb +++ b/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb @@ -4,25 +4,20 @@ context 'GET /api/v1/projects/request_invitation' do it 'com sucesso e recebe confirmação da criação de proposal' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id.to_s, - project_id: invitation_request.project_id.to_s, - profile_id: invitation_request.profile.id.to_s, + invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + message: invitation_request.message, + profile_id: invitation_request.profile.id, + project_id: invitation_request.project_id } } }.as_json json_proposal_response = File.read(Rails.root.join('./spec/support/json/proposal_201.json')) fake_colabora_response = double('faraday_response', status: 201, body: json_proposal_response) - colabora_api_connection = double('Faraday::Connection', post: fake_colabora_response) - allow(Faraday).to receive(:new) - .with(url: 'http://localhost:3000', params: invitation_request_params['data']) - .and_return(colabora_api_connection) - allow(colabora_api_connection) - .to receive(:post) - .with('/api/v1/proposals') - .and_return(fake_colabora_response) - - get '/api/v1/projects/request_invitation', params: invitation_request_params + url = 'http://localhost:3000/api/v1/proposals' + headers = { 'Content-Type': 'application/json' } + allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + .and_return(fake_colabora_response) + get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json expect(response).to have_http_status :ok expect(response.content_type).to include 'application/json' json_response = JSON.parse(response.body) @@ -32,24 +27,20 @@ it 'com sucesso, mas recebe alerta de erro 404 do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id.to_s, - project_id: invitation_request.project_id.to_s, - profile_id: invitation_request.profile.id.to_s, + invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + message: invitation_request.message, + profile_id: invitation_request.profile.id, + project_id: invitation_request.project_id } } }.as_json + url = 'http://localhost:3000/api/v1/proposals' + headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Projeto não encontrado'] }.as_json fake_colabora_response = double('faraday_response', status: 404, body: fake_colabora_response_body) - colabora_api_connection = double('Faraday::Connection', post: fake_colabora_response) - allow(Faraday).to receive(:new) - .with(url: 'http://localhost:3000', params: invitation_request_params['data']) - .and_return(colabora_api_connection) - allow(colabora_api_connection) - .to receive(:post) - .with('/api/v1/proposals') - .and_return(fake_colabora_response) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + .and_return(fake_colabora_response) - get '/api/v1/projects/request_invitation', params: invitation_request_params + get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json expect(response).to have_http_status :ok expect(response.content_type).to include 'application/json' @@ -60,24 +51,20 @@ it 'com sucesso, mas recebe alerta de erro 409 do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id.to_s, - project_id: invitation_request.project_id.to_s, - profile_id: invitation_request.profile.id.to_s, + invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + message: invitation_request.message, + profile_id: invitation_request.profile.id, + project_id: invitation_request.project_id } } }.as_json + url = 'http://localhost:3000/api/v1/proposals' + headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Usuário já faz parte deste projeto'] }.as_json fake_colabora_response = double('faraday_response', status: 409, body: fake_colabora_response_body) - colabora_api_connection = double('Faraday::Connection', post: fake_colabora_response) - allow(Faraday).to receive(:new) - .with(url: 'http://localhost:3000', params: invitation_request_params['data']) - .and_return(colabora_api_connection) - allow(colabora_api_connection) - .to receive(:post) - .with('/api/v1/proposals') - .and_return(fake_colabora_response) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + .and_return(fake_colabora_response) - get '/api/v1/projects/request_invitation', params: invitation_request_params + get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json expect(response).to have_http_status :ok expect(response.content_type).to include 'application/json' @@ -88,24 +75,20 @@ it 'com sucesso, mas recebe alerta de erro 500 do Cola?Bora!' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id.to_s, - project_id: invitation_request.project_id.to_s, - profile_id: invitation_request.profile.id.to_s, + invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + message: invitation_request.message, + profile_id: invitation_request.profile.id, + project_id: invitation_request.project_id } } }.as_json + url = 'http://localhost:3000/api/v1/proposals' + headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json fake_colabora_response = double('faraday_response', status: 500, body: fake_colabora_response_body) - colabora_api_connection = double('Faraday::Connection', post: fake_colabora_response) - allow(Faraday).to receive(:new) - .with(url: 'http://localhost:3000', params: invitation_request_params['data']) - .and_return(colabora_api_connection) - allow(colabora_api_connection) - .to receive(:post) - .with('/api/v1/proposals') - .and_return(fake_colabora_response) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + .and_return(fake_colabora_response) - get '/api/v1/projects/request_invitation', params: invitation_request_params + get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json expect(response).to have_http_status :ok expect(response.content_type).to include 'application/json' @@ -116,17 +99,18 @@ it 'e retorna erro interno do servidor no Portfoliorrr' do invitation_request = create(:invitation_request) - invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id.to_s, - project_id: invitation_request.project_id.to_s, - profile_id: invitation_request.profile.id.to_s, + invitation_request_params = { data: { proposal: { invitation_request_id: invitation_request.id, email: invitation_request.profile.email, - message: invitation_request.message } } }.as_json + message: invitation_request.message, + profile_id: invitation_request.profile.id, + project_id: invitation_request.project_id } } }.as_json - allow(Faraday).to receive(:new) - .with(url: 'http://localhost:3000', params: invitation_request_params['data']) - .and_raise(ActiveRecord::ConnectionNotEstablished) + url = 'http://localhost:3000/api/v1/proposals' + headers = { 'Content-Type': 'application/json' } + allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + .and_raise(ActiveRecord::ConnectionNotEstablished) - get '/api/v1/projects/request_invitation', params: invitation_request_params + get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json expect(response).to have_http_status :internal_server_error json_response = JSON.parse(response.body) diff --git a/spec/services/invitation_request_service/invitation_request_spec.rb b/spec/services/invitation_request_service/invitation_request_spec.rb index 3be1788..2541f16 100644 --- a/spec/services/invitation_request_service/invitation_request_spec.rb +++ b/spec/services/invitation_request_service/invitation_request_spec.rb @@ -1,7 +1,7 @@ require 'rails_helper' RSpec.describe InvitationRequestService::InvitationRequest do - context '.send' do + context '.list' do it 'retorna array de objetos com informações completas do convite' do user = create(:user) @@ -22,7 +22,7 @@ allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - result = InvitationRequestService::InvitationRequest.send(requests) + result = InvitationRequestService::InvitationRequest.list(requests) expect(result.class).to eq Array expect(result.count).to eq 2 @@ -46,7 +46,7 @@ it 'retorna um array vazio quando não há solicitações de convite' do requests = [] - result = InvitationRequestService::InvitationRequest.send(requests) + result = InvitationRequestService::InvitationRequest.list(requests) expect(result.class).to eq Array expect(result).to be_empty From a46808cd51a55836fe93137ea4ae3972489c75d6 Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 09:02:59 -0300 Subject: [PATCH 08/27] Adiciona Gem Co-authored-by: Paulo Henrique --- Gemfile | 1 + Gemfile.lock | 3 + config/initializers/friendly_id.rb | 107 ++++++++++++++++++ .../20240215115659_add_slug_to_profiles.rb | 6 + ...20240215115707_create_friendly_id_slugs.rb | 21 ++++ db/schema.rb | 15 ++- 6 files changed, 152 insertions(+), 1 deletion(-) create mode 100644 config/initializers/friendly_id.rb create mode 100644 db/migrate/20240215115659_add_slug_to_profiles.rb create mode 100644 db/migrate/20240215115707_create_friendly_id_slugs.rb diff --git a/Gemfile b/Gemfile index 2ae20f8..e1c00d5 100644 --- a/Gemfile +++ b/Gemfile @@ -13,6 +13,7 @@ gem 'devise' gem 'faker' gem 'faraday' +gem 'friendly_id', '~> 5.5.0' gem 'image_processing', '>= 1.2' gem 'jbuilder' gem 'jsbundling-rails' diff --git a/Gemfile.lock b/Gemfile.lock index 3de4bb0..c4cb9c9 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -136,6 +136,8 @@ GEM webrick (~> 1.7) websocket-driver (>= 0.6, < 0.8) ffi (1.16.3) + friendly_id (5.5.1) + activerecord (>= 4.0.0) globalid (1.2.1) activesupport (>= 6.1) i18n (1.14.1) @@ -339,6 +341,7 @@ DEPENDENCIES factory_bot_rails faker faraday + friendly_id (~> 5.5.0) image_processing (>= 1.2) jbuilder jsbundling-rails diff --git a/config/initializers/friendly_id.rb b/config/initializers/friendly_id.rb new file mode 100644 index 0000000..5852b58 --- /dev/null +++ b/config/initializers/friendly_id.rb @@ -0,0 +1,107 @@ +# FriendlyId Global Configuration +# +# Use this to set up shared configuration options for your entire application. +# Any of the configuration options shown here can also be applied to single +# models by passing arguments to the `friendly_id` class method or defining +# methods in your model. +# +# To learn more, check out the guide: +# +# http://norman.github.io/friendly_id/file.Guide.html + +FriendlyId.defaults do |config| + # ## Reserved Words + # + # Some words could conflict with Rails's routes when used as slugs, or are + # undesirable to allow as slugs. Edit this list as needed for your app. + config.use :reserved + + config.reserved_words = %w[new edit index session login logout users admin + stylesheets assets javascripts images] + + # This adds an option to treat reserved words as conflicts rather than exceptions. + # When there is no good candidate, a UUID will be appended, matching the existing + # conflict behavior. + + # config.treat_reserved_as_conflict = true + + # ## Friendly Finders + # + # Uncomment this to use friendly finders in all models. By default, if + # you wish to find a record by its friendly id, you must do: + # + # MyModel.friendly.find('foo') + # + # If you uncomment this, you can do: + # + # MyModel.find('foo') + # + # This is significantly more convenient but may not be appropriate for + # all applications, so you must explicitly opt-in to this behavior. You can + # always also configure it on a per-model basis if you prefer. + # + # Something else to consider is that using the :finders addon boosts + # performance because it will avoid Rails-internal code that makes runtime + # calls to `Module.extend`. + # + # config.use :finders + # + # ## Slugs + # + # Most applications will use the :slugged module everywhere. If you wish + # to do so, uncomment the following line. + # + # config.use :slugged + # + # By default, FriendlyId's :slugged addon expects the slug column to be named + # 'slug', but you can change it if you wish. + # + # config.slug_column = 'slug' + # + # By default, slug has no size limit, but you can change it if you wish. + # + # config.slug_limit = 255 + # + # When FriendlyId can not generate a unique ID from your base method, it appends + # a UUID, separated by a single dash. You can configure the character used as the + # separator. If you're upgrading from FriendlyId 4, you may wish to replace this + # with two dashes. + # + # config.sequence_separator = '-' + # + # Note that you must use the :slugged addon **prior** to the line which + # configures the sequence separator, or else FriendlyId will raise an undefined + # method error. + # + # ## Tips and Tricks + # + # ### Controlling when slugs are generated + # + # As of FriendlyId 5.0, new slugs are generated only when the slug field is + # nil, but if you're using a column as your base method can change this + # behavior by overriding the `should_generate_new_friendly_id?` method that + # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave + # more like 4.0. + # Note: Use(include) Slugged module in the config if using the anonymous module. + # If you have `friendly_id :name, use: slugged` in the model, Slugged module + # is included after the anonymous module defined in the initializer, so it + # overrides the `should_generate_new_friendly_id?` method from the anonymous module. + # + # config.use :slugged + # config.use Module.new { + # def should_generate_new_friendly_id? + # slug.blank? || _changed? + # end + # } + # + # FriendlyId uses Rails's `parameterize` method to generate slugs, but for + # languages that don't use the Roman alphabet, that's not usually sufficient. + # Here we use the Babosa library to transliterate Russian Cyrillic slugs to + # ASCII. If you use this, don't forget to add "babosa" to your Gemfile. + # + # config.use Module.new { + # def normalize_friendly_id(text) + # text.to_slug.normalize! :transliterations => [:russian, :latin] + # end + # } +end diff --git a/db/migrate/20240215115659_add_slug_to_profiles.rb b/db/migrate/20240215115659_add_slug_to_profiles.rb new file mode 100644 index 0000000..e8983ab --- /dev/null +++ b/db/migrate/20240215115659_add_slug_to_profiles.rb @@ -0,0 +1,6 @@ +class AddSlugToProfiles < ActiveRecord::Migration[7.1] + def change + add_column :profiles, :slug, :string + add_index :profiles, :slug, unique: true + end +end diff --git a/db/migrate/20240215115707_create_friendly_id_slugs.rb b/db/migrate/20240215115707_create_friendly_id_slugs.rb new file mode 100644 index 0000000..a09491d --- /dev/null +++ b/db/migrate/20240215115707_create_friendly_id_slugs.rb @@ -0,0 +1,21 @@ +MIGRATION_CLASS = + if ActiveRecord::VERSION::MAJOR >= 5 + ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"] + else + ActiveRecord::Migration + end + +class CreateFriendlyIdSlugs < MIGRATION_CLASS + def change + create_table :friendly_id_slugs do |t| + t.string :slug, null: false + t.integer :sluggable_id, null: false + t.string :sluggable_type, limit: 50 + t.string :scope + t.datetime :created_at + end + add_index :friendly_id_slugs, [:sluggable_type, :sluggable_id] + add_index :friendly_id_slugs, [:slug, :sluggable_type], length: {slug: 140, sluggable_type: 50} + add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], length: {slug: 70, sluggable_type: 50, scope: 70}, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 1e32535..7712822 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.1].define(version: 2024_02_14_151256) do +ActiveRecord::Schema[7.1].define(version: 2024_02_15_115707) do create_table "action_text_rich_texts", force: :cascade do |t| t.string "name", null: false t.text "body" @@ -84,6 +84,17 @@ t.index ["profile_id"], name: "index_education_infos_on_profile_id" end + create_table "friendly_id_slugs", force: :cascade do |t| + t.string "slug", null: false + t.integer "sluggable_id", null: false + t.string "sluggable_type", limit: 50 + t.string "scope" + t.datetime "created_at" + t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true + t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type" + t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id" + end + create_table "invitation_requests", force: :cascade do |t| t.integer "profile_id", null: false t.text "message" @@ -203,6 +214,8 @@ t.integer "privacy", default: 10 t.integer "status", default: 5 t.boolean "removed", default: false + t.string "slug" + t.index ["slug"], name: "index_profiles_on_slug", unique: true t.index ["user_id"], name: "index_profiles_on_user_id" end From bcf0f1e755a0f5c48315b6787a05d7ff1f42aa0a Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 10:31:13 -0300 Subject: [PATCH 09/27] Adiciona gem ao Profile Corrige testes Co-authored-by: Rosemilson Barbosa Co-authored-by: Lucas Vasques --- app/controllers/connections_controller.rb | 2 +- app/controllers/profiles_controller.rb | 2 +- app/controllers/reports_controller.rb | 2 +- app/controllers/settings_controller.rb | 2 +- app/mailers/invitations_mailer.rb | 2 +- app/models/profile.rb | 7 +++++++ spec/system/authentication/visitor_logs_in_spec.rb | 2 +- .../connections/user_follows_another_user_spec.rb | 6 +++--- .../connections/user_unfollows_another_user_spec.rb | 2 +- spec/system/connections/user_views_followers_spec.rb | 2 +- .../connections/user_views_following_users_spec.rb | 2 +- .../education_info/user_creates_education_info_spec.rb | 2 +- .../education_info/user_edits_education_info_spec.rb | 2 +- spec/system/invitations/user_views_invitations_spec.rb | 4 ++-- .../job_categories/admin_create_job_category_spec.rb | 2 +- .../user_sees_new_follower_notification_spec.rb | 2 +- .../personal_info/user_edits_personal_info_spec.rb | 2 +- spec/system/posts/user_creates_post_spec.rb | 2 +- spec/system/posts/user_edits_post_spec.rb | 10 +++++----- spec/system/posts/user_views_post_list_spec.rb | 6 +++--- spec/system/posts/visitor_views_post_spec.rb | 2 +- .../user_creates_professional_info_spec.rb | 4 ++-- .../user_edits_professional_info_spec.rb | 4 ++-- spec/system/profile/user_views_profile_spec.rb | 2 +- .../reports/admin_sees_reports_listing_page_spec.rb | 2 +- spec/system/reports/user_report_spec.rb | 4 ++-- spec/system/searches/user_searches_post_by_tag_spec.rb | 6 +++--- spec/system/searches/user_searches_spec.rb | 2 +- .../system/searches/users_searchs_others_users_spec.rb | 2 +- .../settings/user_changes_profile_to_private_spec.rb | 2 +- 30 files changed, 50 insertions(+), 43 deletions(-) diff --git a/app/controllers/connections_controller.rb b/app/controllers/connections_controller.rb index 94979c4..62b4796 100644 --- a/app/controllers/connections_controller.rb +++ b/app/controllers/connections_controller.rb @@ -48,6 +48,6 @@ def set_connection_and_profile end def set_profile - @profile = Profile.find params[:profile_id] + @profile = Profile.friendly.find params[:profile_id] end end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index cb98688..3ae500c 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -50,7 +50,7 @@ def redirect_unauthorized_access end def set_profile_and_posts - @profile = Profile.find(params[:id]) + @profile = Profile.friendly.find(params[:id]) @posts = current_user == @profile.user ? @profile.posts : @profile.posts.published end diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index 1407fce..ee27b61 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -49,7 +49,7 @@ def remove_profile def set_reportable_for_new reportable_id = params[:reportable] @reportable = Post.find(reportable_id) if params[:reportable_type] == 'Post' - @reportable = Profile.find(reportable_id) if params[:reportable_type] == 'Profile' + @reportable = Profile.friendly.find(reportable_id) if params[:reportable_type] == 'Profile' @reportable = Comment.find(reportable_id) if params[:reportable_type] == 'Comment' @reportable = Reply.find(reportable_id) if params[:reportable_type] == 'Reply' end diff --git a/app/controllers/settings_controller.rb b/app/controllers/settings_controller.rb index fde87ca..d7675e7 100644 --- a/app/controllers/settings_controller.rb +++ b/app/controllers/settings_controller.rb @@ -40,7 +40,7 @@ def open_to_work private def redirect_unauthorized_access - @profile = Profile.find(params[:profile_id]) + @profile = Profile.friendly.find(params[:profile_id]) return if current_user == @profile.user redirect_to root_path, alert: t('alerts.unauthorized') diff --git a/app/mailers/invitations_mailer.rb b/app/mailers/invitations_mailer.rb index 1e1e480..be95dc1 100644 --- a/app/mailers/invitations_mailer.rb +++ b/app/mailers/invitations_mailer.rb @@ -1,6 +1,6 @@ class InvitationsMailer < ApplicationMailer def received_invitation - profile = Profile.find(params[:profile_id]) + profile = Profile.friendly.find(params[:profile_id]) project_title = params[:project_title] mail(subject: t('.subject'), to: profile.user.email, body: t('.body', title: project_title)) diff --git a/app/models/profile.rb b/app/models/profile.rb index 663de5e..a395890 100644 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -38,8 +38,15 @@ class Profile < ApplicationRecord enum privacy: { private_profile: 0, public_profile: 10 } enum status: { inactive: 0, active: 5 } + extend FriendlyId + friendly_id :profile_permalink, use: :slugged + delegate :full_name, :email, to: :user + def profile_permalink + user.full_name.to_s + end + def self.advanced_search(search_query) left_outer_joins(:job_categories, :personal_info, :user).where( 'job_categories.name LIKE :term OR diff --git a/spec/system/authentication/visitor_logs_in_spec.rb b/spec/system/authentication/visitor_logs_in_spec.rb index 08d533f..75eeec6 100644 --- a/spec/system/authentication/visitor_logs_in_spec.rb +++ b/spec/system/authentication/visitor_logs_in_spec.rb @@ -59,7 +59,7 @@ click_button class: 'dropdown-toggle' click_on 'Sair' - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Logout efetuado com sucesso' end diff --git a/spec/system/connections/user_follows_another_user_spec.rb b/spec/system/connections/user_follows_another_user_spec.rb index abdea9e..611217c 100644 --- a/spec/system/connections/user_follows_another_user_spec.rb +++ b/spec/system/connections/user_follows_another_user_spec.rb @@ -17,7 +17,7 @@ expect(mail).to have_received(:deliver_later) expect(Connection.count).to eq 1 - expect(current_path).to eq profile_path(followed) + expect(page).to have_current_path profile_path(followed) expect(page).to have_content('Agora você está seguindo Eliseu Ramos') expect(page).not_to have_button('Seguir', exact: true) expect(page).to have_button('Deixar de Seguir', exact: true) @@ -28,7 +28,7 @@ visit profile_path(followed.profile) - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path expect(page).to have_content 'Para continuar, faça login ou registre-se.' end @@ -43,7 +43,7 @@ click_on 'Seguir' follower_relationship = Connection.last - expect(current_path).to eq profile_path(followed.profile) + expect(page).to have_current_path profile_path(followed.profile) expect(follower_relationship).to be_active expect(page).to have_content('Agora você está seguindo Eliseu Ramos') expect(page).to have_button('Deixar de Seguir', exact: true) diff --git a/spec/system/connections/user_unfollows_another_user_spec.rb b/spec/system/connections/user_unfollows_another_user_spec.rb index 445afbd..bac86ea 100644 --- a/spec/system/connections/user_unfollows_another_user_spec.rb +++ b/spec/system/connections/user_unfollows_another_user_spec.rb @@ -12,7 +12,7 @@ click_on 'Deixar de Seguir' follower_relationship = Connection.last - expect(current_path).to eq profile_path(followed.profile) + expect(page).to have_current_path profile_path(followed.profile) expect(follower_relationship).to be_inactive expect(page).to have_content("Você deixou de seguir #{followed.full_name}") expect(page).to have_button('Seguir', exact: true) diff --git a/spec/system/connections/user_views_followers_spec.rb b/spec/system/connections/user_views_followers_spec.rb index 223e4fd..61c6c57 100644 --- a/spec/system/connections/user_views_followers_spec.rb +++ b/spec/system/connections/user_views_followers_spec.rb @@ -47,7 +47,7 @@ visit profile_following_path(user.profile) - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path end end end diff --git a/spec/system/connections/user_views_following_users_spec.rb b/spec/system/connections/user_views_following_users_spec.rb index d21543f..909084e 100644 --- a/spec/system/connections/user_views_following_users_spec.rb +++ b/spec/system/connections/user_views_following_users_spec.rb @@ -47,6 +47,6 @@ visit profile_connections_path(user.profile) - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path end end diff --git a/spec/system/education_info/user_creates_education_info_spec.rb b/spec/system/education_info/user_creates_education_info_spec.rb index 005fa91..fbb60ba 100644 --- a/spec/system/education_info/user_creates_education_info_spec.rb +++ b/spec/system/education_info/user_creates_education_info_spec.rb @@ -62,7 +62,7 @@ check 'Exibir no Perfil' click_on 'Salvar' - expect(current_path).to eq new_user_profile_education_info_path + expect(page).to have_current_path new_user_profile_education_info_path expect(page).to have_content 'Não foi possível cadastrar formação acadêmica' expect(page).to have_content 'Instituição não pode ficar em branco' expect(page).to have_content 'Curso não pode ficar em branco' diff --git a/spec/system/education_info/user_edits_education_info_spec.rb b/spec/system/education_info/user_edits_education_info_spec.rb index 1dc92fc..d6f381a 100644 --- a/spec/system/education_info/user_edits_education_info_spec.rb +++ b/spec/system/education_info/user_edits_education_info_spec.rb @@ -38,7 +38,7 @@ check 'Exibir no Perfil' click_on 'Salvar' - expect(current_path).to eq edit_education_info_path(education_info) + expect(page).to have_current_path edit_education_info_path(education_info) expect(page).to have_content 'Não foi possível atualizar formação acadêmica' expect(page).to have_content 'Instituição não pode ficar em branco' expect(page).to have_content 'Curso não pode ficar em branco' diff --git a/spec/system/invitations/user_views_invitations_spec.rb b/spec/system/invitations/user_views_invitations_spec.rb index dab5e0b..770f2f5 100644 --- a/spec/system/invitations/user_views_invitations_spec.rb +++ b/spec/system/invitations/user_views_invitations_spec.rb @@ -13,7 +13,7 @@ click_on 'Convites' end - expect(current_path).to eq invitations_path + expect(page).to have_current_path invitations_path expect(page).to have_content 'Projeto Cola?Bora!' expect(page).to have_content 'Um projeto muito legal' expect(page).to have_content "Expira dia: #{I18n.l(invitation.expiration_date, format: :default)}" @@ -134,6 +134,6 @@ it 'mas precisa estar logado' do visit invitations_path - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path end end diff --git a/spec/system/job_categories/admin_create_job_category_spec.rb b/spec/system/job_categories/admin_create_job_category_spec.rb index e95af39..2665fbe 100644 --- a/spec/system/job_categories/admin_create_job_category_spec.rb +++ b/spec/system/job_categories/admin_create_job_category_spec.rb @@ -17,7 +17,7 @@ it 'e deve estar logado' do visit job_categories_path - expect(current_path).to eq(new_user_session_path) + expect(page).to have_current_path(new_user_session_path) expect(page).to have_content('Para continuar, faça login ou registre-se.') end diff --git a/spec/system/notifications/user_sees_new_follower_notification_spec.rb b/spec/system/notifications/user_sees_new_follower_notification_spec.rb index 2e78d64..72b6dd8 100644 --- a/spec/system/notifications/user_sees_new_follower_notification_spec.rb +++ b/spec/system/notifications/user_sees_new_follower_notification_spec.rb @@ -22,7 +22,7 @@ visit notifications_path click_on 'Paulo começou a seguir você' - expect(page).to have_current_path profile_path(follower) + expect(page).to have_current_path profile_path(follower.profile.slug) expect(Notification.last).to be_clicked end end diff --git a/spec/system/personal_info/user_edits_personal_info_spec.rb b/spec/system/personal_info/user_edits_personal_info_spec.rb index c85269a..c12f841 100644 --- a/spec/system/personal_info/user_edits_personal_info_spec.rb +++ b/spec/system/personal_info/user_edits_personal_info_spec.rb @@ -78,7 +78,7 @@ it 'e é redirecionado para a tela de login' do visit edit_user_profile_path - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path expect(page).to have_content 'Para continuar, faça login ou registre-se' end end diff --git a/spec/system/posts/user_creates_post_spec.rb b/spec/system/posts/user_creates_post_spec.rb index cd0bb75..9734651 100644 --- a/spec/system/posts/user_creates_post_spec.rb +++ b/spec/system/posts/user_creates_post_spec.rb @@ -4,7 +4,7 @@ it 'apenas quando autenticado' do visit new_post_path - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path end it 'com sucesso' do diff --git a/spec/system/posts/user_edits_post_spec.rb b/spec/system/posts/user_edits_post_spec.rb index f2deff6..425c55b 100644 --- a/spec/system/posts/user_edits_post_spec.rb +++ b/spec/system/posts/user_edits_post_spec.rb @@ -37,7 +37,7 @@ login_as user visit edit_post_path(post) - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Você não pode acessar este conteúdo ou realizar esta ação' end @@ -70,7 +70,7 @@ post = create(:post, user:, title: 'Post A', content: 'Primeira postagem') login_as user - visit profile_path(user) + visit profile_path(user.profile.slug) within "div#post-#{post.id}" do click_button id: 'pin' end @@ -91,7 +91,7 @@ post = create(:post, user:, title: 'Post A', content: 'Primeira postagem', pin: 'pinned') login_as user - visit profile_path(user) + visit profile_path(user.profile.slug) within 'div#fixed' do click_button id: 'unpin' end @@ -111,7 +111,7 @@ post2 = create(:post, user:, title: 'Post B', content: 'Segunda postagem') login_as user - visit profile_path(user) + visit profile_path(user.profile.slug) within "div#post-#{post.id}" do click_button id: 'pin' end @@ -134,7 +134,7 @@ other_user = create(:user, citizen_id_number: '61328427056', email: 'visitor@email.com') login_as other_user - visit profile_path(user) + visit profile_path(user.profile.slug) expect(page).not_to have_content 'Fixar' expect(page).not_to have_content 'Desafixar' diff --git a/spec/system/posts/user_views_post_list_spec.rb b/spec/system/posts/user_views_post_list_spec.rb index c5eed89..15659ae 100644 --- a/spec/system/posts/user_views_post_list_spec.rb +++ b/spec/system/posts/user_views_post_list_spec.rb @@ -13,7 +13,7 @@ click_on 'Pesquisar' click_on user.full_name - expect(page).to have_current_path(profile_path(user)) + expect(page).to have_current_path(profile_path(user.profile.slug)) within 'h2#post-list-title' do expect(page).to have_content('Publicações') end @@ -39,7 +39,7 @@ published_at: 2.days.from_now) login_as user - visit profile_path(user) + visit profile_path(user.profile.slug) expect(page).to have_content 'Há 2 dias' end @@ -56,7 +56,7 @@ create(:post, user:, title: 'Conteúdo C', content: 'Primeira postagem') login_as user - visit profile_path(user) + visit profile_path(user.profile.slug) expect(page.body.index('Conteúdo C')).to be < page.body.index('Texto B') expect(page.body.index('Texto B')).to be < page.body.index('Post A') diff --git a/spec/system/posts/visitor_views_post_spec.rb b/spec/system/posts/visitor_views_post_spec.rb index 23aa44f..df5c740 100644 --- a/spec/system/posts/visitor_views_post_spec.rb +++ b/spec/system/posts/visitor_views_post_spec.rb @@ -6,7 +6,7 @@ visit post_path(post) - expect(current_path).to eq post_path(post) + expect(page).to have_current_path post_path(post) expect(page).to have_content 'Título do post' expect(page).to have_content 'Conteúdo do post' expect(page).to have_link "Criado por #{post.user.full_name}", href: profile_path(post.user.profile) diff --git a/spec/system/professional_info/user_creates_professional_info_spec.rb b/spec/system/professional_info/user_creates_professional_info_spec.rb index 24bb8cc..49c1463 100644 --- a/spec/system/professional_info/user_creates_professional_info_spec.rb +++ b/spec/system/professional_info/user_creates_professional_info_spec.rb @@ -42,7 +42,7 @@ click_on 'Salvar' - expect(current_path).to eq new_user_profile_professional_info_path + expect(page).to have_current_path new_user_profile_professional_info_path expect(page).to have_content 'Não foi possível cadastrar experiência profissional' expect(page).to have_content 'Empresa não pode ficar em branco' @@ -67,7 +67,7 @@ click_on 'Salvar' - expect(current_path).to eq new_user_profile_professional_info_path + expect(page).to have_current_path new_user_profile_professional_info_path expect(page).to have_content 'Não foi possível cadastrar experiência profissional' expect(page).to have_content 'Empresa não pode ficar em branco' diff --git a/spec/system/professional_info/user_edits_professional_info_spec.rb b/spec/system/professional_info/user_edits_professional_info_spec.rb index d7db6b6..a72097b 100644 --- a/spec/system/professional_info/user_edits_professional_info_spec.rb +++ b/spec/system/professional_info/user_edits_professional_info_spec.rb @@ -47,7 +47,7 @@ click_on 'Salvar' - expect(current_path).to eq edit_professional_info_path(professional_info) + expect(page).to have_current_path edit_professional_info_path(professional_info) expect(page).to have_content 'Não foi possível atualizar experiência profissional' expect(page).to have_content 'Empresa não pode ficar em branco' @@ -93,7 +93,7 @@ visit edit_professional_info_path(professional_info_user1) - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Não foi possível completar sua ação' end end diff --git a/spec/system/profile/user_views_profile_spec.rb b/spec/system/profile/user_views_profile_spec.rb index d7cc611..2b2b8fb 100644 --- a/spec/system/profile/user_views_profile_spec.rb +++ b/spec/system/profile/user_views_profile_spec.rb @@ -91,7 +91,7 @@ it 'e é redirecionado para a página de login' do user = create(:user) visit profile_path(user.profile) - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path expect(page).to have_content 'Para continuar, faça login ou registre-se' end end diff --git a/spec/system/reports/admin_sees_reports_listing_page_spec.rb b/spec/system/reports/admin_sees_reports_listing_page_spec.rb index 8fd5b7b..2dfff00 100644 --- a/spec/system/reports/admin_sees_reports_listing_page_spec.rb +++ b/spec/system/reports/admin_sees_reports_listing_page_spec.rb @@ -94,7 +94,7 @@ login_as user visit reports_path - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Você não têm permissão para realizar essa ação.' end end diff --git a/spec/system/reports/user_report_spec.rb b/spec/system/reports/user_report_spec.rb index 0c1dc3d..e7b70ff 100644 --- a/spec/system/reports/user_report_spec.rb +++ b/spec/system/reports/user_report_spec.rb @@ -30,7 +30,7 @@ login_as user visit new_report_path params: { reportable: post, reportable_type: post.class.name } - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Essa publicação não está disponível.' end @@ -205,7 +205,7 @@ visit new_report_path params: { reportable: post, reportable_type: post.class.name } - expect(current_path).to eq new_user_session_path + expect(page).to have_current_path new_user_session_path expect(page).to have_content 'Para continuar, faça login ou registre-se.' end end diff --git a/spec/system/searches/user_searches_post_by_tag_spec.rb b/spec/system/searches/user_searches_post_by_tag_spec.rb index 149e382..e6ea0db 100644 --- a/spec/system/searches/user_searches_post_by_tag_spec.rb +++ b/spec/system/searches/user_searches_post_by_tag_spec.rb @@ -13,10 +13,10 @@ click_on 'tdd' end - expect(current_path).to eq searches_path expect(page).to have_content post.title expect(page).to have_content another_post.title expect(page).not_to have_content other_post.title + expect(current_path).to eq searches_path end it 'ao buscar por uma hashtag no campo de busca da home' do @@ -30,11 +30,11 @@ fill_in 'Buscar', with: '#tdd' click_on 'Pesquisar' - expect(current_path).to eq searches_path expect(page).to have_content post.title expect(page).to have_content another_post.title expect(page).not_to have_content other_post.title expect(page).to have_content '2 Publicações com: #tdd' + expect(current_path).to eq searches_path end it 'deve ser uma busca exata' do @@ -48,10 +48,10 @@ fill_in 'Buscar', with: '#td' click_on 'Pesquisar' - expect(current_path).to eq searches_path expect(page).not_to have_content post.title expect(page).not_to have_content another_post.title expect(page).not_to have_content other_post.title expect(page).to have_content 'Nenhum resultado encontrado com: #td' + expect(current_path).to eq searches_path end end diff --git a/spec/system/searches/user_searches_spec.rb b/spec/system/searches/user_searches_spec.rb index 40daee1..08916e2 100644 --- a/spec/system/searches/user_searches_spec.rb +++ b/spec/system/searches/user_searches_spec.rb @@ -9,7 +9,7 @@ fill_in 'Buscar', with: '' click_on 'Pesquisar' - expect(current_path).to eq root_path + expect(page).to have_current_path root_path expect(page).to have_content 'Você precisa informar um termo para fazer a pesquisa' end end diff --git a/spec/system/searches/users_searchs_others_users_spec.rb b/spec/system/searches/users_searchs_others_users_spec.rb index ed346d7..6811761 100644 --- a/spec/system/searches/users_searchs_others_users_spec.rb +++ b/spec/system/searches/users_searchs_others_users_spec.rb @@ -15,7 +15,6 @@ fill_in 'Buscar', with: 'gErAl' click_on 'Pesquisar' - expect(current_path).to eq searches_path expect(page).to have_content('2 resultados para: gErAl') expect(page).not_to have_content 'Horácio Fernandes' expect(page).to have_link 'Geraldo José' @@ -26,6 +25,7 @@ within 'h2' do expect(page).to have_content 'Resultados da Pesquisa' end + expect(current_path).to eq searches_path end it 'e não encontra nenhum usuário' do diff --git a/spec/system/settings/user_changes_profile_to_private_spec.rb b/spec/system/settings/user_changes_profile_to_private_spec.rb index 43d11bb..b80b5bb 100644 --- a/spec/system/settings/user_changes_profile_to_private_spec.rb +++ b/spec/system/settings/user_changes_profile_to_private_spec.rb @@ -28,10 +28,10 @@ fill_in 'Buscar', with: 'C++' click_on 'Pesquisar' - expect(current_path).to eq searches_path expect(page).to have_content('1 resultado para: C++') expect(page).not_to have_content private_user.full_name expect(page).to have_content public_user.full_name + expect(current_path).to eq searches_path end it 'e dados aparecem aos seguidores' do From 30c3db8e45ccaa2722d163bf96fc7c0d45b559f4 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 10:56:51 -0300 Subject: [PATCH 10/27] =?UTF-8?q?Move=20classe=20ColaBoraProject=20para=20?= =?UTF-8?q?servi=C3=A7o=20de=20Projetos?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/services/invitation_request_service.rb | 27 +++---------------- app/services/projects_service.rb | 27 +++++++++++++++++++ .../colabora_project_spec.rb | 8 +++--- 3 files changed, 34 insertions(+), 28 deletions(-) create mode 100644 app/services/projects_service.rb diff --git a/app/services/invitation_request_service.rb b/app/services/invitation_request_service.rb index 1b34e8b..d1e19aa 100644 --- a/app/services/invitation_request_service.rb +++ b/app/services/invitation_request_service.rb @@ -1,37 +1,16 @@ module InvitationRequestService + include ProjectsService + COLABORA_BASE_URL = 'http://localhost:3000'.freeze COLABORA_API_V1_PROJECTS_URL = '/api/v1/projects'.freeze COLABORA_API_V1_PROPOSALS_URL = '/api/v1/proposals'.freeze COLABORA_API_V1_INVITATIONS_BASE_URL = '/api/v1/invitations'.freeze - class ColaboraProject - def self.send - @response = Faraday.get("#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}") - return build_projects if @response.success? - - raise StandardError - end - - class << self - private - - def build_projects - projects = JSON.parse(@response.body, symbolize_names: true) - projects.map do |project| - Project.new(id: project[:id], - title: project[:title], - description: project[:description], - category: project[:category]) - end - end - end - end - class InvitationRequest def self.list(requests) return [] if requests.empty? - projects = ColaboraProject.send + projects = ProjectsService::ColaBoraProject.send requests.map do |request| project = projects.find { |proj| proj.id == request.project_id } diff --git a/app/services/projects_service.rb b/app/services/projects_service.rb new file mode 100644 index 0000000..2a2302a --- /dev/null +++ b/app/services/projects_service.rb @@ -0,0 +1,27 @@ +module ProjectsService + COLABORA_BASE_URL = 'http://localhost:3000'.freeze + COLABORA_API_V1_PROJECTS_URL = '/api/v1/projects'.freeze + + class ColaBoraProject + def self.send + @response = Faraday.get("#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}") + return build_projects if @response.success? + + raise StandardError + end + + class << self + private + + def build_projects + projects = JSON.parse(@response.body, symbolize_names: true) + projects.map do |project| + Project.new(id: project[:id], + title: project[:title], + description: project[:description], + category: project[:category]) + end + end + end + end +end diff --git a/spec/services/invitation_request_service/colabora_project_spec.rb b/spec/services/invitation_request_service/colabora_project_spec.rb index 8dcab46..9ededc7 100644 --- a/spec/services/invitation_request_service/colabora_project_spec.rb +++ b/spec/services/invitation_request_service/colabora_project_spec.rb @@ -1,6 +1,6 @@ require 'rails_helper' -RSpec.describe InvitationRequestService::ColaboraProject do +RSpec.describe InvitationRequestService::ColaBoraProject do context '.send' do it 'retorna array de objetos do tipo Project' do json_data = File.read(Rails.root.join('./spec/support/json/projects.json')) @@ -20,9 +20,9 @@ category: 'Industrial') ] allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - allow(InvitationRequestService::ColaboraProject).to receive(:build_projects).and_return(projects) + allow(InvitationRequestService::ColaBoraProject).to receive(:build_projects).and_return(projects) - result = InvitationRequestService::ColaboraProject.send + result = InvitationRequestService::ColaBoraProject.send expect(result.class).to eq Array expect(result.count).to eq 4 @@ -33,7 +33,7 @@ fake_response = double('faraday_response', success?: false, status: :internal_server_error) allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - expect { InvitationRequestService::ColaboraProject.send }.to raise_error(StandardError) + expect { InvitationRequestService::ColaBoraProject.send }.to raise_error(StandardError) end end end From d876dd8e647cc5c0850016fdede1c0a1dd7ebf1d Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 11:04:07 -0300 Subject: [PATCH 11/27] =?UTF-8?q?Move=20requisi=C3=A7=C3=A3o=20GET=20local?= =?UTF-8?q?host:3000/api/v1/projects=20para=20ProjectsService?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/controllers/api/v1/projects_controller.rb | 2 +- app/services/projects_service.rb | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/app/controllers/api/v1/projects_controller.rb b/app/controllers/api/v1/projects_controller.rb index ad1929a..78d3064 100644 --- a/app/controllers/api/v1/projects_controller.rb +++ b/app/controllers/api/v1/projects_controller.rb @@ -2,7 +2,7 @@ module Api module V1 class ProjectsController < ApiController def index - response = Faraday.get('http://localhost:3000/api/v1/projects') + response = ProjectsService::ColaBoraApiGetProjects.send if response.status == 200 projects = JSON.parse(response.body) render status: :ok, json: projects.as_json diff --git a/app/services/projects_service.rb b/app/services/projects_service.rb index 2a2302a..68c8983 100644 --- a/app/services/projects_service.rb +++ b/app/services/projects_service.rb @@ -24,4 +24,13 @@ def build_projects end end end + + class ColaBoraApiGetProjects + def self.send + url = "#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}" + Faraday.get(url) + rescue Faraday::ConnectionFailed + raise Exceptions::ColaBoraAPIOffline + end + end end From 552f1743ea1ff48df8fe3c5292055367f9b0f4d9 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 11:33:25 -0300 Subject: [PATCH 12/27] =?UTF-8?q?Cria=20arquivo=20de=20configura=C3=A7?= =?UTF-8?q?=C3=A3o=20colabora=5Fapi=5Fv1.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Centraliza URL base do Cola?Bora! e urls de endpoints de API da aplicação para o arquivo de configuração, para tornar o código mais DRY e facilitar manutenção futura. --- app/services/invitation_request_service.rb | 7 +++---- app/services/projects_service.rb | 4 ++-- app/views/invitations/show.html.erb | 2 +- config/application.rb | 3 +++ config/colabora_api_v1.yml | 9 +++++++++ 5 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 config/colabora_api_v1.yml diff --git a/app/services/invitation_request_service.rb b/app/services/invitation_request_service.rb index d1e19aa..189842f 100644 --- a/app/services/invitation_request_service.rb +++ b/app/services/invitation_request_service.rb @@ -1,10 +1,9 @@ module InvitationRequestService include ProjectsService - COLABORA_BASE_URL = 'http://localhost:3000'.freeze - COLABORA_API_V1_PROJECTS_URL = '/api/v1/projects'.freeze - COLABORA_API_V1_PROPOSALS_URL = '/api/v1/proposals'.freeze - COLABORA_API_V1_INVITATIONS_BASE_URL = '/api/v1/invitations'.freeze + COLABORA_BASE_URL = Rails.configuration.colabora_api_v1.base_url + COLABORA_API_V1_PROJECTS_URL = Rails.configuration.colabora_api_v1.projects_url + COLABORA_API_V1_PROPOSALS_URL = Rails.configuration.colabora_api_v1.proposals_url class InvitationRequest def self.list(requests) diff --git a/app/services/projects_service.rb b/app/services/projects_service.rb index 68c8983..f08f7f0 100644 --- a/app/services/projects_service.rb +++ b/app/services/projects_service.rb @@ -1,6 +1,6 @@ module ProjectsService - COLABORA_BASE_URL = 'http://localhost:3000'.freeze - COLABORA_API_V1_PROJECTS_URL = '/api/v1/projects'.freeze + COLABORA_BASE_URL = Rails.configuration.colabora_api_v1.base_url + COLABORA_API_V1_PROJECTS_URL = Rails.configuration.colabora_api_v1.projects_url class ColaBoraProject def self.send diff --git a/app/views/invitations/show.html.erb b/app/views/invitations/show.html.erb index e6c2f0a..7ce9ebb 100644 --- a/app/views/invitations/show.html.erb +++ b/app/views/invitations/show.html.erb @@ -16,7 +16,7 @@ <% if @invitation.pending? %>
- <%= link_to t('accept_btn'), 'http://localhost:3000', class: 'btn btn-primary me-4' %> + <%= link_to t('accept_btn'), Rails.configuration.colabora_api_v1.base_url, class: 'btn btn-primary me-4' %>
<%= button_to t('decline_btn'), decline_invitation_path(@invitation), method: :patch, class: 'btn btn-secondary' %> diff --git a/config/application.rb b/config/application.rb index ff33ae3..48f9c55 100644 --- a/config/application.rb +++ b/config/application.rb @@ -38,5 +38,8 @@ class Application < Rails::Application # Don't generate system test files. config.generators.system_tests = nil + + # ColaBora API configurations + config.colabora_api_v1 = config_for(:colabora_api_v1) end end diff --git a/config/colabora_api_v1.yml b/config/colabora_api_v1.yml new file mode 100644 index 0000000..9168649 --- /dev/null +++ b/config/colabora_api_v1.yml @@ -0,0 +1,9 @@ +development: + base_url: 'http://localhost:3000' + projects_url: '/api/v1/projects' + proposals_url: '/api/v1/proposals' + +test: + base_url: 'http://localhost:3000' + projects_url: '/api/v1/projects' + proposals_url: '/api/v1/proposals' \ No newline at end of file From 039213f003deee086b9d83d231cbbd91f3903f64 Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 11:38:44 -0300 Subject: [PATCH 13/27] fix/conserta chamada de profile no report controller --- app/controllers/reports_controller.rb | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index ee27b61..d3f433d 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -48,10 +48,11 @@ def remove_profile def set_reportable_for_new reportable_id = params[:reportable] - @reportable = Post.find(reportable_id) if params[:reportable_type] == 'Post' - @reportable = Profile.friendly.find(reportable_id) if params[:reportable_type] == 'Profile' - @reportable = Comment.find(reportable_id) if params[:reportable_type] == 'Comment' - @reportable = Reply.find(reportable_id) if params[:reportable_type] == 'Reply' + reportable_type = params[:reportable_type] + @reportable = Post.find(reportable_id) if reportable_type == 'Post' + @reportable = Profile.friendly.find(reportable_id) if reportable_type == 'Profile' + @reportable = Comment.find(reportable_id) if reportable_type == 'Comment' + @reportable = Reply.find(reportable_id) if reportable_type == 'Reply' end def set_reportable_for_create From ba2d0b0252ad238f0198890abcb08a75c7a82ed4 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 11:46:05 -0300 Subject: [PATCH 14/27] =?UTF-8?q?Cria=20arquivo=20de=20configura=C3=A7?= =?UTF-8?q?=C3=A3o=20portfoliorrr=5Fapi=5Fv1.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Centraliza URL base do Portfoliorrr e urls de endpoints de API da aplicação para o arquivo de configuração, para tornar o código mais DRY e facilitar manutenção futura. --- app/jobs/decline_invitation_job.rb | 4 +++- app/jobs/request_invitation_job.rb | 4 +++- config/application.rb | 3 +++ config/portfoliorrr_api_v1.yml | 9 +++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) create mode 100644 config/portfoliorrr_api_v1.yml diff --git a/app/jobs/decline_invitation_job.rb b/app/jobs/decline_invitation_job.rb index 85d2149..7588ff9 100644 --- a/app/jobs/decline_invitation_job.rb +++ b/app/jobs/decline_invitation_job.rb @@ -1,10 +1,12 @@ class DeclineInvitationJob < ApplicationJob + PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url + PORTFOLIORRR_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.invitations_url retry_on Faraday::ConnectionFailed, Faraday::ServerError, wait: :polynomially_longer, attempts: 5 do |job| job.arguments.first.pending! end def perform(invitation) - url = "http://localhost:4000/api/v1/invitations/#{invitation.colabora_invitation_id}" + url = "#{PORTFOLIORRR_BASE_URL}#{PORTFOLIORRR_INVITATION_URL}#{invitation.colabora_invitation_id}" Faraday.new { |faraday| faraday.response :raise_error }.patch(url) invitation.declined! rescue Faraday::ResourceNotFound, Faraday::ConflictError diff --git a/app/jobs/request_invitation_job.rb b/app/jobs/request_invitation_job.rb index b641ac3..2805113 100644 --- a/app/jobs/request_invitation_job.rb +++ b/app/jobs/request_invitation_job.rb @@ -1,4 +1,6 @@ class RequestInvitationJob < ApplicationJob + PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url + PORTFOLIORRRR_REQUEST_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.request_invitation_url queue_as :default retry_on Exceptions::PortfoliorrrAPIOffline, wait: 1.hour, attempts: :unlimited retry_on Exceptions::ColaBoraAPIOffline, wait: 1.hour, attempts: 5 do |job, _error| @@ -7,7 +9,7 @@ class RequestInvitationJob < ApplicationJob def perform(invitation_request:) data = { invitation_request_id: invitation_request.id }.as_json - response = Faraday.new(url: 'http://localhost:4000', params: data).get('/api/v1/projects/request_invitation') + response = Faraday.new(url: PORTFOLIORRR_BASE_URL, params: data).get(PORTFOLIORRRR_REQUEST_INVITATION_URL) return raise Exceptions::PortfoliorrrAPIOffline if response.status == :internal_server_error invitation_request.process_colabora_api_response(response) diff --git a/config/application.rb b/config/application.rb index 48f9c55..b2e37ee 100644 --- a/config/application.rb +++ b/config/application.rb @@ -41,5 +41,8 @@ class Application < Rails::Application # ColaBora API configurations config.colabora_api_v1 = config_for(:colabora_api_v1) + + # Portfoliorrr API configurations + config.portfoliorrr_api_v1 = config_for(:portfoliorrr_api_v1) end end diff --git a/config/portfoliorrr_api_v1.yml b/config/portfoliorrr_api_v1.yml new file mode 100644 index 0000000..5f23fce --- /dev/null +++ b/config/portfoliorrr_api_v1.yml @@ -0,0 +1,9 @@ +development: + base_url: 'http://localhost:4000' + invitations_url: '/api/v1/invitations/' + request_invitation_url: '/api/v1/projects/request_invitation' + +test: + base_url: 'http://localhost:4000' + invitations_url: '/api/v1/invitations/' + request_invitation_url: '/api/v1/projects/request_invitation' From 214b219cb32d02ff701d8236dde366a9bbd92cd2 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 11:46:05 -0300 Subject: [PATCH 15/27] =?UTF-8?q?Cria=20arquivo=20de=20configura=C3=A7?= =?UTF-8?q?=C3=A3o=20portfoliorrr=5Fapi=5Fv1.yml?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Centraliza URL base do Portfoliorrr e urls de endpoints de API da aplicação para o arquivo de configuração, para tornar o código mais DRY e facilitar manutenção futura. --- app/controllers/projects_controller.rb | 1 + app/javascript/components/projects_vue.js | 3 ++- app/jobs/decline_invitation_job.rb | 5 ++++- app/jobs/request_invitation_job.rb | 4 +++- app/views/projects/index.html.erb | 1 + config/application.rb | 3 +++ config/portfoliorrr_api_v1.yml | 11 +++++++++++ db/schema.rb | 4 ++-- 8 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 config/portfoliorrr_api_v1.yml diff --git a/app/controllers/projects_controller.rb b/app/controllers/projects_controller.rb index d0996a6..a35e537 100644 --- a/app/controllers/projects_controller.rb +++ b/app/controllers/projects_controller.rb @@ -5,6 +5,7 @@ def index @invitation_request = current_user.invitation_requests.build @invitation_requests = current_user.invitation_requests.pluck(:project_id).to_json @invitation_requests_projects_ids = current_user.invitation_requests.pluck(:project_id) + @projects_url = Rails.configuration.portfoliorrr_api_v1.projects_url end def create_invitation_request diff --git a/app/javascript/components/projects_vue.js b/app/javascript/components/projects_vue.js index de014f3..9597810 100644 --- a/app/javascript/components/projects_vue.js +++ b/app/javascript/components/projects_vue.js @@ -11,6 +11,7 @@ export default { currentProjectId: null, invitationRequestsProjectsIds: window.invitationRequestsProjectsIds, errorMsg: false, + portfoliorrrProjectsApiUrl: window.portfoliorrrProjectsApiUrl, } }, computed:{ @@ -45,7 +46,7 @@ export default { async created() { try { - let response = await fetch('/api/v1/projects', { signal }); + let response = await fetch(this.portfoliorrrProjectsApiUrl, { signal }); if (response.ok) { let data = await response.json(); if (!data.message) { diff --git a/app/jobs/decline_invitation_job.rb b/app/jobs/decline_invitation_job.rb index 85d2149..ef051d9 100644 --- a/app/jobs/decline_invitation_job.rb +++ b/app/jobs/decline_invitation_job.rb @@ -1,10 +1,13 @@ class DeclineInvitationJob < ApplicationJob + PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url + PORTFOLIORRR_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.invitations_url + retry_on Faraday::ConnectionFailed, Faraday::ServerError, wait: :polynomially_longer, attempts: 5 do |job| job.arguments.first.pending! end def perform(invitation) - url = "http://localhost:4000/api/v1/invitations/#{invitation.colabora_invitation_id}" + url = "#{PORTFOLIORRR_BASE_URL}#{PORTFOLIORRR_INVITATION_URL}#{invitation.colabora_invitation_id}" Faraday.new { |faraday| faraday.response :raise_error }.patch(url) invitation.declined! rescue Faraday::ResourceNotFound, Faraday::ConflictError diff --git a/app/jobs/request_invitation_job.rb b/app/jobs/request_invitation_job.rb index b641ac3..2805113 100644 --- a/app/jobs/request_invitation_job.rb +++ b/app/jobs/request_invitation_job.rb @@ -1,4 +1,6 @@ class RequestInvitationJob < ApplicationJob + PORTFOLIORRR_BASE_URL = Rails.configuration.portfoliorrr_api_v1.base_url + PORTFOLIORRRR_REQUEST_INVITATION_URL = Rails.configuration.portfoliorrr_api_v1.request_invitation_url queue_as :default retry_on Exceptions::PortfoliorrrAPIOffline, wait: 1.hour, attempts: :unlimited retry_on Exceptions::ColaBoraAPIOffline, wait: 1.hour, attempts: 5 do |job, _error| @@ -7,7 +9,7 @@ class RequestInvitationJob < ApplicationJob def perform(invitation_request:) data = { invitation_request_id: invitation_request.id }.as_json - response = Faraday.new(url: 'http://localhost:4000', params: data).get('/api/v1/projects/request_invitation') + response = Faraday.new(url: PORTFOLIORRR_BASE_URL, params: data).get(PORTFOLIORRRR_REQUEST_INVITATION_URL) return raise Exceptions::PortfoliorrrAPIOffline if response.status == :internal_server_error invitation_request.process_colabora_api_response(response) diff --git a/app/views/projects/index.html.erb b/app/views/projects/index.html.erb index 4d36291..5df3fbf 100644 --- a/app/views/projects/index.html.erb +++ b/app/views/projects/index.html.erb @@ -70,5 +70,6 @@
diff --git a/config/application.rb b/config/application.rb index 48f9c55..b2e37ee 100644 --- a/config/application.rb +++ b/config/application.rb @@ -41,5 +41,8 @@ class Application < Rails::Application # ColaBora API configurations config.colabora_api_v1 = config_for(:colabora_api_v1) + + # Portfoliorrr API configurations + config.portfoliorrr_api_v1 = config_for(:portfoliorrr_api_v1) end end diff --git a/config/portfoliorrr_api_v1.yml b/config/portfoliorrr_api_v1.yml new file mode 100644 index 0000000..75c9712 --- /dev/null +++ b/config/portfoliorrr_api_v1.yml @@ -0,0 +1,11 @@ +development: + base_url: 'http://localhost:4000' + invitations_url: '/api/v1/invitations/' + request_invitation_url: '/api/v1/projects/request_invitation' + projects_url: '/api/v1/projects' + +test: + base_url: 'http://localhost:4000' + invitations_url: '/api/v1/invitations/' + request_invitation_url: '/api/v1/projects/request_invitation' + projects_url: '/api/v1/projects' diff --git a/db/schema.rb b/db/schema.rb index 02e02c2..c7de8d0 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -55,8 +55,8 @@ t.integer "user_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false - t.text "old_message" t.integer "status", default: 0 + t.text "old_message" t.index ["post_id"], name: "index_comments_on_post_id" t.index ["user_id"], name: "index_comments_on_user_id" end @@ -162,7 +162,7 @@ t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "pin", default: 0 - t.datetime "edited_at", default: "2024-02-13 03:11:57" + t.datetime "edited_at" t.integer "status", default: 0 t.datetime "published_at" t.string "old_status" From 4d48a35197a4279da9e3ea9de9f9f2c39b8c5eb4 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 13:32:03 -0300 Subject: [PATCH 16/27] =?UTF-8?q?Adiciona=20e=20organiza=20testes=20unit?= =?UTF-8?q?=C3=A1rios?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../invitation_requests_controller.rb | 2 +- app/services/invitation_request_service.rb | 2 +- app/services/projects_service.rb | 4 +--- .../colabora_invitation_request_post_spec.rb | 18 ++++++++++++++++++ .../invitation_request_spec.rb | 8 ++++---- .../colabora_api_get_projects_spec.rb | 18 ++++++++++++++++++ .../colabora_project_spec.rb | 8 ++++---- 7 files changed, 47 insertions(+), 13 deletions(-) create mode 100644 spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb create mode 100644 spec/services/projects_service/colabora_api_get_projects_spec.rb rename spec/services/{invitation_request_service => projects_service}/colabora_project_spec.rb (82%) diff --git a/app/controllers/invitation_requests_controller.rb b/app/controllers/invitation_requests_controller.rb index 068112e..3637a96 100644 --- a/app/controllers/invitation_requests_controller.rb +++ b/app/controllers/invitation_requests_controller.rb @@ -7,7 +7,7 @@ def index @invitation_request_infos = [] begin - @invitation_request_infos = InvitationRequestService::InvitationRequest.list(invitation_requests) + @invitation_request_infos = InvitationRequestService::InvitationRequest.send(invitation_requests) rescue StandardError return @error = true end diff --git a/app/services/invitation_request_service.rb b/app/services/invitation_request_service.rb index 189842f..c9503b9 100644 --- a/app/services/invitation_request_service.rb +++ b/app/services/invitation_request_service.rb @@ -6,7 +6,7 @@ module InvitationRequestService COLABORA_API_V1_PROPOSALS_URL = Rails.configuration.colabora_api_v1.proposals_url class InvitationRequest - def self.list(requests) + def self.send(requests) return [] if requests.empty? projects = ProjectsService::ColaBoraProject.send diff --git a/app/services/projects_service.rb b/app/services/projects_service.rb index f08f7f0..449f2d6 100644 --- a/app/services/projects_service.rb +++ b/app/services/projects_service.rb @@ -4,7 +4,7 @@ module ProjectsService class ColaBoraProject def self.send - @response = Faraday.get("#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}") + @response = ColaBoraApiGetProjects.send return build_projects if @response.success? raise StandardError @@ -29,8 +29,6 @@ class ColaBoraApiGetProjects def self.send url = "#{COLABORA_BASE_URL}#{COLABORA_API_V1_PROJECTS_URL}" Faraday.get(url) - rescue Faraday::ConnectionFailed - raise Exceptions::ColaBoraAPIOffline end end end diff --git a/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb b/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb new file mode 100644 index 0000000..6c92dc6 --- /dev/null +++ b/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb @@ -0,0 +1,18 @@ +require 'rails_helper' + +RSpec.describe InvitationRequestService::ColaBoraInvitationRequestPost do + context '.send' do + it 'retorna a resposta da requisição feita ao ColaBora' do + invitation_request = create(:invitation_request) + fake_colabora_body = File.read(Rails.root.join('./spec/support/json/proposal_201.json')) + fake_colabora_response = double('faraday_response', status: 201, body: fake_colabora_body) + allow(Faraday).to receive(:post).and_return(fake_colabora_response) + + response = InvitationRequestService::ColaBoraInvitationRequestPost.send(invitation_request) + + json_response = JSON.parse(response.body) + expect(json_response.class).to eq Hash + expect(json_response['data']['proposal_id']).to eq 1 + end + end +end \ No newline at end of file diff --git a/spec/services/invitation_request_service/invitation_request_spec.rb b/spec/services/invitation_request_service/invitation_request_spec.rb index 2541f16..e8f249f 100644 --- a/spec/services/invitation_request_service/invitation_request_spec.rb +++ b/spec/services/invitation_request_service/invitation_request_spec.rb @@ -1,7 +1,7 @@ require 'rails_helper' RSpec.describe InvitationRequestService::InvitationRequest do - context '.list' do + context '.send' do it 'retorna array de objetos com informações completas do convite' do user = create(:user) @@ -22,7 +22,7 @@ allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - result = InvitationRequestService::InvitationRequest.list(requests) + result = InvitationRequestService::InvitationRequest.send(requests) expect(result.class).to eq Array expect(result.count).to eq 2 @@ -46,10 +46,10 @@ it 'retorna um array vazio quando não há solicitações de convite' do requests = [] - result = InvitationRequestService::InvitationRequest.list(requests) + result = InvitationRequestService::InvitationRequest.send(requests) expect(result.class).to eq Array expect(result).to be_empty end end -end +end \ No newline at end of file diff --git a/spec/services/projects_service/colabora_api_get_projects_spec.rb b/spec/services/projects_service/colabora_api_get_projects_spec.rb new file mode 100644 index 0000000..76edf48 --- /dev/null +++ b/spec/services/projects_service/colabora_api_get_projects_spec.rb @@ -0,0 +1,18 @@ +require 'rails_helper' + +RSpec.describe ProjectsService::ColaBoraApiGetProjects do + context '.send' do + it 'retorna array de objetos do tipo Project' do + json_data = File.read(Rails.root.join('./spec/support/json/projects.json')) + fake_response = double('faraday_response', success?: true, body: json_data) + + allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) + + result = ProjectsService::ColaBoraApiGetProjects.send + + json_response = JSON.parse(result.body) + expect(json_response.class).to eq Array + expect(json_response.count).to eq 4 + end + end +end diff --git a/spec/services/invitation_request_service/colabora_project_spec.rb b/spec/services/projects_service/colabora_project_spec.rb similarity index 82% rename from spec/services/invitation_request_service/colabora_project_spec.rb rename to spec/services/projects_service/colabora_project_spec.rb index 9ededc7..7917426 100644 --- a/spec/services/invitation_request_service/colabora_project_spec.rb +++ b/spec/services/projects_service/colabora_project_spec.rb @@ -1,6 +1,6 @@ require 'rails_helper' -RSpec.describe InvitationRequestService::ColaBoraProject do +RSpec.describe ProjectsService::ColaBoraProject do context '.send' do it 'retorna array de objetos do tipo Project' do json_data = File.read(Rails.root.join('./spec/support/json/projects.json')) @@ -20,9 +20,9 @@ category: 'Industrial') ] allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - allow(InvitationRequestService::ColaBoraProject).to receive(:build_projects).and_return(projects) + allow(ProjectsService::ColaBoraProject).to receive(:build_projects).and_return(projects) - result = InvitationRequestService::ColaBoraProject.send + result = ProjectsService::ColaBoraProject.send expect(result.class).to eq Array expect(result.count).to eq 4 @@ -33,7 +33,7 @@ fake_response = double('faraday_response', success?: false, status: :internal_server_error) allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - expect { InvitationRequestService::ColaBoraProject.send }.to raise_error(StandardError) + expect { ProjectsService::ColaBoraProject.send }.to raise_error(StandardError) end end end From c3a3d603594554ecd1b8ec9b306fc8c953e34a61 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 13:46:50 -0300 Subject: [PATCH 17/27] Corrige problemas de lint (rubocop) --- .../colabora_invitation_request_post_spec.rb | 2 +- .../invitation_request_service/invitation_request_spec.rb | 2 +- .../projects_service/colabora_api_get_projects_spec.rb | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb b/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb index 6c92dc6..8d8830e 100644 --- a/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb +++ b/spec/services/invitation_request_service/colabora_invitation_request_post_spec.rb @@ -15,4 +15,4 @@ expect(json_response['data']['proposal_id']).to eq 1 end end -end \ No newline at end of file +end diff --git a/spec/services/invitation_request_service/invitation_request_spec.rb b/spec/services/invitation_request_service/invitation_request_spec.rb index e8f249f..3be1788 100644 --- a/spec/services/invitation_request_service/invitation_request_spec.rb +++ b/spec/services/invitation_request_service/invitation_request_spec.rb @@ -52,4 +52,4 @@ expect(result).to be_empty end end -end \ No newline at end of file +end diff --git a/spec/services/projects_service/colabora_api_get_projects_spec.rb b/spec/services/projects_service/colabora_api_get_projects_spec.rb index 76edf48..ebfcffa 100644 --- a/spec/services/projects_service/colabora_api_get_projects_spec.rb +++ b/spec/services/projects_service/colabora_api_get_projects_spec.rb @@ -5,9 +5,9 @@ it 'retorna array de objetos do tipo Project' do json_data = File.read(Rails.root.join('./spec/support/json/projects.json')) fake_response = double('faraday_response', success?: true, body: json_data) - + allow(Faraday).to receive(:get).with('http://localhost:3000/api/v1/projects').and_return(fake_response) - + result = ProjectsService::ColaBoraApiGetProjects.send json_response = JSON.parse(result.body) From aa928ffd8dd2bef7c7d9e68d2f17e2415f73cc20 Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 14:31:55 -0300 Subject: [PATCH 18/27] Adiciona FriendlyId aos posts --- Gemfile | 1 + Gemfile.lock | 3 + app/controllers/comments_controller.rb | 14 ++- app/controllers/posts/likes_controller.rb | 2 +- app/controllers/posts_controller.rb | 2 +- app/controllers/reports_controller.rb | 10 +- app/models/post.rb | 3 + config/initializers/friendly_id.rb | 107 ++++++++++++++++++ .../20240215171014_add_slug_to_posts.rb | 6 + ...20240215171359_create_friendly_id_slugs.rb | 21 ++++ db/schema.rb | 15 ++- 11 files changed, 172 insertions(+), 12 deletions(-) create mode 100644 config/initializers/friendly_id.rb create mode 100644 db/migrate/20240215171014_add_slug_to_posts.rb create mode 100644 db/migrate/20240215171359_create_friendly_id_slugs.rb diff --git a/Gemfile b/Gemfile index 2ae20f8..e1c00d5 100644 --- a/Gemfile +++ b/Gemfile @@ -13,6 +13,7 @@ gem 'devise' gem 'faker' gem 'faraday' +gem 'friendly_id', '~> 5.5.0' gem 'image_processing', '>= 1.2' gem 'jbuilder' gem 'jsbundling-rails' diff --git a/Gemfile.lock b/Gemfile.lock index 3de4bb0..c4cb9c9 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -136,6 +136,8 @@ GEM webrick (~> 1.7) websocket-driver (>= 0.6, < 0.8) ffi (1.16.3) + friendly_id (5.5.1) + activerecord (>= 4.0.0) globalid (1.2.1) activesupport (>= 6.1) i18n (1.14.1) @@ -339,6 +341,7 @@ DEPENDENCIES factory_bot_rails faker faraday + friendly_id (~> 5.5.0) image_processing (>= 1.2) jbuilder jsbundling-rails diff --git a/app/controllers/comments_controller.rb b/app/controllers/comments_controller.rb index 95f998c..180c22e 100644 --- a/app/controllers/comments_controller.rb +++ b/app/controllers/comments_controller.rb @@ -1,15 +1,21 @@ class CommentsController < ApplicationController before_action :authenticate_user! + before_action :set_post def create - post = Post.find(params[:post_id]) comments_params = params.require(:comment).permit(:message) comments_params[:user_id] = current_user.id - comment = post.comments.build(comments_params) + comment = @post.comments.build(comments_params) if comment.save - redirect_to post, notice: t('.success') + redirect_to @post, notice: t('.success') else - redirect_to post, alert: t('.error') + redirect_to @post, alert: t('.error') end end end + +private + +def set_post + @post = Post.friendly.find(params[:post_id]) +end diff --git a/app/controllers/posts/likes_controller.rb b/app/controllers/posts/likes_controller.rb index b0024a0..7175121 100644 --- a/app/controllers/posts/likes_controller.rb +++ b/app/controllers/posts/likes_controller.rb @@ -5,7 +5,7 @@ class LikesController < LikesController private def set_likeable - @likeable = Post.find(params[:post_id]) + @likeable = Post.friendly.find(params[:post_id]) @post = @likeable end end diff --git a/app/controllers/posts_controller.rb b/app/controllers/posts_controller.rb index 7adfc0c..69df32f 100644 --- a/app/controllers/posts_controller.rb +++ b/app/controllers/posts_controller.rb @@ -68,7 +68,7 @@ def post_params end def set_post - @post = Post.find(params[:id]) + @post = Post.friendly.find(params[:id]) end def authorize! diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index 1407fce..4030ff5 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -47,11 +47,11 @@ def remove_profile private def set_reportable_for_new - reportable_id = params[:reportable] - @reportable = Post.find(reportable_id) if params[:reportable_type] == 'Post' - @reportable = Profile.find(reportable_id) if params[:reportable_type] == 'Profile' - @reportable = Comment.find(reportable_id) if params[:reportable_type] == 'Comment' - @reportable = Reply.find(reportable_id) if params[:reportable_type] == 'Reply' + reportable_type = params[:reportable_type] + @reportable = Post.friendly.find(reportable_id) if reportable_type == 'Post' + @reportable = Profile.find(reportable_id) if reportable_type == 'Profile' + @reportable = Comment.find(reportable_id) if reportable_type == 'Comment' + @reportable = Reply.find(reportable_id) if reportable_type == 'Reply' end def set_reportable_for_create diff --git a/app/models/post.rb b/app/models/post.rb index 51134ac..a3ea31c 100644 --- a/app/models/post.rb +++ b/app/models/post.rb @@ -20,6 +20,9 @@ class Post < ApplicationRecord has_rich_text :content + extend FriendlyId + friendly_id :title, use: :slugged + def self.get_sample(amount) published.sample amount end diff --git a/config/initializers/friendly_id.rb b/config/initializers/friendly_id.rb new file mode 100644 index 0000000..5852b58 --- /dev/null +++ b/config/initializers/friendly_id.rb @@ -0,0 +1,107 @@ +# FriendlyId Global Configuration +# +# Use this to set up shared configuration options for your entire application. +# Any of the configuration options shown here can also be applied to single +# models by passing arguments to the `friendly_id` class method or defining +# methods in your model. +# +# To learn more, check out the guide: +# +# http://norman.github.io/friendly_id/file.Guide.html + +FriendlyId.defaults do |config| + # ## Reserved Words + # + # Some words could conflict with Rails's routes when used as slugs, or are + # undesirable to allow as slugs. Edit this list as needed for your app. + config.use :reserved + + config.reserved_words = %w[new edit index session login logout users admin + stylesheets assets javascripts images] + + # This adds an option to treat reserved words as conflicts rather than exceptions. + # When there is no good candidate, a UUID will be appended, matching the existing + # conflict behavior. + + # config.treat_reserved_as_conflict = true + + # ## Friendly Finders + # + # Uncomment this to use friendly finders in all models. By default, if + # you wish to find a record by its friendly id, you must do: + # + # MyModel.friendly.find('foo') + # + # If you uncomment this, you can do: + # + # MyModel.find('foo') + # + # This is significantly more convenient but may not be appropriate for + # all applications, so you must explicitly opt-in to this behavior. You can + # always also configure it on a per-model basis if you prefer. + # + # Something else to consider is that using the :finders addon boosts + # performance because it will avoid Rails-internal code that makes runtime + # calls to `Module.extend`. + # + # config.use :finders + # + # ## Slugs + # + # Most applications will use the :slugged module everywhere. If you wish + # to do so, uncomment the following line. + # + # config.use :slugged + # + # By default, FriendlyId's :slugged addon expects the slug column to be named + # 'slug', but you can change it if you wish. + # + # config.slug_column = 'slug' + # + # By default, slug has no size limit, but you can change it if you wish. + # + # config.slug_limit = 255 + # + # When FriendlyId can not generate a unique ID from your base method, it appends + # a UUID, separated by a single dash. You can configure the character used as the + # separator. If you're upgrading from FriendlyId 4, you may wish to replace this + # with two dashes. + # + # config.sequence_separator = '-' + # + # Note that you must use the :slugged addon **prior** to the line which + # configures the sequence separator, or else FriendlyId will raise an undefined + # method error. + # + # ## Tips and Tricks + # + # ### Controlling when slugs are generated + # + # As of FriendlyId 5.0, new slugs are generated only when the slug field is + # nil, but if you're using a column as your base method can change this + # behavior by overriding the `should_generate_new_friendly_id?` method that + # FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave + # more like 4.0. + # Note: Use(include) Slugged module in the config if using the anonymous module. + # If you have `friendly_id :name, use: slugged` in the model, Slugged module + # is included after the anonymous module defined in the initializer, so it + # overrides the `should_generate_new_friendly_id?` method from the anonymous module. + # + # config.use :slugged + # config.use Module.new { + # def should_generate_new_friendly_id? + # slug.blank? || _changed? + # end + # } + # + # FriendlyId uses Rails's `parameterize` method to generate slugs, but for + # languages that don't use the Roman alphabet, that's not usually sufficient. + # Here we use the Babosa library to transliterate Russian Cyrillic slugs to + # ASCII. If you use this, don't forget to add "babosa" to your Gemfile. + # + # config.use Module.new { + # def normalize_friendly_id(text) + # text.to_slug.normalize! :transliterations => [:russian, :latin] + # end + # } +end diff --git a/db/migrate/20240215171014_add_slug_to_posts.rb b/db/migrate/20240215171014_add_slug_to_posts.rb new file mode 100644 index 0000000..8b0745c --- /dev/null +++ b/db/migrate/20240215171014_add_slug_to_posts.rb @@ -0,0 +1,6 @@ +class AddSlugToPosts < ActiveRecord::Migration[7.1] + def change + add_column :posts, :slug, :string + add_index :posts, :slug, unique: true + end +end diff --git a/db/migrate/20240215171359_create_friendly_id_slugs.rb b/db/migrate/20240215171359_create_friendly_id_slugs.rb new file mode 100644 index 0000000..a09491d --- /dev/null +++ b/db/migrate/20240215171359_create_friendly_id_slugs.rb @@ -0,0 +1,21 @@ +MIGRATION_CLASS = + if ActiveRecord::VERSION::MAJOR >= 5 + ActiveRecord::Migration["#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}"] + else + ActiveRecord::Migration + end + +class CreateFriendlyIdSlugs < MIGRATION_CLASS + def change + create_table :friendly_id_slugs do |t| + t.string :slug, null: false + t.integer :sluggable_id, null: false + t.string :sluggable_type, limit: 50 + t.string :scope + t.datetime :created_at + end + add_index :friendly_id_slugs, [:sluggable_type, :sluggable_id] + add_index :friendly_id_slugs, [:slug, :sluggable_type], length: {slug: 140, sluggable_type: 50} + add_index :friendly_id_slugs, [:slug, :sluggable_type, :scope], length: {slug: 70, sluggable_type: 50, scope: 70}, unique: true + end +end diff --git a/db/schema.rb b/db/schema.rb index 1e32535..d40f7e2 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[7.1].define(version: 2024_02_14_151256) do +ActiveRecord::Schema[7.1].define(version: 2024_02_15_171359) do create_table "action_text_rich_texts", force: :cascade do |t| t.string "name", null: false t.text "body" @@ -84,6 +84,17 @@ t.index ["profile_id"], name: "index_education_infos_on_profile_id" end + create_table "friendly_id_slugs", force: :cascade do |t| + t.string "slug", null: false + t.integer "sluggable_id", null: false + t.string "sluggable_type", limit: 50 + t.string "scope" + t.datetime "created_at" + t.index ["slug", "sluggable_type", "scope"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type_and_scope", unique: true + t.index ["slug", "sluggable_type"], name: "index_friendly_id_slugs_on_slug_and_sluggable_type" + t.index ["sluggable_type", "sluggable_id"], name: "index_friendly_id_slugs_on_sluggable_type_and_sluggable_id" + end + create_table "invitation_requests", force: :cascade do |t| t.integer "profile_id", null: false t.text "message" @@ -166,6 +177,8 @@ t.integer "status", default: 0 t.datetime "published_at" t.string "old_status" + t.string "slug" + t.index ["slug"], name: "index_posts_on_slug", unique: true t.index ["user_id"], name: "index_posts_on_user_id" end From 74b3e9b5dd373dfea8e76ece343eba8afd9f300d Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 14:36:09 -0300 Subject: [PATCH 19/27] =?UTF-8?q?Remove=20atribui=C3=A7=C3=A3o=20desnecess?= =?UTF-8?q?=C3=A1ria=20de=20headers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../projects_request_invitations_api_spec.rb | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb b/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb index d5d6d47..39d086b 100644 --- a/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb +++ b/spec/requests/apis/v1/projects/projects_request_invitations_api_spec.rb @@ -13,8 +13,7 @@ fake_colabora_response = double('faraday_response', status: 201, body: json_proposal_response) url = 'http://localhost:3000/api/v1/proposals' - headers = { 'Content-Type': 'application/json' } - allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data']) .and_return(fake_colabora_response) get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json @@ -34,10 +33,9 @@ project_id: invitation_request.project_id } } }.as_json url = 'http://localhost:3000/api/v1/proposals' - headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Projeto não encontrado'] }.as_json fake_colabora_response = double('faraday_response', status: 404, body: fake_colabora_response_body) - allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data']) .and_return(fake_colabora_response) get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json @@ -58,10 +56,9 @@ project_id: invitation_request.project_id } } }.as_json url = 'http://localhost:3000/api/v1/proposals' - headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Usuário já faz parte deste projeto'] }.as_json fake_colabora_response = double('faraday_response', status: 409, body: fake_colabora_response_body) - allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data']) .and_return(fake_colabora_response) get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json @@ -82,10 +79,9 @@ project_id: invitation_request.project_id } } }.as_json url = 'http://localhost:3000/api/v1/proposals' - headers = { 'Content-Type': 'application/json' } fake_colabora_response_body = { 'errors': ['Erro interno de servidor.'] }.as_json fake_colabora_response = double('faraday_response', status: 500, body: fake_colabora_response_body) - allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data']) .and_return(fake_colabora_response) get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json @@ -106,8 +102,7 @@ project_id: invitation_request.project_id } } }.as_json url = 'http://localhost:3000/api/v1/proposals' - headers = { 'Content-Type': 'application/json' } - allow(Faraday).to receive(:post).with(url, invitation_request_params['data'], headers) + allow(Faraday).to receive(:post).with(url, invitation_request_params['data']) .and_raise(ActiveRecord::ConnectionNotEstablished) get '/api/v1/projects/request_invitation', params: { invitation_request_id: invitation_request.id }.as_json From 4de95dd071bcd70002890c859fa270687c5bc5fc Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 15:37:28 -0300 Subject: [PATCH 20/27] Fix/Corrige merge conflitos Co-authored-by: Paulo Henrique --- app/controllers/reports_controller.rb | 1 + 1 file changed, 1 insertion(+) diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rb index f4ed5d7..ea5b8d2 100644 --- a/app/controllers/reports_controller.rb +++ b/app/controllers/reports_controller.rb @@ -47,6 +47,7 @@ def remove_profile private def set_reportable_for_new + reportable_id = params[:reportable] reportable_type = params[:reportable_type] @reportable = Post.friendly.find(reportable_id) if reportable_type == 'Post' @reportable = Profile.friendly.find(reportable_id) if reportable_type == 'Profile' From cef24c7ed77160c7d644b27ecc8f6ee144917dca Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 15:46:34 -0300 Subject: [PATCH 21/27] Remove quebras de linhas em excesso em NotifyLikes --- app/views/likes_mailer/notify_like.html.erb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app/views/likes_mailer/notify_like.html.erb b/app/views/likes_mailer/notify_like.html.erb index 9195aa9..fb9a692 100644 --- a/app/views/likes_mailer/notify_like.html.erb +++ b/app/views/likes_mailer/notify_like.html.erb @@ -6,12 +6,12 @@
<%= t('.comment_likes', like_count: @comment_likes.count) if @comment_likes.any? %>
<% if @post_likes.any? %> -

<%= t('.most_liked_post') %> <%= link_to @most_liked_post.title, post_url(@most_liked_post) %>

+

<%= t('.most_liked_post') %> <%= link_to @most_liked_post.title, post_url(@most_liked_post) %>

<% end %> <% if @comment_likes.any? %>

<%= t('.most_liked_comment', comment: @most_liked_comment.message) %> <%= link_to @most_liked_comment.post.title, post_url(@most_liked_comment.post) %>

<% end %> -

<%= link_to t('click_btn'), profile_url(@user.profile) %> <%= t('.access_profile') %>

+

<%= link_to t('click_btn'), profile_url(@user.profile) %> <%= t('.access_profile') %>

<%= t('.regards') %>, Portfoliorrr \ No newline at end of file From f0fff71c709ae9bf184c1183ea19b3441afbdac5 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 16:04:40 -0300 Subject: [PATCH 22/27] Refatora corpo do email de NotifyFollow --- app/views/connections_mailer/notify_follow.html.erb | 8 +++++++- app/views/likes_mailer/notify_like.html.erb | 2 +- config/locales/models/connections.pt-BR.yml | 5 ++++- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/views/connections_mailer/notify_follow.html.erb b/app/views/connections_mailer/notify_follow.html.erb index 6620377..e447029 100644 --- a/app/views/connections_mailer/notify_follow.html.erb +++ b/app/views/connections_mailer/notify_follow.html.erb @@ -1 +1,7 @@ -

<%= @notification.notifiable.follower.full_name %> <%= t('notifications.started_following_you') %>

+

<%= t('.greeting', recipient: @notification.profile.full_name) %>

+ +

<%= link_to @notification.notifiable.follower.full_name, profile_url(@notification.notifiable.follower) %> <%= t('notifications.started_following_you') %>

+ +

<%= link_to t('click_btn'), profile_url(@notification.profile) %> <%= t('.access_profile') %>

+<%= t('.regards') %>, +

Portfoliorrr

\ No newline at end of file diff --git a/app/views/likes_mailer/notify_like.html.erb b/app/views/likes_mailer/notify_like.html.erb index fb9a692..e59dbbb 100644 --- a/app/views/likes_mailer/notify_like.html.erb +++ b/app/views/likes_mailer/notify_like.html.erb @@ -14,4 +14,4 @@

<%= link_to t('click_btn'), profile_url(@user.profile) %> <%= t('.access_profile') %>

<%= t('.regards') %>, -Portfoliorrr \ No newline at end of file +

Portfoliorrr

\ No newline at end of file diff --git a/config/locales/models/connections.pt-BR.yml b/config/locales/models/connections.pt-BR.yml index a8d1387..7701ae9 100644 --- a/config/locales/models/connections.pt-BR.yml +++ b/config/locales/models/connections.pt-BR.yml @@ -29,4 +29,7 @@ pt-BR: connections_mailer: notify_follow: - subject: 'Alguém seguiu seu perfil' \ No newline at end of file + subject: 'Alguém seguiu seu perfil' + greeting: Olá, %{recipient}! + access_profile: para acessar seu perfil e continuar interagindo. + regards: Abraços \ No newline at end of file From 189484d82ba0519fff5d5d8fa30ad3dc3496387f Mon Sep 17 00:00:00 2001 From: Rodrigo Gyodai Date: Thu, 15 Feb 2024 16:08:44 -0300 Subject: [PATCH 23/27] Refactor do Superseed - Postagens com textos de tamanho e estrutura mais realistas - Melhorias de performance - Andamento do seed mostrado em tela Co-authored-by: Gabriel Manika --- README.md | 6 ++++++ db/seeds/superseed.rb | 24 ++++++++++++++++++------ spec/factories/posts.rb | 26 +++++++++++++++++++++++++- spec/factories/professional_infos.rb | 16 ++++++++++++++-- 4 files changed, 63 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 589a7c6..b7c5d91 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,12 @@ O Portfoliorrr é uma rede social com funcionalidades de portfólio para pessoas - Rode o comando `bin/setup` e aguarde sua conclusão; - Rode o comando `yarn install` (necessário ter `node` instalado em sua máquina); +## Populando o banco de dados + +- O seed comum, para desenvolvimento, pode ser feito normalmente com `rails db:seed` +- Para apresentações e testes de front-end, é possível fazer um superseed, utilizando `rails db:seed:superseed` +- O superseed utiliza as gems Faker e FactoryBot, que são instaladas durante a configuração (ver item anterior) + ## Como visualizar a aplicação no navegador - Siga as instruções de configuração da aplicação diff --git a/db/seeds/superseed.rb b/db/seeds/superseed.rb index 5590cff..180d518 100644 --- a/db/seeds/superseed.rb +++ b/db/seeds/superseed.rb @@ -58,6 +58,7 @@ ] # Adiciona usuários, perfis, informações pessoais +print "\n4. criando usuários " @number_of_users.times do user = FactoryBot.create(:user, :seed) profile = FactoryBot.create(:profile, :seed, user:) @@ -65,10 +66,11 @@ personal_info = FactoryBot.create(:personal_info, :seed, profile:) # Adiciona experiências profissionais - FactoryBot.create(:professional_info, :first_seed, profile:) + FactoryBot.create(:professional_info, :first_job, profile:) rand(2..7).times do - FactoryBot.create(:professional_info, :seed, profile:) + FactoryBot.create(:professional_info, :seed_job, profile:) end + FactoryBot.create(:professional_info, :current_job, profile:) # Adiciona experiências acadêmicas FactoryBot.create(:education_info, :first_seed, profile:) @@ -85,25 +87,33 @@ job_category: job_categories.sample, description: Faker::Lorem.paragraph) end + print '.' +end - # Cria um post com imagem e outros posts somente texto (WIP) +# Para cada user cria um post com imagem e de um a três sem imagens +print "\n3. criando postagens " +User.all.each do |user| html_post = %() - user.posts.create(title: Faker::Lorem.sentence, content: "#{Faker::Lorem.paragraph} #{html_post}", tag_list: [tags].sample) + FactoryBot.create(:post, :seed, user:, content: "#{Faker::Lorem.paragraphs(number: 3).join(' ')} #{html_post}") rand(1..3).times do - user.posts.create(title: Faker::Lorem.sentence, content: "#{Faker::Lorem.paragraph}", tag_list: [tags].sample) + FactoryBot.create(:post, :seed, user:) end + print '.' end # Adiciona followers aos perfis +print "\n2. estabelecendo seguidores e seguidos " User.all.each do |user| rand(2..5).times do not_followed_profiles = Profile.all.reject { |profile| profile.following?(user.profile) } followed_profile = not_followed_profiles.sample if not_followed_profiles.any? Connection.create!(follower: user.profile, followed_profile:) unless followed_profile == user.profile end + print '.' end # Adiciona comentários e likes +print "\n1. criando comentários e dando likes " Post.all.each do |post| rand(0..10).times do FactoryBot.create(:like, likeable: post, user: User.all.reject { |user| post.likes.pluck(:user_id).include?(user.id) }.sample) @@ -114,7 +124,9 @@ FactoryBot.create(:like, likeable: comment, user: User.all.reject { |user| comment.likes.pluck(:user_id).include?(user.id) }.sample) end end + print '.' end -puts "Pronto! #{@number_of_users} usuários criados." +puts "\nPronto! #{@number_of_users} usuários criados." puts "Admin: #{admin.email}, senha: #{admin.password}" +puts "\n" diff --git a/spec/factories/posts.rb b/spec/factories/posts.rb index f4e2404..dc24ef3 100644 --- a/spec/factories/posts.rb +++ b/spec/factories/posts.rb @@ -1,13 +1,37 @@ FactoryBot.define do + + def long_post + 'very big sentence' + end + factory :post do user title { Faker::Lorem.sentence } - content { Faker::Lorem.paragraph sentence_count: rand(35..50) } + content { Faker::Lorem.paragraph sentence_count: rand(2..12) } edited_at { Time.zone.now } trait :published do published_at { Time.zone.now } status { :published } end + + trait :seed do + content { + [ + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(2..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)) + ].join('

') + } + tag_list { + [ + ['tdd', 'rubocop'], ['seeds', 'desafios'], ['boaspraticas', 'solid'], ['vue', 'zoom'], ["vue", "desafios"], + ['codesaga', 'desafios', 'tdd'], ['rubocop', 'vue', 'seeds'], ['zoom', 'boaspraticas', 'solid'], + ["tdd", "codesaga"], ["rubocop", "vue", "desafios"], ["seeds", "boaspraticas", "zoom"], ["solid", "codesaga"] + ].sample + } + end end end diff --git a/spec/factories/professional_infos.rb b/spec/factories/professional_infos.rb index 827a72e..9fdd317 100644 --- a/spec/factories/professional_infos.rb +++ b/spec/factories/professional_infos.rb @@ -12,22 +12,34 @@ position { %w[programador estagiário gerente].sample } end - trait :first_seed do + trait :first_job do company { Faker::Company.name } position { Faker::Job.position } + description { Faker::Lorem.sentences(number: 6)} profile start_date { Faker::Date.backward(days: Time.zone.today - profile.personal_info.birth_date + 5840) } end_date { Faker::Date.between(from: start_date, to: start_date.advance(months: rand(2..120))) } end - trait :seed do + trait :seed_job do company { Faker::Company.name } position { Faker::Job.position } + description { Faker::Lorem.sentences(number: 6)} start_date do Faker::Date.between(from: profile.professional_infos.last.end_date, to: profile.professional_infos.last.end_date.advance(months: rand(2..12))) end end_date { Faker::Date.between(from: start_date, to: start_date.advance(months: rand(2..120))) } end + + trait :current_job do + company { Faker::Company.name } + position { Faker::Job.position } + description { Faker::Lorem.sentences(number: 6)} + profile + start_date { Faker::Date.backward(days: Time.zone.today - profile.personal_info.birth_date + 5840) } + end_date { } + current_job { true } + end end end From d2ccc5cb39a0800ca96e15514566757f6c2943fb Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 16:27:09 -0300 Subject: [PATCH 24/27] Refatora corpo do e-mail de InvitationMailer --- app/mailers/invitations_mailer.rb | 7 +++---- app/views/connections_mailer/notify_follow.html.erb | 4 ++-- app/views/invitations_mailer/received_invitation.html.erb | 7 +++++++ config/locales/models/connections.pt-BR.yml | 2 +- config/locales/models/invitation.pt-BR.yml | 5 ++++- spec/mailer/connections_mailer_spec.rb | 3 ++- 6 files changed, 19 insertions(+), 9 deletions(-) create mode 100644 app/views/invitations_mailer/received_invitation.html.erb diff --git a/app/mailers/invitations_mailer.rb b/app/mailers/invitations_mailer.rb index 1e1e480..5186cff 100644 --- a/app/mailers/invitations_mailer.rb +++ b/app/mailers/invitations_mailer.rb @@ -1,8 +1,7 @@ class InvitationsMailer < ApplicationMailer def received_invitation - profile = Profile.find(params[:profile_id]) - project_title = params[:project_title] - mail(subject: t('.subject'), to: profile.user.email, - body: t('.body', title: project_title)) + @profile = Profile.find(params[:profile_id]) + @project_title = params[:project_title] + mail(subject: t('.subject'), to: @profile.user.email) end end diff --git a/app/views/connections_mailer/notify_follow.html.erb b/app/views/connections_mailer/notify_follow.html.erb index e447029..766b5c5 100644 --- a/app/views/connections_mailer/notify_follow.html.erb +++ b/app/views/connections_mailer/notify_follow.html.erb @@ -2,6 +2,6 @@

<%= link_to @notification.notifiable.follower.full_name, profile_url(@notification.notifiable.follower) %> <%= t('notifications.started_following_you') %>

-

<%= link_to t('click_btn'), profile_url(@notification.profile) %> <%= t('.access_profile') %>

-<%= t('.regards') %>, +

<%= link_to t('click_btn'), @notification.profile %> <%= t('.access_profile') %>

+<%= t('.regards') %>

Portfoliorrr

\ No newline at end of file diff --git a/app/views/invitations_mailer/received_invitation.html.erb b/app/views/invitations_mailer/received_invitation.html.erb new file mode 100644 index 0000000..0a1d558 --- /dev/null +++ b/app/views/invitations_mailer/received_invitation.html.erb @@ -0,0 +1,7 @@ +

<%= t('.greeting', recipient: @profile.full_name) %>

+ +

<%= t('.body', title: @project_title) %>

+ +

<%= link_to t('click_btn'), invitations_url %> <%= t('.access_invitations') %>

+<%= t('.regards') %> +

Portfoliorrr

\ No newline at end of file diff --git a/config/locales/models/connections.pt-BR.yml b/config/locales/models/connections.pt-BR.yml index 7701ae9..07cd5f6 100644 --- a/config/locales/models/connections.pt-BR.yml +++ b/config/locales/models/connections.pt-BR.yml @@ -32,4 +32,4 @@ pt-BR: subject: 'Alguém seguiu seu perfil' greeting: Olá, %{recipient}! access_profile: para acessar seu perfil e continuar interagindo. - regards: Abraços \ No newline at end of file + regards: Abraços, \ No newline at end of file diff --git a/config/locales/models/invitation.pt-BR.yml b/config/locales/models/invitation.pt-BR.yml index 019e826..c17d43b 100644 --- a/config/locales/models/invitation.pt-BR.yml +++ b/config/locales/models/invitation.pt-BR.yml @@ -32,5 +32,8 @@ pt-BR: invitations_mailer: received_invitation: + greeting: Olá, %{recipient}! subject: 'Você recebeu um convite' - body: Você recebeu um convite para participar do projeto %{title}. + body: Você recebeu um convite para participar do projeto %{title}. + access_invitations: para ver seus convites e aceitá-los. + regards: Abraços, diff --git a/spec/mailer/connections_mailer_spec.rb b/spec/mailer/connections_mailer_spec.rb index 9656f87..ecffb2f 100644 --- a/spec/mailer/connections_mailer_spec.rb +++ b/spec/mailer/connections_mailer_spec.rb @@ -14,7 +14,8 @@ expect(mail.subject).to include 'Alguém seguiu seu perfil' expect(mail.to).to eq [followed_profile.email] expect(mail.from).to eq ['notifications@portfoliorrr.com'] - expect(mail.body).to include 'Danilo Martins começou a seguir você' + expect(mail.body).to include "" + expect(mail.body).to include 'Danilo Martins começou a seguir você' end end end From 34c09f163726067c9c90e726f2cb29409b60d851 Mon Sep 17 00:00:00 2001 From: Eliseu Ramos Date: Thu, 15 Feb 2024 17:32:03 -0300 Subject: [PATCH 25/27] =?UTF-8?q?Adiciona=20condicionais=20para=20presen?= =?UTF-8?q?=C3=A7a=20de=20published=5Fat=20e=20edited=5Fat?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/views/posts/show.html.erb | 8 +++++--- app/views/reports/_post.html.erb | 30 ++++++++++++++++++++---------- 2 files changed, 25 insertions(+), 13 deletions(-) diff --git a/app/views/posts/show.html.erb b/app/views/posts/show.html.erb index 60ffbc8..5c6c522 100644 --- a/app/views/posts/show.html.erb +++ b/app/views/posts/show.html.erb @@ -32,9 +32,11 @@

<% end %>

- + <% if @post.edited_at.present? %> + + <% end %>

diff --git a/app/views/reports/_post.html.erb b/app/views/reports/_post.html.erb index 7718a6d..9383253 100644 --- a/app/views/reports/_post.html.erb +++ b/app/views/reports/_post.html.erb @@ -7,16 +7,26 @@

<%= post.content %>

-

- -

-

- -

+ <% if post.published_at.present? %> +

+ +

+ <% else %> +

+ +

+ <% end %> + <% if post.edited_at.present? %> +

+ +

+ <% end %>

<% post.tags.each do |tag| %> From e8a303dd5c8411d9e5ea6abc1845d8a593ae73d8 Mon Sep 17 00:00:00 2001 From: Paulo Henrique Date: Thu, 15 Feb 2024 17:55:55 -0300 Subject: [PATCH 26/27] Fix/rubocop --- spec/factories/posts.rb | 33 ++++++++++++++-------------- spec/factories/professional_infos.rb | 8 +++---- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/spec/factories/posts.rb b/spec/factories/posts.rb index dc24ef3..c40477d 100644 --- a/spec/factories/posts.rb +++ b/spec/factories/posts.rb @@ -1,5 +1,4 @@ FactoryBot.define do - def long_post 'very big sentence' end @@ -16,22 +15,22 @@ def long_post end trait :seed do - content { - [ - Faker::Lorem.paragraph(sentence_count: rand(4..18)), - Faker::Lorem.paragraph(sentence_count: rand(2..18)), - Faker::Lorem.paragraph(sentence_count: rand(4..18)), - Faker::Lorem.paragraph(sentence_count: rand(4..18)), - Faker::Lorem.paragraph(sentence_count: rand(4..18)) - ].join('

') - } - tag_list { - [ - ['tdd', 'rubocop'], ['seeds', 'desafios'], ['boaspraticas', 'solid'], ['vue', 'zoom'], ["vue", "desafios"], - ['codesaga', 'desafios', 'tdd'], ['rubocop', 'vue', 'seeds'], ['zoom', 'boaspraticas', 'solid'], - ["tdd", "codesaga"], ["rubocop", "vue", "desafios"], ["seeds", "boaspraticas", "zoom"], ["solid", "codesaga"] - ].sample - } + content do + [ + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(2..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)), + Faker::Lorem.paragraph(sentence_count: rand(4..18)) + ].join('

') + end + tag_list do + [ + %w[tdd rubocop], %w[seeds desafios], %w[boaspraticas solid], %w[vue zoom], %w[vue desafios], + %w[codesaga desafios tdd], %w[rubocop vue seeds], %w[zoom boaspraticas solid], + %w[tdd codesaga], %w[rubocop vue desafios], %w[seeds boaspraticas zoom], %w[solid codesaga] + ].sample + end end end end diff --git a/spec/factories/professional_infos.rb b/spec/factories/professional_infos.rb index 9fdd317..fbe5106 100644 --- a/spec/factories/professional_infos.rb +++ b/spec/factories/professional_infos.rb @@ -15,7 +15,7 @@ trait :first_job do company { Faker::Company.name } position { Faker::Job.position } - description { Faker::Lorem.sentences(number: 6)} + description { Faker::Lorem.sentences(number: 6) } profile start_date { Faker::Date.backward(days: Time.zone.today - profile.personal_info.birth_date + 5840) } end_date { Faker::Date.between(from: start_date, to: start_date.advance(months: rand(2..120))) } @@ -24,7 +24,7 @@ trait :seed_job do company { Faker::Company.name } position { Faker::Job.position } - description { Faker::Lorem.sentences(number: 6)} + description { Faker::Lorem.sentences(number: 6) } start_date do Faker::Date.between(from: profile.professional_infos.last.end_date, to: profile.professional_infos.last.end_date.advance(months: rand(2..12))) @@ -35,10 +35,10 @@ trait :current_job do company { Faker::Company.name } position { Faker::Job.position } - description { Faker::Lorem.sentences(number: 6)} + description { Faker::Lorem.sentences(number: 6) } profile start_date { Faker::Date.backward(days: Time.zone.today - profile.personal_info.birth_date + 5840) } - end_date { } + end_date {} current_job { true } end end From 064964448ab0082aa2d422823d3e556defac54de Mon Sep 17 00:00:00 2001 From: anaresgalla Date: Thu, 15 Feb 2024 19:39:31 -0300 Subject: [PATCH 27/27] Corrige testes quebrados e problemas de rubocop --- app/mailers/invitations_mailer.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/app/mailers/invitations_mailer.rb b/app/mailers/invitations_mailer.rb index aa4e294..21de21e 100644 --- a/app/mailers/invitations_mailer.rb +++ b/app/mailers/invitations_mailer.rb @@ -1,7 +1,7 @@ class InvitationsMailer < ApplicationMailer def received_invitation - profile = Profile.friendly.find(params[:profile_id]) - project_title = params[:project_title] - mail(subject: t('.subject'), to: profile.user.email) + @profile = Profile.friendly.find(params[:profile_id]) + @project_title = params[:project_title] + mail(subject: t('.subject'), to: @profile.user.email) end end