From 275c2bdf22d351fd23b22a1dc3f5599b38878bb8 Mon Sep 17 00:00:00 2001 From: Mariana S Date: Wed, 26 Oct 2022 19:33:29 -0300 Subject: [PATCH 1/2] Preparando o projeto para desenvolvimento --- Gemfile.lock | 4 ++ .../product_categories_controller.rb | 21 ------- app/controllers/products_controller.rb | 61 ------------------- app/controllers/welcome_controller.rb | 9 --- .../_product_category.html.erb | 1 - app/views/products/_form.html.erb | 27 -------- app/views/products/_product.html.erb | 12 ---- app/views/products/edit.html.erb | 10 --- app/views/products/index.html.erb | 50 --------------- app/views/products/new.html.erb | 9 --- app/views/products/show.html.erb | 12 ---- app/views/welcome/index.html.erb | 42 ------------- db/seeds.rb | 11 +--- 13 files changed, 5 insertions(+), 264 deletions(-) delete mode 100644 app/controllers/product_categories_controller.rb delete mode 100644 app/controllers/products_controller.rb delete mode 100644 app/controllers/welcome_controller.rb delete mode 100644 app/views/product_categories/_product_category.html.erb delete mode 100644 app/views/products/_form.html.erb delete mode 100644 app/views/products/_product.html.erb delete mode 100644 app/views/products/edit.html.erb delete mode 100644 app/views/products/index.html.erb delete mode 100644 app/views/products/new.html.erb delete mode 100644 app/views/products/show.html.erb delete mode 100644 app/views/welcome/index.html.erb diff --git a/Gemfile.lock b/Gemfile.lock index 72989ad..d5f5e1b 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -131,6 +131,8 @@ GEM nio4r (2.5.8) nokogiri (1.13.8-arm64-darwin) racc (~> 1.4) + nokogiri (1.13.8-x86_64-linux) + racc (~> 1.4) orm_adapter (0.5.0) popper_js (2.11.6) public_suffix (5.0.0) @@ -206,6 +208,7 @@ GEM activesupport (>= 5.2) sprockets (>= 3.0.0) sqlite3 (1.5.2-arm64-darwin) + sqlite3 (1.5.2-x86_64-linux) thor (1.2.1) tilt (2.0.11) timeout (0.3.0) @@ -222,6 +225,7 @@ GEM PLATFORMS arm64-darwin-21 + x86_64-linux DEPENDENCIES bootstrap (~> 5.2.1) diff --git a/app/controllers/product_categories_controller.rb b/app/controllers/product_categories_controller.rb deleted file mode 100644 index 180bc41..0000000 --- a/app/controllers/product_categories_controller.rb +++ /dev/null @@ -1,21 +0,0 @@ -class ProductCategoriesController < ApplicationController - def create - ProductCategory.create!(name: params.require(:product_category).permit(:name)) - redirect_to products_path, notice: 'Categoria cadastrada' - end - - def search - nome_a_buscar = params[:busca] - ProductCategory.where("name LIKE :param_busca OR outro_campo LIKE :param_busca OR mais_um_campo LIKE :param_busca ", - { param_busca: "%#{nome_a_buscar}%" } ) - - @transports = find_available_transports - - end - - private - - def find_available_transports() - FreightageFinder.new(transports, order).find() - end -end \ No newline at end of file diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb deleted file mode 100644 index 039a826..0000000 --- a/app/controllers/products_controller.rb +++ /dev/null @@ -1,61 +0,0 @@ -class ProductsController < ApplicationController - before_action :set_product, only: %i[ show edit update destroy ] - - # GET /products - def index - @products = Product.all - @product = Product.new - @product_category = ProductCategory.new - @product_categories = ProductCategory.all - end - - # GET /products/1 - def show - end - - # GET /products/new - def new - @product = Product.new - end - - # GET /products/1/edit - def edit - end - - # POST /products - def create - @product = Product.new(product_params) - - if @product.save - redirect_to @product, notice: "Product was successfully created." - else - render :new, status: :unprocessable_entity - end - end - - # PATCH/PUT /products/1 - def update - if @product.update(product_params) - redirect_to @product, notice: "Product was successfully updated." - else - render :edit, status: :unprocessable_entity - end - end - - # DELETE /products/1 - def destroy - @product.destroy - redirect_to products_url, notice: "Product was successfully destroyed." - end - - private - # Use callbacks to share common setup or constraints between actions. - def set_product - @product = Product.find(params[:id]) - end - - # Only allow a list of trusted parameters through. - def product_params - params.require(:product).permit(:name, :price, :product_category_id) - end -end diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb deleted file mode 100644 index 73ff2dc..0000000 --- a/app/controllers/welcome_controller.rb +++ /dev/null @@ -1,9 +0,0 @@ -class WelcomeController < ApplicationController - - - def index - - end - - -end \ No newline at end of file diff --git a/app/views/product_categories/_product_category.html.erb b/app/views/product_categories/_product_category.html.erb deleted file mode 100644 index e216369..0000000 --- a/app/views/product_categories/_product_category.html.erb +++ /dev/null @@ -1 +0,0 @@ -<%= product_category.name %> \ No newline at end of file diff --git a/app/views/products/_form.html.erb b/app/views/products/_form.html.erb deleted file mode 100644 index a2a1d8e..0000000 --- a/app/views/products/_form.html.erb +++ /dev/null @@ -1,27 +0,0 @@ -<%= form_with(model: product) do |form| %> - <% if product.errors.any? %> -
-

<%= pluralize(product.errors.count, "error") %> prohibited this product from being saved:

- - -
- <% end %> - -
- <%= form.label :name, style: "display: block" %> - <%= form.text_field :name %> -
- -
- <%= form.label :price, style: "display: block" %> - <%= form.text_field :price %> -
- -
- <%= form.submit %> -
-<% end %> diff --git a/app/views/products/_product.html.erb b/app/views/products/_product.html.erb deleted file mode 100644 index 19ca353..0000000 --- a/app/views/products/_product.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -
-

- Name: - <%= product.name %> -

- -

- Price: - <%= product.price %> -

- -
diff --git a/app/views/products/edit.html.erb b/app/views/products/edit.html.erb deleted file mode 100644 index 90cb860..0000000 --- a/app/views/products/edit.html.erb +++ /dev/null @@ -1,10 +0,0 @@ -

Editing product

- -<%= render "form", product: @product %> - -
- -
- <%= link_to "Show this product", @product %> | - <%= link_to "Back to products", products_path %> -
diff --git a/app/views/products/index.html.erb b/app/views/products/index.html.erb deleted file mode 100644 index a84a004..0000000 --- a/app/views/products/index.html.erb +++ /dev/null @@ -1,50 +0,0 @@ -

<%= notice %>

- -

Products

-
- <% @products.each do |product| %> - <%= render product %> -

- <%= link_to "Show this product", product %> -

- <% end %> -
-
-

Nova Categoria de Produto

-<%= form_with(model: @product_category) do |f| %> - <%= f.label :name %> - <%= f.text_field :name %> - <%= f.submit %> -<% end %> -
- - - -

Novo Produto

-<%= form_with(model: @product) do |form| %> -
- <%= form.label :name, style: "display: block" %> - <%= form.text_field :name %> -
- -
- <%= form.label :price, style: "display: block" %> - <%= form.text_field :price %> -
- -
- <%= form.label :condition_new, 'Produto Novo' %> - <%= form.radio_button :condition, :new %> - - <%= form.label :condition_used, 'Produto Usado' %> - <%= form.radio_button :condition, :used %> -
- -
- <%= form.submit %> -
-<% end %> - - -choose 'Produto Usado' - diff --git a/app/views/products/new.html.erb b/app/views/products/new.html.erb deleted file mode 100644 index d438e41..0000000 --- a/app/views/products/new.html.erb +++ /dev/null @@ -1,9 +0,0 @@ -

New product

- -<%= render "form", product: @product %> - -
- -
- <%= link_to "Back to products", products_path %> -
diff --git a/app/views/products/show.html.erb b/app/views/products/show.html.erb deleted file mode 100644 index 7e30dc8..0000000 --- a/app/views/products/show.html.erb +++ /dev/null @@ -1,12 +0,0 @@ -

<%= notice %>

- -<%= render @product %> - -<%= render @product.product_category %> - -
- <%= link_to "Edit this product", edit_product_path(@product) %> | - <%= link_to "Back to products", products_path %> - - <%= button_to "Destroy this product", @product, method: :delete %> -
diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb deleted file mode 100644 index 65777a5..0000000 --- a/app/views/welcome/index.html.erb +++ /dev/null @@ -1,42 +0,0 @@ -

<%= translate('.title') %>

- -
-
- <%= image_tag 'delivery.png', class: 'img-fluid' %> -
- -
- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
#FirstLastHandle
1MarkOtto@mdo
2JacobThornton@fat
3Larry the Bird@twitter
-
-
- - -<%= link_to 'Início', root_path, class: 'btn btn-primary btn-lg' %> diff --git a/db/seeds.rb b/db/seeds.rb index fbaf120..0119433 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -6,13 +6,4 @@ # movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) # Character.create(name: "Luke", movie: movies.first) -User.create(email: user@email.com, password: ) -Company.create(name: , cnpj: ) -Product.create(name: , price: , company: ) - - - - - - -User.create(email: user@email.com, password: ) \ No newline at end of file +User.create(email: 'user@email.com', password: 'password') From df39be458e53111ba75689307319225b151fda51 Mon Sep 17 00:00:00 2001 From: Mariana S Date: Wed, 26 Oct 2022 20:36:34 -0300 Subject: [PATCH 2/2] Funcionalidade para adicionar produto Co-authored-by: Izabelly --- app/controllers/products_controller.rb | 18 ++ app/controllers/welcome_controller.rb | 7 + app/models/product_category.rb | 2 + app/views/products/new.html.erb | 11 ++ app/views/welcome/index.html.erb | 20 +++ config/initializers/locale.rb | 4 + config/locales/pt-BR.yml | 161 ++++++++++++++++-- config/routes.rb | 6 +- .../user_register_new_product_spec.rb | 36 ++++ 9 files changed, 247 insertions(+), 18 deletions(-) create mode 100644 app/controllers/products_controller.rb create mode 100644 app/controllers/welcome_controller.rb create mode 100644 app/views/products/new.html.erb create mode 100644 app/views/welcome/index.html.erb create mode 100644 config/initializers/locale.rb create mode 100644 spec/system/products/user_register_new_product_spec.rb diff --git a/app/controllers/products_controller.rb b/app/controllers/products_controller.rb new file mode 100644 index 0000000..7ec7cc1 --- /dev/null +++ b/app/controllers/products_controller.rb @@ -0,0 +1,18 @@ +class ProductsController < ApplicationController + + + def new + @product_categories = ProductCategory.all + @product = Product.new() + end + + def create + + product_params = params.require(:product).permit(:name, :price, :product_category_id) + product = Product.new(product_params) + product.save! + redirect_to root_path, notice: "Produto adicionado!" + + end + +end diff --git a/app/controllers/welcome_controller.rb b/app/controllers/welcome_controller.rb new file mode 100644 index 0000000..ceb57d6 --- /dev/null +++ b/app/controllers/welcome_controller.rb @@ -0,0 +1,7 @@ +class WelcomeController < ApplicationController + + def index + @products = Product.all + end + +end diff --git a/app/models/product_category.rb b/app/models/product_category.rb index 282738c..f8369d6 100644 --- a/app/models/product_category.rb +++ b/app/models/product_category.rb @@ -1,3 +1,5 @@ class ProductCategory < ApplicationRecord validates :name, presence: true + + has_many :products end diff --git a/app/views/products/new.html.erb b/app/views/products/new.html.erb new file mode 100644 index 0000000..c160738 --- /dev/null +++ b/app/views/products/new.html.erb @@ -0,0 +1,11 @@ +

Adicionar novo produto

+ +<%= form_with(model: @product) do |f| %> + <%= f.label :name, 'Nome'%> + <%= f.text_field :name %> + <%= f.label :price, 'Preço'%> + <%= f.number_field :price, step: 0.01 %> + <%= f.label :product_category_id, 'Categoria'%> + <%= f.collection_select :product_category_id, @product_categories, :id, :name %> + <%= f.submit 'Salvar' %> +<% end %> diff --git a/app/views/welcome/index.html.erb b/app/views/welcome/index.html.erb new file mode 100644 index 0000000..b31e498 --- /dev/null +++ b/app/views/welcome/index.html.erb @@ -0,0 +1,20 @@ +

Produtos

+ +
    +
  • <%= link_to 'Adicionar novo produto', new_product_url %>
  • +
+ + +
+ <% @products.each do |p| %> +
+
Nome:
+
<%= p.name %>
+
Preço:
+
<%= number_to_currency(p.price, unit: "R$", separator: ",", format: "%u %n") %>
+
Categoria:
+
<%= p.product_category.name %>
+
+ <% end %> + +
diff --git a/config/initializers/locale.rb b/config/initializers/locale.rb new file mode 100644 index 0000000..cb4e8d9 --- /dev/null +++ b/config/initializers/locale.rb @@ -0,0 +1,4 @@ +I18n.available_locales = [:'pt-BR'] + +# Set default locale to something other than :en +I18n.default_locale = :'pt-BR' \ No newline at end of file diff --git a/config/locales/pt-BR.yml b/config/locales/pt-BR.yml index 68c10cf..e20e676 100644 --- a/config/locales/pt-BR.yml +++ b/config/locales/pt-BR.yml @@ -1,14 +1,147 @@ -en: - transport_mode: - error: - not_available: 'Não existe modalidade disponível' - - welcome: - index: - title: 'Sistema de Frete e Transporatdoras' - outro: - outro: - outro: - - -I18n.translate('transport_mode.error.not_available') \ No newline at end of file +pt-BR: + activerecord: + attributes: + user: + confirmation_sent_at: Confirmação enviada em + confirmation_token: Token de confirmação + confirmed_at: Confirmado em + created_at: Criado em + current_password: Senha atual + current_sign_in_at: Atualmente logado em + current_sign_in_ip: IP do acesso atual + email: E-mail + encrypted_password: Senha criptografada + failed_attempts: Tentativas sem sucesso + last_sign_in_at: Último acesso em + last_sign_in_ip: Último IP de acesso + locked_at: Bloqueado em + password: Senha + password_confirmation: Confirme sua senha + remember_created_at: Lembrar criado em + remember_me: Lembre-se de mim + reset_password_sent_at: Resetar senha enviado em + reset_password_token: Resetar token de senha + sign_in_count: Contagem de acessos + unconfirmed_email: E-mail não confirmado + unlock_token: Token de desbloqueio + updated_at: Atualizado em + models: + user: + one: Usuário + other: Usuários + devise: + confirmations: + confirmed: A sua conta foi confirmada com sucesso. + new: + resend_confirmation_instructions: Reenviar instruções de confirmação + send_instructions: Dentro de minutos, você receberá um email com as instruções de confirmação da sua conta. + send_paranoid_instructions: Se o seu e-mail existir em nosso banco de dados, você receberá um email com instruções sobre como confirmar sua conta em alguns minutos. + failure: + already_authenticated: Você já está autenticado. + inactive: A sua conta ainda não foi ativada. + invalid: "%{authentication_keys} ou senha inválidos." + last_attempt: Você tem mais uma única tentativa antes de sua conta ser bloqueada. + locked: A sua conta está bloqueada. + not_found_in_database: "%{authentication_keys} ou senha inválidos." + timeout: A sua sessão expirou, por favor, faça login novamente para continuar. + unauthenticated: Para continuar, faça login ou registre-se. + unconfirmed: Antes de continuar, confirme a sua conta. + mailer: + confirmation_instructions: + action: Confirmar minha conta + greeting: Bem-vindo %{recipient}! + instruction: 'Você pode confirmar sua conta através do link abaixo:' + subject: Instruções de confirmação + email_changed: + greeting: Olá %{recipient}! + message: Estamos entrando em contato para notificá-lo de que seu e-mail está sendo alterado para %{email}. + message_unconfirmed: Estamos entrando em contato para notificá-lo de que seu e-mail está sendo alterado para %{email}. + subject: E-mail alterado + password_change: + greeting: Olá %{recipient}! + message: Estamos entrando em contato para notificá-lo de que sua senha foi alterada. + subject: Senha alterada + reset_password_instructions: + action: Redefinir minha senha + greeting: Olá %{recipient}! + instruction: Alguém fez o pedido para redefinir sua senha, e você pode fazer isso clicando no link abaixo. + instruction_2: Se você não fez este pedido, por favor ignore este e-mail. + instruction_3: Sua senha não será alterada até que você acesse o link acima e crie uma nova. + subject: Instruções de redefinição de senha + unlock_instructions: + action: Desbloquear minha conta + greeting: Olá %{recipient}! + instruction: 'Clique no link abaixo para desbloquear sua conta:' + message: Sua conta foi bloqueada devido ao excessivo número de tentativas acesso inválidas. + subject: Instruções de desbloqueio + omniauth_callbacks: + failure: Não foi possível autorizar de uma conta de %{kind} porque "%{reason}". + success: Autorizado com sucesso de uma conta de %{kind}. + passwords: + edit: + change_my_password: Alterar minha senha + change_your_password: Alterar sua senha + confirm_new_password: Confirme sua nova senha + new_password: Nova senha + new: + forgot_your_password: Esqueceu sua senha? + send_me_reset_password_instructions: Enviar instruções para redefinição da senha + no_token: Você não pode acessar esta página sem estar logado. Se você veio de um email de redefinição de senha, por favor certifique-se de ter digitado a URL corretamente. + send_instructions: Dentro de minutos, você receberá um e-mail com as instruções de redefinição da sua senha. + send_paranoid_instructions: Se o seu email existir em nosso banco de dados, você receberá um email com um link para recuperação da senha. + updated: A sua senha foi alterada com sucesso. Você está autenticado. + updated_not_active: Sua senha foi alterada com sucesso. + registrations: + destroyed: Adeus! A sua conta foi cancelada com sucesso. Esperamos vê-lo novamente em breve. + edit: + are_you_sure: Você tem certeza? + cancel_my_account: Cancelar minha conta + currently_waiting_confirmation_for_email: 'No momento esperando por: %{email}' + leave_blank_if_you_don_t_want_to_change_it: deixe em branco caso não queira alterá-la + title: Editar %{resource} + unhappy: Não está contente? + update: Atualizar + we_need_your_current_password_to_confirm_your_changes: precisamos da sua senha atual para confirmar suas mudanças + new: + sign_up: Inscrever-se + signed_up: Bem vindo! Você realizou seu registro com sucesso. + signed_up_but_inactive: Você se inscreveu com sucesso, porém nós não podemos autenticá-lo porque sua conta ainda não foi ativada. + signed_up_but_locked: Você se inscreveu com sucesso. Porém nós não podemos autenticá-lo porque sua conta está bloqueada. + signed_up_but_unconfirmed: Uma mensagem com um link de confirmação foi enviada para o seu e-mail. Por favor, acesse o link para ativar sua conta. + update_needs_confirmation: Sua conta foi atualizada com sucesso, mas nós precisamos verificar o novo endereço de email. Por favor, verifique seu e-mail e clique no link de confirmação para finalizar confirmando o seu novo e-mail. + updated: A sua conta foi atualizada com sucesso. + updated_but_not_signed_in: Sua conta foi atualizada com sucesso, uma vez que sua senha foi alterada será necessário realizar o login novamente. + sessions: + already_signed_out: Logout efetuado com sucesso. + new: + sign_in: Login + signed_in: Login efetuado com sucesso. + signed_out: Logout efetuado com sucesso. + shared: + links: + back: Voltar + didn_t_receive_confirmation_instructions: Não recebeu instruções de confirmação? + didn_t_receive_unlock_instructions: Não recebeu instruções de desbloqueio? + forgot_your_password: Esqueceu sua senha? + sign_in: Login + sign_in_with_provider: Entrar com %{provider} + sign_up: Inscrever-se + minimum_password_length: + one: "(Mínimo de %{count} caractere)" + other: "(Mínimo de %{count} caracteres)" + unlocks: + new: + resend_unlock_instructions: Reenviar instruções de desbloqueio + send_instructions: Dentro de minutos, você receberá um e-mail com instruções de desbloqueio da sua conta. + send_paranoid_instructions: Se sua conta existir em nosso banco de dados, você receberá em breve um e-mail com instruções para desbloquear ela. + unlocked: A sua conta foi desbloqueada com sucesso. Efetue login para continuar. + errors: + messages: + already_confirmed: já foi confirmado + confirmation_period_expired: É necessário ser confirmado dentro do período %{period}, por favor requisite um novo usuário. + expired: expirou, por favor solicite uma nova + not_found: não encontrado + not_locked: não foi bloqueado + not_saved: + one: 'Não foi possível salvar %{resource}: 1 erro' + other: 'Não foi possível salvar %{resource}: %{count} erros.' \ No newline at end of file diff --git a/config/routes.rb b/config/routes.rb index e23c4d5..b5dfa97 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -1,8 +1,6 @@ Rails.application.routes.draw do - resources :products - resources :product_categories, only: [:create, :show] do - resources :products, only: [:create] - end devise_for :users root 'welcome#index' + resources :products, only: [:new, :create] + resources :product_categories, only: [:new, :create, :show] end diff --git a/spec/system/products/user_register_new_product_spec.rb b/spec/system/products/user_register_new_product_spec.rb new file mode 100644 index 0000000..321146b --- /dev/null +++ b/spec/system/products/user_register_new_product_spec.rb @@ -0,0 +1,36 @@ +require 'rails_helper' + + +describe "Usuário registra produto" do + it 'a partir da página inicial' do + ProductCategory.create!(name: "Eletrônicos") + ProductCategory.create!(name: "Vestuário") + + visit root_path + click_on "Adicionar novo produto" + + expect(current_path).to eq(new_product_path) + expect(page).to have_field("Nome") + expect(page).to have_field("Preço") + expect(page).to have_select("Categoria") + expect(page).to have_button("Salvar") + end + + it 'com sucesso' do + ProductCategory.create!(name: "Eletrônicos") + ProductCategory.create!(name: "Vestuário") + + visit root_path + click_on "Adicionar novo produto" + fill_in "Nome", with: "Celular S20" + fill_in "Preço", with: 10.00 + select "Eletrônicos", from: "Categoria" + click_on "Salvar" + + expect(current_path).to eq(root_path) + expect(page).to have_content("Produto adicionado!") + expect(page).to have_content("Celular S20") + expect(page).to have_content("R$ 10,00") + expect(page).to have_content("Eletrônicos") + end +end \ No newline at end of file