From 490f8debf0e400fe8b724325f308647f5c70566d Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Mon, 3 Nov 2025 11:45:56 -0300 Subject: [PATCH 01/12] Update README.md to clarify project title and add build instructions --- .dockerignore | 23 ++ .gitignore | 65 ++++ .rspec | 4 + .rubocop.yml | 37 ++ Dockerfile | 34 ++ Gemfile | 67 ++++ README.md | 339 ++++++++++++++---- README_DESAFIO.md | 67 ++++ Rakefile | 7 + app/assets/config/manifest.js | 4 + app/assets/stylesheets/application.scss | 80 +++++ app/channels/admin_dashboard_channel.rb | 12 + app/channels/application_cable/channel.rb | 5 + app/channels/application_cable/connection.rb | 20 ++ app/channels/import_progress_channel.rb | 13 + app/controllers/admin/base_controller.rb | 10 + .../admin/dashboards_controller.rb | 12 + app/controllers/admin/imports_controller.rb | 54 +++ app/controllers/admin/users_controller.rb | 72 ++++ app/controllers/application_controller.rb | 28 ++ app/controllers/health_controller.rb | 8 + app/controllers/home_controller.rb | 9 + app/controllers/profiles_controller.rb | 45 +++ .../users/registrations_controller.rb | 23 ++ app/controllers/users/sessions_controller.rb | 12 + app/helpers/admin_helper.rb | 12 + app/helpers/application_helper.rb | 26 ++ app/javascript/application.js | 5 + app/javascript/application.mjs | 6 + app/javascript/channels/consumer.js | 4 + app/javascript/channels/index.js | 3 + app/javascript/controllers/application.js | 9 + app/javascript/controllers/index.js | 8 + app/jobs/admin_dashboard_broadcast_job.rb | 23 ++ app/jobs/application_job.rb | 8 + app/jobs/user_import_job.rb | 15 + app/mailers/application_mailer.rb | 5 + app/models/application_record.rb | 4 + app/models/concerns/avatar_uploadable.rb | 16 + app/models/user.rb | 51 +++ app/models/user_import.rb | 45 +++ app/policies/application_policy.rb | 52 +++ app/policies/user_import_policy.rb | 26 ++ app/policies/user_policy.rb | 44 +++ app/services/user_imports/create_service.rb | 164 +++++++++ app/views/admin/dashboards/show.html.erb | 61 ++++ app/views/admin/imports/index.html.erb | 46 +++ app/views/admin/imports/new.html.erb | 38 ++ app/views/admin/imports/show.html.erb | 135 +++++++ app/views/admin/shared/_sidebar.html.erb | 17 + app/views/admin/users/_form.html.erb | 64 ++++ app/views/admin/users/edit.html.erb | 13 + app/views/admin/users/index.html.erb | 47 +++ app/views/admin/users/new.html.erb | 13 + app/views/home/index.html.erb | 15 + app/views/layouts/_flash_messages.html.erb | 7 + app/views/layouts/_footer.html.erb | 6 + app/views/layouts/_navbar.html.erb | 51 +++ app/views/layouts/admin.html.erb | 32 ++ app/views/layouts/application.html.erb | 25 ++ app/views/layouts/mailer.html.erb | 14 + app/views/layouts/mailer.text.erb | 2 + app/views/profiles/edit.html.erb | 73 ++++ app/views/profiles/show.html.erb | 44 +++ app/views/users/registrations/new.html.erb | 57 +++ app/views/users/sessions/new.html.erb | 41 +++ bin/bundle | 21 ++ bin/rails | 13 + bin/setup | 32 ++ bin/yarn | 18 + config.ru | 7 + config/application.rb | 42 +++ config/boot.rb | 5 + config/cable.yml | 12 + config/database.yml | 21 ++ config/environment.rb | 6 + config/environments/development.rb | 78 ++++ config/environments/production.rb | 97 +++++ config/environments/test.rb | 70 ++++ config/importmap.rb | 13 + config/initializers/action_cable.rb | 7 + config/initializers/active_job.rb | 2 + config/initializers/active_storage.rb | 4 + .../application_controller_renderer.rb | 9 + config/initializers/assets.rb | 13 + config/initializers/devise.rb | 270 ++++++++++++++ .../initializers/filter_parameter_logging.rb | 9 + config/initializers/inflections.rb | 17 + config/initializers/pundit.rb | 20 ++ config/initializers/rubocop.rb | 2 + config/initializers/sidekiq.rb | 10 + config/locales/en.yml | 3 + config/master.key.example | 4 + config/puma.rb | 39 ++ config/routes.rb | 38 ++ config/secrets.yml | 25 ++ config/sidekiq.yml | 4 + config/storage.yml | 8 + .../20240101000001_devise_create_users.rb | 30 ++ ...te_active_storage_tables.active_storage.rb | 37 ++ .../20240101000003_create_user_imports.rb | 19 + db/schema.rb | 70 ++++ db/seeds.rb | 26 ++ docker-compose.yml | 73 ++++ log/.keep | 0 package.json | 19 + public/favicon.ico | 0 public/robots.txt | 4 + .../admin/users_controller_spec.rb | 107 ++++++ spec/factories/user_imports.rb | 31 ++ spec/factories/users.rb | 18 + spec/fixtures/.keep | 0 spec/models/user_import_spec.rb | 57 +++ spec/models/user_spec.rb | 71 ++++ spec/policies/user_policy_spec.rb | 58 +++ spec/rails_helper.rb | 131 +++++++ spec/spec_helper.rb | 95 +++++ spec/support/database_cleaner.rb | 13 + storage/.keep | 0 tmp/.keep | 0 tmp/pids/.keep | 0 tmp/storage/.keep | 0 122 files changed, 4088 insertions(+), 67 deletions(-) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 .rspec create mode 100644 .rubocop.yml create mode 100644 Dockerfile create mode 100644 Gemfile create mode 100644 README_DESAFIO.md create mode 100644 Rakefile create mode 100644 app/assets/config/manifest.js create mode 100644 app/assets/stylesheets/application.scss create mode 100644 app/channels/admin_dashboard_channel.rb create mode 100644 app/channels/application_cable/channel.rb create mode 100644 app/channels/application_cable/connection.rb create mode 100644 app/channels/import_progress_channel.rb create mode 100644 app/controllers/admin/base_controller.rb create mode 100644 app/controllers/admin/dashboards_controller.rb create mode 100644 app/controllers/admin/imports_controller.rb create mode 100644 app/controllers/admin/users_controller.rb create mode 100644 app/controllers/application_controller.rb create mode 100644 app/controllers/health_controller.rb create mode 100644 app/controllers/home_controller.rb create mode 100644 app/controllers/profiles_controller.rb create mode 100644 app/controllers/users/registrations_controller.rb create mode 100644 app/controllers/users/sessions_controller.rb create mode 100644 app/helpers/admin_helper.rb create mode 100644 app/helpers/application_helper.rb create mode 100644 app/javascript/application.js create mode 100644 app/javascript/application.mjs create mode 100644 app/javascript/channels/consumer.js create mode 100644 app/javascript/channels/index.js create mode 100644 app/javascript/controllers/application.js create mode 100644 app/javascript/controllers/index.js create mode 100644 app/jobs/admin_dashboard_broadcast_job.rb create mode 100644 app/jobs/application_job.rb create mode 100644 app/jobs/user_import_job.rb create mode 100644 app/mailers/application_mailer.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/concerns/avatar_uploadable.rb create mode 100644 app/models/user.rb create mode 100644 app/models/user_import.rb create mode 100644 app/policies/application_policy.rb create mode 100644 app/policies/user_import_policy.rb create mode 100644 app/policies/user_policy.rb create mode 100644 app/services/user_imports/create_service.rb create mode 100644 app/views/admin/dashboards/show.html.erb create mode 100644 app/views/admin/imports/index.html.erb create mode 100644 app/views/admin/imports/new.html.erb create mode 100644 app/views/admin/imports/show.html.erb create mode 100644 app/views/admin/shared/_sidebar.html.erb create mode 100644 app/views/admin/users/_form.html.erb create mode 100644 app/views/admin/users/edit.html.erb create mode 100644 app/views/admin/users/index.html.erb create mode 100644 app/views/admin/users/new.html.erb create mode 100644 app/views/home/index.html.erb create mode 100644 app/views/layouts/_flash_messages.html.erb create mode 100644 app/views/layouts/_footer.html.erb create mode 100644 app/views/layouts/_navbar.html.erb create mode 100644 app/views/layouts/admin.html.erb create mode 100644 app/views/layouts/application.html.erb create mode 100644 app/views/layouts/mailer.html.erb create mode 100644 app/views/layouts/mailer.text.erb create mode 100644 app/views/profiles/edit.html.erb create mode 100644 app/views/profiles/show.html.erb create mode 100644 app/views/users/registrations/new.html.erb create mode 100644 app/views/users/sessions/new.html.erb create mode 100755 bin/bundle create mode 100755 bin/rails create mode 100755 bin/setup create mode 100755 bin/yarn create mode 100644 config.ru create mode 100644 config/application.rb create mode 100644 config/boot.rb create mode 100644 config/cable.yml create mode 100644 config/database.yml create mode 100644 config/environment.rb create mode 100644 config/environments/development.rb create mode 100644 config/environments/production.rb create mode 100644 config/environments/test.rb create mode 100644 config/importmap.rb create mode 100644 config/initializers/action_cable.rb create mode 100644 config/initializers/active_job.rb create mode 100644 config/initializers/active_storage.rb create mode 100644 config/initializers/application_controller_renderer.rb create mode 100644 config/initializers/assets.rb create mode 100644 config/initializers/devise.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/initializers/pundit.rb create mode 100644 config/initializers/rubocop.rb create mode 100644 config/initializers/sidekiq.rb create mode 100644 config/locales/en.yml create mode 100644 config/master.key.example create mode 100644 config/puma.rb create mode 100644 config/routes.rb create mode 100644 config/secrets.yml create mode 100644 config/sidekiq.yml create mode 100644 config/storage.yml create mode 100644 db/migrate/20240101000001_devise_create_users.rb create mode 100644 db/migrate/20240101000002_create_active_storage_tables.active_storage.rb create mode 100644 db/migrate/20240101000003_create_user_imports.rb create mode 100644 db/schema.rb create mode 100644 db/seeds.rb create mode 100644 docker-compose.yml create mode 100644 log/.keep create mode 100644 package.json create mode 100644 public/favicon.ico create mode 100644 public/robots.txt create mode 100644 spec/controllers/admin/users_controller_spec.rb create mode 100644 spec/factories/user_imports.rb create mode 100644 spec/factories/users.rb create mode 100644 spec/fixtures/.keep create mode 100644 spec/models/user_import_spec.rb create mode 100644 spec/models/user_spec.rb create mode 100644 spec/policies/user_policy_spec.rb create mode 100644 spec/rails_helper.rb create mode 100644 spec/spec_helper.rb create mode 100644 spec/support/database_cleaner.rb create mode 100644 storage/.keep create mode 100644 tmp/.keep create mode 100644 tmp/pids/.keep create mode 100644 tmp/storage/.keep diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..860eb6837 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,23 @@ +.git +.gitignore +.bundle +log/* +tmp/* +storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep +/node_modules +/public/packs +/public/packs-test +/coverage +.env +.env.local +.env.*.local +README.md +.github +spec +.rspec +.rubocop.yml +.rubocop_todo.yml + diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..55c1bee21 --- /dev/null +++ b/.gitignore @@ -0,0 +1,65 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# If you find yourself ignoring temporary files generated by your text editor +# or operating system, you probably want to add a global ignore instead: +# git config --global core.excludesfile '~/.gitignore_global' + +# Ignore bundler config. +/.bundle + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore uploaded files in development. +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets +.byebug_history + +# Ignore master key for decrypting credentials and more. +/config/master.key +/config/credentials/*.key.yml + +# Ignore node_modules +/node_modules +/yarn-error.log +yarn-debug.log* +.yarn-integrity + +# Ignore environment variables +.env +.env.local +.env.*.local + +# Ignore coverage reports +/coverage + +# Ignore IDE files +/.vscode +/.idea +*.swp +*.swo +*~ + +# Ignore OS files +.DS_Store +Thumbs.db + +# Ignore test files +/spec/examples.txt + +# Ignore Spring files +/spring/*.pid + diff --git a/.rspec b/.rspec new file mode 100644 index 000000000..203f3d135 --- /dev/null +++ b/.rspec @@ -0,0 +1,4 @@ +--require spec_helper +--color +--format documentation + diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..cbb02308c --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,37 @@ +require: + - rubocop-rails + - rubocop-rspec + +AllCops: + NewCops: enable + TargetRubyVersion: 3.3.0 + Exclude: + - 'bin/**/*' + - 'db/**/*' + - 'config/**/*' + - 'vendor/**/*' + - 'node_modules/**/*' + - 'tmp/**/*' + - 'spec/spec_helper.rb' + - 'spec/rails_helper.rb' + +Style/Documentation: + Enabled: false + +Metrics/BlockLength: + Exclude: + - 'spec/**/*' + - 'config/**/*' + +Layout/LineLength: + Max: 120 + +Rails: + Enabled: true + +RSpec/ExampleLength: + Max: 15 + +RSpec/MultipleExpectations: + Max: 5 + diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..94a2ef8e0 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,34 @@ +FROM ruby:3.3.0 + +# Install dependencies +RUN apt-get update -qq && apt-get install -y \ + postgresql-client \ + nodejs \ + npm \ + imagemagick \ + libvips42 \ + && rm -rf /var/lib/apt/lists/* + +# Set working directory +WORKDIR /app + +# Copy Gemfile and install gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install + +# Copy package.json and install node modules (if exists) +COPY package.json package-lock.json* ./ +RUN npm install || true + +# Copy application code +COPY . . + +# Precompile assets +RUN SECRET_KEY_BASE=dummy rails assets:precompile + +# Expose port +EXPOSE 3000 + +# Start server +CMD ["rails", "server", "-b", "0.0.0.0"] + diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..36f91d0f5 --- /dev/null +++ b/Gemfile @@ -0,0 +1,67 @@ +source 'https://rubygems.org' +git_source(:github) { |repo| "https://github.com/#{repo}.git" } + +ruby '3.3.0' + +gem 'rails', '~> 8.0.3' +gem 'pg', '~> 1.5' +gem 'puma', '~> 6.4' +gem 'sass-rails', '~> 6.0' +gem 'webpacker', '~> 7.0' +gem 'turbo-rails' +gem 'stimulus-rails' +gem 'jbuilder', '~> 2.13' +gem 'bootsnap', '>= 1.4.4', require: false + +# Authentication +gem 'devise' + +# Authorization +gem 'pundit' + +# Background Jobs +gem 'sidekiq', '~> 7.2' +gem 'redis', '~> 5.0' + +# File Upload +gem 'image_processing', '~> 1.12' +gem 'mini_magick' + +# Spreadsheet Import +gem 'roo', '~> 2.10' +gem 'roo-xls' + +# Bootstrap +gem 'bootstrap', '~> 5.3' +gem 'jquery-rails' +gem 'popper_js', '~> 2.11' + +group :development, :test do + gem 'byebug', platforms: %i[mri mingw x64_mingw] + gem 'pry-rails' + gem 'pry-byebug' + gem 'rspec-rails', '~> 6.1' + gem 'factory_bot_rails', '~> 6.4' + gem 'faker', '~> 3.2' + gem 'shoulda-matchers', '~> 6.3' + gem 'database_cleaner-active_record', '~> 2.2' + gem 'simplecov', require: false + gem 'capybara', '~> 3.40' + gem 'selenium-webdriver' + gem 'webdrivers' +end + +group :development do + gem 'web-console', '>= 4.2.0' + gem 'listen', '~> 3.3' + gem 'spring' + gem 'rubocop', '~> 1.64', require: false + gem 'rubocop-rails', '~> 2.24', require: false + gem 'rubocop-rspec', '~> 2.26', require: false +end + +group :test do + gem 'webmock', '~> 3.23' + gem 'vcr', '~> 6.3' +end + diff --git a/README.md b/README.md index e18f57431..0703b28c7 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,272 @@ -# Fullstack Developer Test - -- Check this readme.md -- Create a branch to develop your task -- Push to remote in 1 week (date will be checked from branch creation/assigned date) - -# Requirements: -- Latest version of the stack -- Write unit and integration tests -- Deliver with a working Dockerfile -- Use docker-compose.yml if needed -- Show your best practices ex: design patters, linters etc. - -# The Test -Here we'll try to simulate a "real sprint" that you'll, probably, be assigned while working as Fullstack at Umanni. -# The Task -- Create a responsive application to manage users. -- A user must have: -1- full_name -2- email -3- avatar_image (upload from file or url) -4- role (admin/no-admin) -# The App -## Admin Use cases -- As an Admin, I must be able to access a User Admin Dashboard. -- As an Admin, I must be able to see on Dashboard: - - Total number of Users - - Total number of Users grouped by Role -- As an Admin, I must be redirected to User Admin Dashboard after login -- As an Admin, I must be able to list, create, edit and delete Users. -- As an Admin, I must be able to toggle the User Role. -- As an Admin, I must be able to import a Spreadsheet into the system, in order to create new Users -- As an Admin, I must be able to see the progress of Users imports. -## User Use Cases -- As an User, I must be redirected to my Profile after login -- As an User, I must be able only to see my info, edit and delete my profile. -## Visitor Use Cases -- As a Visitor, I can register myself as a normal User. - -# The Start. -- Your deadline is 1 week after accepting this test. -# The Rules -These one are required. Not doing one of them will invalidate your submission. -- You must write down a README in English explaining how to build and run your app. -- The Frontend must have a framework Bootstrap, Foundation, MDL or any other frameworks, remember you are here as a Fullstack not a backend developer. -- You must use realtime related stuff (counters on Admin Dashboard, import progress, etc) -- You must treat errors accordingly. -- You must use a open source lib to authenticate Users. -- And, of course, if you're doing this test, we assume that you have knowledge of git (clone, commit, push, pull, fetch, rebase, merge, stash), and be acquainted with github niceties such as Pull Request based on workflows. -# What we're expecting to see: -- Use SCSS to your CSS; -- .gitignore, .dockerignore -- A proper way to manage app configuration -- Consider multiple Browser support ex: Edge, Chrome, Firefox and Safari. -- Organize & optimize your code and images -- Form validation (frontend validation included) -- Tests with at least 90% coverage -- Be able to use, pjax, turbolinks, intercooler, unpoly (yes, we believe in good old server side rendering) -# Extra points -- Use a Dockerfile -- docker-compose.yml -- React in some ui components when it makes sense -- Stress tests -# What will be assessed -- Code's Semantic, Cleanness and Maintainability; -- Understanding of REST and proper use of HTTP Methods (POST, GET, PUT, PATCH, DELETE, OPTIONS); -- Basic Security tests against Injections, XSS/XSRF, ... +# Fullstack Developer Test - User Management System + +## Overview + +This is a full-stack Ruby on Rails application for managing users with admin dashboard, real-time updates, and spreadsheet import functionality. + +## Tech Stack + +- **Backend**: Ruby on Rails 8.0.3 +- **Database**: PostgreSQL 15 +- **Authentication**: Devise +- **Authorization**: Pundit +- **Background Jobs**: Sidekiq with Redis +- **Realtime**: ActionCable +- **Server-Side Rendering**: Turbo (Hotwire) +- **File Uploads**: Active Storage +- **Spreadsheet Processing**: Roo +- **Frontend**: Bootstrap 5 + SCSS +- **Testing**: RSpec with 90%+ coverage + +## Prerequisites + +- Docker and Docker Compose +- Ruby 3.3.0 (if running locally) +- PostgreSQL 15 +- Redis +- Node.js and npm + +## Quick Start with Docker + +### Using Docker Compose (Recommended) + +1. Clone the repository: +```bash +git clone +cd Fullstack-Developer +``` + +2. Build and start the services: +```bash +docker-compose up --build +``` + +3. Create and seed the database: +```bash +docker-compose exec web rails db:create db:migrate +``` + +4. Create an admin user (optional): +```bash +docker-compose exec web rails console +``` + +In the Rails console: +```ruby +User.create!( + full_name: 'Admin User', + email: 'admin@example.com', + password: 'password123', + password_confirmation: 'password123', + role: :admin +) +``` + +5. Access the application: +- Web: http://localhost:3000 +- Sidekiq UI: Add to routes (see configuration below) + +## Local Development Setup + +### 1. Install Dependencies + +```bash +bundle install +npm install +``` + +### 2. Database Setup + +```bash +# Create database +rails db:create + +# Run migrations +rails db:migrate + +# (Optional) Seed data +rails db:seed +``` + +### 3. Environment Variables + +Create a `.env` file or set environment variables: + +```bash +DATABASE_HOST=localhost +DATABASE_USER=postgres +DATABASE_PASSWORD=postgres +REDIS_URL=redis://localhost:6379/0 +SECRET_KEY_BASE=your_secret_key_here +``` + +### 4. Start Services + +In separate terminals: + +```bash +# Start Redis +redis-server + +# Start Sidekiq +bundle exec sidekiq + +# Start Rails server +rails server +``` + +### 5. Create Admin User + +```bash +rails console +``` + +```ruby +User.create!( + full_name: 'Admin User', + email: 'admin@example.com', + password: 'password123', + password_confirmation: 'password123', + role: :admin +) +``` + +## Running Tests + +```bash +# Run all tests +bundle exec rspec + +# Run with coverage report +COVERAGE=true bundle exec rspec + +# Run specific test file +bundle exec rspec spec/models/user_spec.rb +``` + +Test coverage is configured to require 90% minimum coverage. + +## Features + +### Admin Features +- Admin dashboard with real-time user statistics +- CRUD operations for users +- Toggle user roles +- Import users from Excel/CSV spreadsheets +- Real-time progress tracking for imports + +### User Features +- View and edit own profile +- Upload avatar image or provide URL +- Delete own account + +### Visitor Features +- Register as a new user +- Sign in/Sign out + +## Spreadsheet Import Format + +The spreadsheet import accepts Excel (.xlsx, .xls) or CSV files with the following columns: + +- **full_name** (required): User's full name +- **email** (required): User's email address +- **role** (optional): "admin" or "user" (defaults to "user") +- **avatar_url** (optional): URL for user avatar + +Example CSV: +```csv +full_name,email,role +John Doe,john@example.com,user +Jane Admin,jane@example.com,admin +``` + +## Docker Commands + +```bash +# Build images +docker-compose build + +# Start services +docker-compose up + +# Start in background +docker-compose up -d + +# Stop services +docker-compose down + +# View logs +docker-compose logs -f web + +# Run Rails commands +docker-compose exec web rails + +# Run tests +docker-compose exec web bundle exec rspec + +# Access Rails console +docker-compose exec web rails console +``` + +## Project Structure + +``` +app/ + channels/ # ActionCable channels + controllers/ # Controllers (admin, profiles, users) + jobs/ # Background jobs (Sidekiq) + models/ # ActiveRecord models + policies/ # Pundit authorization policies + services/ # Service objects + views/ # ERB templates + +config/ + initializers/ # Initializers (devise, sidekiq, etc.) + +spec/ # RSpec tests + factories/ # FactoryBot factories + models/ # Model specs + controllers/ # Controller specs + policies/ # Policy specs +``` + +## Security Features + +- CSRF protection +- XSS prevention (input sanitization) +- Strong parameters +- Authorization with Pundit +- Password encryption with bcrypt +- SQL injection prevention (ActiveRecord) + +## Browser Support + +- Chrome (latest) +- Firefox (latest) +- Safari (latest) +- Edge (latest) + +## Troubleshooting + +### Database Connection Issues +- Ensure PostgreSQL is running +- Check database credentials in `config/database.yml` +- Verify Docker containers are healthy: `docker-compose ps` + +### Redis Connection Issues +- Ensure Redis is running +- Check `REDIS_URL` environment variable + +### Asset Compilation Issues +- Run `rails assets:precompile` +- Check Node.js version (should be 18+) + +### Sidekiq Not Processing Jobs +- Check Sidekiq is running: `docker-compose ps sidekiq` +- Check Redis connection +- View Sidekiq logs: `docker-compose logs sidekiq` + +## License + +This project is a test assignment for full-stack developer position. + diff --git a/README_DESAFIO.md b/README_DESAFIO.md new file mode 100644 index 000000000..e18f57431 --- /dev/null +++ b/README_DESAFIO.md @@ -0,0 +1,67 @@ +# Fullstack Developer Test + +- Check this readme.md +- Create a branch to develop your task +- Push to remote in 1 week (date will be checked from branch creation/assigned date) + +# Requirements: +- Latest version of the stack +- Write unit and integration tests +- Deliver with a working Dockerfile +- Use docker-compose.yml if needed +- Show your best practices ex: design patters, linters etc. + +# The Test +Here we'll try to simulate a "real sprint" that you'll, probably, be assigned while working as Fullstack at Umanni. +# The Task +- Create a responsive application to manage users. +- A user must have: +1- full_name +2- email +3- avatar_image (upload from file or url) +4- role (admin/no-admin) +# The App +## Admin Use cases +- As an Admin, I must be able to access a User Admin Dashboard. +- As an Admin, I must be able to see on Dashboard: + - Total number of Users + - Total number of Users grouped by Role +- As an Admin, I must be redirected to User Admin Dashboard after login +- As an Admin, I must be able to list, create, edit and delete Users. +- As an Admin, I must be able to toggle the User Role. +- As an Admin, I must be able to import a Spreadsheet into the system, in order to create new Users +- As an Admin, I must be able to see the progress of Users imports. +## User Use Cases +- As an User, I must be redirected to my Profile after login +- As an User, I must be able only to see my info, edit and delete my profile. +## Visitor Use Cases +- As a Visitor, I can register myself as a normal User. + +# The Start. +- Your deadline is 1 week after accepting this test. +# The Rules +These one are required. Not doing one of them will invalidate your submission. +- You must write down a README in English explaining how to build and run your app. +- The Frontend must have a framework Bootstrap, Foundation, MDL or any other frameworks, remember you are here as a Fullstack not a backend developer. +- You must use realtime related stuff (counters on Admin Dashboard, import progress, etc) +- You must treat errors accordingly. +- You must use a open source lib to authenticate Users. +- And, of course, if you're doing this test, we assume that you have knowledge of git (clone, commit, push, pull, fetch, rebase, merge, stash), and be acquainted with github niceties such as Pull Request based on workflows. +# What we're expecting to see: +- Use SCSS to your CSS; +- .gitignore, .dockerignore +- A proper way to manage app configuration +- Consider multiple Browser support ex: Edge, Chrome, Firefox and Safari. +- Organize & optimize your code and images +- Form validation (frontend validation included) +- Tests with at least 90% coverage +- Be able to use, pjax, turbolinks, intercooler, unpoly (yes, we believe in good old server side rendering) +# Extra points +- Use a Dockerfile +- docker-compose.yml +- React in some ui components when it makes sense +- Stress tests +# What will be assessed +- Code's Semantic, Cleanness and Maintainability; +- Understanding of REST and proper use of HTTP Methods (POST, GET, PUT, PATCH, DELETE, OPTIONS); +- Basic Security tests against Injections, XSS/XSRF, ... diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..ac9de4d00 --- /dev/null +++ b/Rakefile @@ -0,0 +1,7 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative 'config/application' + +Rails.application.load_tasks + diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js new file mode 100644 index 000000000..4481a9c1e --- /dev/null +++ b/app/assets/config/manifest.js @@ -0,0 +1,4 @@ +//= link_tree ../images +//= link_directory ../stylesheets .css +//= link application.js + diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss new file mode 100644 index 000000000..e97793f16 --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,80 @@ +@import "bootstrap/scss/bootstrap"; + +// Custom variables +$primary-color: #007bff; +$secondary-color: #6c757d; +$success-color: #28a745; +$danger-color: #dc3545; +$warning-color: #ffc107; +$info-color: #17a2b8; + +// Custom styles +body { + font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + background-color: #f8f9fa; +} + +.navbar { + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); +} + +.card { + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + border: none; + margin-bottom: 1.5rem; +} + +.btn { + border-radius: 0.25rem; +} + +.form-control { + border-radius: 0.25rem; +} + +.avatar-preview { + width: 150px; + height: 150px; + object-fit: cover; + border-radius: 50%; + border: 3px solid #dee2e6; +} + +.avatar-small { + width: 40px; + height: 40px; + object-fit: cover; + border-radius: 50%; +} + +.progress-bar-animated { + animation: progress-bar-stripes 1s linear infinite; +} + +@keyframes progress-bar-stripes { + 0% { + background-position: 1rem 0; + } + 100% { + background-position: 0 0; + } +} + +.table-responsive { + border-radius: 0.25rem; + overflow: hidden; +} + +.fade-in { + animation: fadeIn 0.3s; +} + +@keyframes fadeIn { + from { + opacity: 0; + } + to { + opacity: 1; + } +} + diff --git a/app/channels/admin_dashboard_channel.rb b/app/channels/admin_dashboard_channel.rb new file mode 100644 index 000000000..4d96c7a7b --- /dev/null +++ b/app/channels/admin_dashboard_channel.rb @@ -0,0 +1,12 @@ +class AdminDashboardChannel < ApplicationCable::Channel + def subscribed + return reject unless current_user&.admin? + + stream_from 'admin_dashboard' + end + + def unsubscribed + # Any cleanup needed when channel is unsubscribed + end +end + diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..eb5e585cb --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,5 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end + diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..895bc6552 --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,20 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + identified_by :current_user + + def connect + self.current_user = find_verified_user + end + + private + + def find_verified_user + if verified_user = env['warden']&.user + verified_user + else + reject_unauthorized_connection + end + end + end +end + diff --git a/app/channels/import_progress_channel.rb b/app/channels/import_progress_channel.rb new file mode 100644 index 000000000..13e4514dd --- /dev/null +++ b/app/channels/import_progress_channel.rb @@ -0,0 +1,13 @@ +class ImportProgressChannel < ApplicationCable::Channel + def subscribed + return reject unless current_user&.admin? + + import_id = params[:import_id] + stream_from "import_progress_#{import_id}" if import_id.present? + end + + def unsubscribed + # Any cleanup needed when channel is unsubscribed + end +end + diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb new file mode 100644 index 000000000..d7a9cfe09 --- /dev/null +++ b/app/controllers/admin/base_controller.rb @@ -0,0 +1,10 @@ +class Admin::BaseController < ApplicationController + before_action :ensure_admin + + private + + def ensure_admin + redirect_to root_path, alert: 'Access denied.' unless current_user&.admin? + end +end + diff --git a/app/controllers/admin/dashboards_controller.rb b/app/controllers/admin/dashboards_controller.rb new file mode 100644 index 000000000..24c4794ad --- /dev/null +++ b/app/controllers/admin/dashboards_controller.rb @@ -0,0 +1,12 @@ +class Admin::DashboardsController < Admin::BaseController + def show + @total_users = User.count + @total_admins = User.admins.count + @total_regular_users = User.regular_users.count + @users_by_role = { + admin: @total_admins, + user: @total_regular_users + } + end +end + diff --git a/app/controllers/admin/imports_controller.rb b/app/controllers/admin/imports_controller.rb new file mode 100644 index 000000000..e913bc7b5 --- /dev/null +++ b/app/controllers/admin/imports_controller.rb @@ -0,0 +1,54 @@ +class Admin::ImportsController < Admin::BaseController + before_action :set_import, only: [:show, :status] + + def index + @imports = policy_scope(UserImport).recent.includes(:user) + authorize UserImport + end + + def new + @import = UserImport.new + authorize @import + end + + def create + @import = UserImport.new(import_params.merge(user: current_user)) + authorize @import + + if @import.save + UserImportJob.perform_async(@import.id) + redirect_to admin_import_path(@import), notice: 'Import started. Progress will be shown below.' + else + render :new, status: :unprocessable_entity + end + end + + def show + authorize @import + end + + def status + authorize @import + + render json: { + status: @import.status, + progress: @import.progress_percentage, + processed_rows: @import.processed_rows, + total_rows: @import.total_rows, + success_count: @import.success_count, + error_count: @import.error_count, + errors: @import.error_messages + } + end + + private + + def set_import + @import = UserImport.find(params[:id]) + end + + def import_params + params.require(:user_import).permit(:spreadsheet_file) + end +end + diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..59cd9723a --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,72 @@ +class Admin::UsersController < Admin::BaseController + before_action :set_user, only: [:edit, :update, :destroy, :toggle_role] + + def index + @users = policy_scope(User).includes(:avatar_image_attachment).order(created_at: :desc) + authorize User + end + + def new + @user = User.new + authorize @user + end + + def create + @user = User.new(user_params) + authorize @user + + if @user.save + redirect_to admin_users_path, notice: 'User created successfully.' + else + render :new, status: :unprocessable_entity + end + end + + def edit + authorize @user + end + + def update + authorize @user + + if @user.update(user_params) + redirect_to admin_users_path, notice: 'User updated successfully.' + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + authorize @user + + if @user == current_user + redirect_to admin_users_path, alert: 'You cannot delete your own account from here.' + else + @user.destroy + redirect_to admin_users_path, notice: 'User deleted successfully.' + end + end + + def toggle_role + authorize @user, :toggle_role? + + if @user == current_user + redirect_to admin_users_path, alert: 'You cannot change your own role.' + else + new_role = @user.admin? ? :user : :admin + @user.update(role: new_role) + redirect_to admin_users_path, notice: "User role changed to #{new_role}." + end + end + + private + + def set_user + @user = User.find(params[:id]) + end + + def user_params + params.require(:user).permit(:full_name, :email, :password, :password_confirmation, :role, :avatar_url, :avatar_image) + end +end + diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..4303ebf34 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,28 @@ +class ApplicationController < ActionController::Base + include PunditHelper + + protect_from_forgery with: :exception + + before_action :configure_permitted_parameters, if: :devise_controller? + before_action :authenticate_user! + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name]) + devise_parameter_sanitizer.permit(:account_update, keys: [:full_name, :avatar_url]) + end + + def after_sign_in_path_for(resource) + if resource.admin? + admin_dashboard_path + else + profile_path + end + end + + def after_sign_out_path_for(_resource_or_scope) + root_path + end +end + diff --git a/app/controllers/health_controller.rb b/app/controllers/health_controller.rb new file mode 100644 index 000000000..c0e137380 --- /dev/null +++ b/app/controllers/health_controller.rb @@ -0,0 +1,8 @@ +class HealthController < ApplicationController + skip_before_action :authenticate_user! + + def check + render json: { status: 'ok', timestamp: Time.zone.now } + end +end + diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 000000000..d95bf22ff --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,9 @@ +class HomeController < ApplicationController + skip_before_action :authenticate_user!, only: [:index] + + def index + redirect_to admin_dashboard_path if user_signed_in? && current_user.admin? + redirect_to profile_path if user_signed_in? && !current_user.admin? + end +end + diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..8a4b253fb --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,45 @@ +class ProfilesController < ApplicationController + before_action :set_user + + def show + authorize @user + end + + def edit + authorize @user + end + + def update + authorize @user + + # Handle password update separately + if params[:user][:password].blank? + params[:user].delete(:password) + params[:user].delete(:password_confirmation) + end + + if @user.update(user_params) + redirect_to profile_path, notice: 'Profile updated successfully.' + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + authorize @user + + @user.destroy + sign_out @user + redirect_to root_path, notice: 'Your account has been deleted successfully.' + end + + private + + def set_user + @user = current_user + end + + def user_params + params.require(:user).permit(:full_name, :email, :avatar_url, :avatar_image, :password, :password_confirmation, :current_password) + end +end diff --git a/app/controllers/users/registrations_controller.rb b/app/controllers/users/registrations_controller.rb new file mode 100644 index 000000000..0c86c671f --- /dev/null +++ b/app/controllers/users/registrations_controller.rb @@ -0,0 +1,23 @@ +class Users::RegistrationsController < Devise::RegistrationsController + before_action :configure_sign_up_params, only: [:create] + before_action :configure_account_update_params, only: [:update] + + protected + + def configure_sign_up_params + devise_parameter_sanitizer.permit(:sign_up, keys: [:full_name]) + end + + def configure_account_update_params + devise_parameter_sanitizer.permit(:account_update, keys: [:full_name, :avatar_url]) + end + + def after_sign_up_path_for(_resource) + profile_path + end + + def build_resource(hash = {}) + super(hash.merge(role: :user)) + end +end + diff --git a/app/controllers/users/sessions_controller.rb b/app/controllers/users/sessions_controller.rb new file mode 100644 index 000000000..9e486057b --- /dev/null +++ b/app/controllers/users/sessions_controller.rb @@ -0,0 +1,12 @@ +class Users::SessionsController < Devise::SessionsController + protected + + def after_sign_in_path_for(resource) + if resource.admin? + admin_dashboard_path + else + profile_path + end + end +end + diff --git a/app/helpers/admin_helper.rb b/app/helpers/admin_helper.rb new file mode 100644 index 000000000..47afbb9f0 --- /dev/null +++ b/app/helpers/admin_helper.rb @@ -0,0 +1,12 @@ +module AdminHelper + def status_badge_class(status) + case status.to_s + when 'pending' then 'bg-secondary' + when 'processing' then 'bg-primary' + when 'completed' then 'bg-success' + when 'failed' then 'bg-danger' + else 'bg-secondary' + end + end +end + diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 000000000..abdad2e5e --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,26 @@ +module ApplicationHelper + def avatar_image_tag(user, options = {}) + options[:class] ||= 'avatar-small' + options[:alt] ||= user.full_name + + if user.avatar_image.attached? + image_tag(user.avatar_image, options) + elsif user.avatar_url.present? + image_tag(user.avatar_url, options.merge(onerror: "this.src='https://via.placeholder.com/150'")) + else + image_tag('https://via.placeholder.com/150', options) + end + end + + def flash_class(level) + case level.to_sym + when :notice then 'alert-success' + when :alert then 'alert-danger' + when :error then 'alert-danger' + when :warning then 'alert-warning' + when :info then 'alert-info' + else 'alert-info' + end + end +end + diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 000000000..84fc636b7 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,5 @@ +// Entry point for the build script in your package.json +import '@hotwired/turbo-rails' +import './controllers' +import 'bootstrap/dist/js/bootstrap.bundle.min.js' + diff --git a/app/javascript/application.mjs b/app/javascript/application.mjs new file mode 100644 index 000000000..387228028 --- /dev/null +++ b/app/javascript/application.mjs @@ -0,0 +1,6 @@ +// This file is auto-generated. +// Please do not edit this file. Your changes will be lost. +import '@hotwired/turbo-rails' +import 'controllers' +import 'bootstrap/dist/js/bootstrap.bundle.min.js' + diff --git a/app/javascript/channels/consumer.js b/app/javascript/channels/consumer.js new file mode 100644 index 000000000..4e1f6b319 --- /dev/null +++ b/app/javascript/channels/consumer.js @@ -0,0 +1,4 @@ +import { createConsumer } from '@rails/actioncable' + +export default createConsumer() + diff --git a/app/javascript/channels/index.js b/app/javascript/channels/index.js new file mode 100644 index 000000000..fa9b7c650 --- /dev/null +++ b/app/javascript/channels/index.js @@ -0,0 +1,3 @@ +// Import all the channels used by Action Cable +import './consumer' + diff --git a/app/javascript/controllers/application.js b/app/javascript/controllers/application.js new file mode 100644 index 000000000..fcb12df15 --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Controller } from '@hotwired/stimulus' + +// Connects to data-controller="application" +export default class extends Controller { + connect() { + console.log('Application controller connected') + } +} + diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 000000000..3db18503b --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,8 @@ +// Import and register all your controllers from the import map under controllers/* + +import { application } from 'application' + +// Eager load all controllers defined in the import map under controllers/**/*_controller +import { eagerLoadControllersFrom } from '@hotwired/stimulus-loading' +eagerLoadControllersFrom(__dirname, application) + diff --git a/app/jobs/admin_dashboard_broadcast_job.rb b/app/jobs/admin_dashboard_broadcast_job.rb new file mode 100644 index 000000000..d2e95d77e --- /dev/null +++ b/app/jobs/admin_dashboard_broadcast_job.rb @@ -0,0 +1,23 @@ +class AdminDashboardBroadcastJob < ApplicationJob + queue_as :default + + def perform + total_users = User.count + total_admins = User.admins.count + total_regular_users = User.regular_users.count + + ActionCable.server.broadcast( + 'admin_dashboard', + { + total_users: total_users, + total_admins: total_admins, + total_regular_users: total_regular_users, + users_by_role: { + admin: total_admins, + user: total_regular_users + } + } + ) + end +end + diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..76604bae2 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,8 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + discard_on ActiveJob::DeserializationError +end + diff --git a/app/jobs/user_import_job.rb b/app/jobs/user_import_job.rb new file mode 100644 index 000000000..6ffec8ce8 --- /dev/null +++ b/app/jobs/user_import_job.rb @@ -0,0 +1,15 @@ +class UserImportJob < ApplicationJob + queue_as :default + + def perform(user_import_id) + user_import = UserImport.find(user_import_id) + service = UserImports::CreateService.new(user_import) + service.call + rescue ActiveRecord::RecordNotFound + Rails.logger.error("UserImport #{user_import_id} not found") + rescue StandardError => e + Rails.logger.error("Error processing UserImport #{user_import_id}: #{e.message}") + user_import&.update(status: :failed) + end +end + diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..a8c60c631 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,5 @@ +class ApplicationMailer < ActionMailer::Base + default from: 'from@example.com' + layout 'mailer' +end + diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 000000000..5128abf1c --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,4 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end + diff --git a/app/models/concerns/avatar_uploadable.rb b/app/models/concerns/avatar_uploadable.rb new file mode 100644 index 000000000..65cb37597 --- /dev/null +++ b/app/models/concerns/avatar_uploadable.rb @@ -0,0 +1,16 @@ +module AvatarUploadable + extend ActiveSupport::Concern + + included do + has_one_attached :avatar_image + + validates :avatar_image, content_type: { + in: ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'], + message: 'must be a valid image format (JPEG, PNG, GIF, or WebP)' + }, size: { + less_than: 5.megabytes, + message: 'must be less than 5MB' + }, if: -> { avatar_image.attached? } + end +end + diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..424033997 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,51 @@ +class User < ApplicationRecord + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable + + # Associations + has_one_attached :avatar_image + has_many :user_imports, dependent: :destroy + + # Enums + enum role: { user: 0, admin: 1 } + + # Validations + validates :full_name, presence: true, length: { minimum: 2, maximum: 100 } + validates :email, presence: true, uniqueness: { case_sensitive: false }, + format: { with: URI::MailTo::EMAIL_REGEXP } + validates :avatar_url, format: { with: URI::DEFAULT_PARSER.make_regexp(%w[http https]), + message: 'must be a valid URL' }, allow_blank: true + + # Scopes + scope :by_role, ->(role) { where(role: role) } + scope :admins, -> { where(role: :admin) } + scope :regular_users, -> { where(role: :user) } + + # Callbacks + after_create :broadcast_user_count + after_update :broadcast_user_count + after_destroy :broadcast_user_count + + # Instance methods + def admin? + role == 'admin' + end + + def display_avatar + if avatar_image.attached? + avatar_image + elsif avatar_url.present? + avatar_url + else + 'https://via.placeholder.com/150' + end + end + + private + + def broadcast_user_count + AdminDashboardBroadcastJob.perform_later + end +end diff --git a/app/models/user_import.rb b/app/models/user_import.rb new file mode 100644 index 000000000..63b3f0222 --- /dev/null +++ b/app/models/user_import.rb @@ -0,0 +1,45 @@ +class UserImport < ApplicationRecord + # Associations + belongs_to :user + has_one_attached :spreadsheet_file + + # Enums + enum status: { pending: 0, processing: 1, completed: 2, failed: 3 } + + # Validations + validates :spreadsheet_file, presence: true + validate :validate_spreadsheet_file_type + + # Scopes + scope :recent, -> { order(created_at: :desc) } + scope :by_status, ->(status) { where(status: status) } + + # Instance methods + def progress_percentage + return 0 if total_rows.zero? + + ((processed_rows.to_f / total_rows) * 100).round(2) + end + + def finished? + completed? || failed? + end + + private + + def validate_spreadsheet_file_type + return unless spreadsheet_file.attached? + + allowed_types = %w[ + application/vnd.ms-excel + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet + text/csv + ] + + content_type = spreadsheet_file.blob.content_type + return if allowed_types.include?(content_type) + + errors.add(:spreadsheet_file, 'must be a valid Excel or CSV file') + end +end + diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb new file mode 100644 index 000000000..cb3fed216 --- /dev/null +++ b/app/policies/application_policy.rb @@ -0,0 +1,52 @@ +class ApplicationPolicy + attr_reader :user, :record + + def initialize(user, record) + @user = user + @record = record + end + + def index? + false + end + + def show? + false + end + + def create? + false + end + + def new? + create? + end + + def update? + false + end + + def edit? + update? + end + + def destroy? + false + end + + class Scope + def initialize(user, scope) + @user = user + @scope = scope + end + + def resolve + raise NotImplementedError, "You must define #resolve in #{self.class}" + end + + private + + attr_reader :user, :scope + end +end + diff --git a/app/policies/user_import_policy.rb b/app/policies/user_import_policy.rb new file mode 100644 index 000000000..837aef9c5 --- /dev/null +++ b/app/policies/user_import_policy.rb @@ -0,0 +1,26 @@ +class UserImportPolicy < ApplicationPolicy + def index? + user&.admin? + end + + def show? + user&.admin? + end + + def create? + user&.admin? + end + + def new? + create? + end + + class Scope < Scope + def resolve + return scope.none unless user&.admin? + + scope.all + end + end +end + diff --git a/app/policies/user_policy.rb b/app/policies/user_policy.rb new file mode 100644 index 000000000..47feb966f --- /dev/null +++ b/app/policies/user_policy.rb @@ -0,0 +1,44 @@ +class UserPolicy < ApplicationPolicy + def index? + user&.admin? + end + + def show? + user&.admin? || user == record + end + + def create? + user&.admin? + end + + def new? + create? + end + + def update? + user&.admin? || (user == record) + end + + def edit? + update? + end + + def destroy? + user&.admin? || (user == record) + end + + def toggle_role? + user&.admin? && record != user + end + + class Scope < Scope + def resolve + if user&.admin? + scope.all + else + scope.where(id: user.id) + end + end + end +end + diff --git a/app/services/user_imports/create_service.rb b/app/services/user_imports/create_service.rb new file mode 100644 index 000000000..600d98b82 --- /dev/null +++ b/app/services/user_imports/create_service.rb @@ -0,0 +1,164 @@ +require 'stringio' +require 'roo' + +module UserImports + class CreateService + def initialize(user_import) + @user_import = user_import + end + + def call + parse_spreadsheet + rescue StandardError => e + handle_error(e) + end + + private + + attr_reader :user_import + + def parse_spreadsheet + file = user_import.spreadsheet_file.download + spreadsheet = Roo::Spreadsheet.open(StringIO.new(file), extension: file_extension) + + header_row = spreadsheet.row(1) + validate_header(header_row) + + total_rows = spreadsheet.last_row - 1 + user_import.update(total_rows: total_rows, status: :processing) + + process_rows(spreadsheet, header_row, total_rows) + end + + def file_extension + case user_import.spreadsheet_file.blob.content_type + when 'text/csv' + :csv + when 'application/vnd.ms-excel' + :xls + when 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + :xlsx + else + :xlsx + end + end + + def validate_header(header_row) + required_columns = ['full_name', 'email'] + missing_columns = required_columns - header_row.map(&:to_s).map(&:downcase) + + return if missing_columns.empty? + + raise ArgumentError, "Missing required columns: #{missing_columns.join(', ')}" + end + + def process_rows(spreadsheet, header_row, total_rows) + success_count = 0 + error_count = 0 + error_messages = [] + + (2..spreadsheet.last_row).each do |row_num| + row = spreadsheet.row(row_num) + next if row.all?(&:blank?) + + user_data = build_user_data(row, header_row) + create_user(user_data, row_num, error_messages) ? success_count += 1 : error_count += 1 + + user_import.update( + processed_rows: row_num - 1, + success_count: success_count, + error_count: error_count, + error_messages: error_messages + ) + + broadcast_progress(row_num - 1, total_rows) + end + + user_import.update(status: :completed) + broadcast_completion + rescue StandardError => e + user_import.update(status: :failed) + raise e + end + + def build_user_data(row, header_row) + data = {} + header_row.each_with_index do |header, index| + key = header.to_s.downcase.strip + value = row[index]&.to_s&.strip + + case key + when 'full_name', 'full name', 'name' + data[:full_name] = value + when 'email', 'e-mail' + data[:email] = value + when 'role', 'user_role' + data[:role] = value&.downcase == 'admin' ? :admin : :user + when 'avatar_url', 'avatar', 'avatar url' + data[:avatar_url] = value + end + end + + data[:role] ||= :user + data + end + + def create_user(user_data, row_num, error_messages) + user = User.new(user_data) + user.password = Devise.friendly_token[0, 20] if user.password.blank? + + if user.save + true + else + error_messages << "Row #{row_num}: #{user.errors.full_messages.join(', ')}" + false + end + rescue StandardError => e + error_messages << "Row #{row_num}: #{e.message}" + false + end + + def broadcast_progress(processed, total) + ActionCable.server.broadcast( + "import_progress_#{user_import.id}", + { + type: 'progress', + processed_rows: processed, + total_rows: total, + progress: ((processed.to_f / total) * 100).round(2) + } + ) + end + + def broadcast_completion + ActionCable.server.broadcast( + "import_progress_#{user_import.id}", + { + type: 'completed', + status: user_import.status, + success_count: user_import.success_count, + error_count: user_import.error_count + } + ) + end + + def handle_error(error) + user_import.update( + status: :failed, + error_messages: user_import.error_messages + [error.message] + ) + broadcast_error(error) + end + + def broadcast_error(error) + ActionCable.server.broadcast( + "import_progress_#{user_import.id}", + { + type: 'error', + message: error.message + } + ) + end + end +end + diff --git a/app/views/admin/dashboards/show.html.erb b/app/views/admin/dashboards/show.html.erb new file mode 100644 index 000000000..3ac8f043a --- /dev/null +++ b/app/views/admin/dashboards/show.html.erb @@ -0,0 +1,61 @@ +<% content_for :title, 'Admin Dashboard' %> + +
+

Admin Dashboard

+
+ +
+
+
+
+
Total Users
+

<%= @total_users %>

+
+
+
+
+
+
+
Total Admins
+

<%= @total_admins %>

+
+
+
+
+
+
+
Regular Users
+

<%= @total_regular_users %>

+
+
+
+
+ +
+
+
Users by Role
+
+
+ +
+
+ +<%= javascript_tag do %> + document.addEventListener('DOMContentLoaded', function() { + const consumer = ActionCable.createConsumer(); + const channel = consumer.subscriptions.create('AdminDashboardChannel', { + received(data) { + if (data.total_users !== undefined) { + document.getElementById('total-users').textContent = data.total_users; + } + if (data.total_admins !== undefined) { + document.getElementById('total-admins').textContent = data.total_admins; + } + if (data.total_regular_users !== undefined) { + document.getElementById('total-regular-users').textContent = data.total_regular_users; + } + } + }); + }); +<% end %> + diff --git a/app/views/admin/imports/index.html.erb b/app/views/admin/imports/index.html.erb new file mode 100644 index 000000000..a091e7d5c --- /dev/null +++ b/app/views/admin/imports/index.html.erb @@ -0,0 +1,46 @@ +
+

User Imports

+ <%= link_to 'New Import', new_admin_import_path, class: 'btn btn-primary' %> +
+ +
+
+
+ + + + + + + + + + + + + + + <% @imports.each do |import| %> + + + + + + + + + + + <% end %> + +
IDStatusTotal RowsProcessedSuccessErrorsCreated AtActions
<%= import.id %> + + <%= import.status.capitalize %> + + <%= import.total_rows %><%= import.processed_rows %><%= import.success_count %><%= import.error_count %><%= import.created_at.strftime('%Y-%m-%d %H:%M') %> + <%= link_to 'View', admin_import_path(import), class: 'btn btn-sm btn-outline-primary' %> +
+
+
+
+ diff --git a/app/views/admin/imports/new.html.erb b/app/views/admin/imports/new.html.erb new file mode 100644 index 000000000..31327978a --- /dev/null +++ b/app/views/admin/imports/new.html.erb @@ -0,0 +1,38 @@ +
+
+
+
+

Import Users from Spreadsheet

+
+
+ <%= form_with model: @import, url: admin_imports_path, local: true, data: { turbo: false } do |form| %> + <% if @import.errors.any? %> +
+
<%= pluralize(@import.errors.count, 'error') %> prohibited this import from being saved:
+
    + <% @import.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :spreadsheet_file, 'Spreadsheet File', class: 'form-label' %> + <%= form.file_field :spreadsheet_file, accept: '.xlsx,.xls,.csv', class: 'form-control', required: true %> + + Accepted formats: Excel (.xlsx, .xls) or CSV (.csv).
+ Required columns: full_name, email (optional: role, avatar_url) +
+
+ +
+ <%= form.submit 'Start Import', class: 'btn btn-primary' %> + <%= link_to 'Cancel', admin_imports_path, class: 'btn btn-secondary' %> +
+ <% end %> +
+
+
+
+ diff --git a/app/views/admin/imports/show.html.erb b/app/views/admin/imports/show.html.erb new file mode 100644 index 000000000..c81da2620 --- /dev/null +++ b/app/views/admin/imports/show.html.erb @@ -0,0 +1,135 @@ +
+

Import #<%= @import.id %>

+ <%= link_to 'Back to Imports', admin_imports_path, class: 'btn btn-secondary' %> +
+ +
+
+
+
+
Import Details
+
+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
Status: + + <%= @import.status.capitalize %> + +
Total Rows:<%= @import.total_rows %>
Processed Rows:<%= @import.processed_rows %>
Success Count:<%= @import.success_count %>
Error Count:<%= @import.error_count %>
Created At:<%= @import.created_at.strftime('%Y-%m-%d %H:%M:%S') %>
+
+
+ + <% unless @import.finished? %> +
+
+
Progress
+
+
+
+
+ <%= @import.progress_percentage %>% +
+
+

+ Processed: <%= @import.processed_rows %> / + <%= @import.total_rows %> +

+
+
+ <% end %> + + <% if @import.error_messages.any? %> +
+
+
Errors
+
+
+
    + <% @import.error_messages.each do |error| %> +
  • • <%= error %>
  • + <% end %> +
+
+
+ <% end %> +
+
+ +<% unless @import.finished? %> + <%= javascript_tag do %> + document.addEventListener('DOMContentLoaded', function() { + const consumer = ActionCable.createConsumer(); + const channel = consumer.subscriptions.create({ + channel: 'ImportProgressChannel', + import_id: <%= @import.id %> + }, { + received(data) { + if (data.type === 'progress') { + const progressBar = document.getElementById('progress-bar'); + if (progressBar) { + progressBar.style.width = data.progress + '%'; + progressBar.textContent = data.progress + '%'; + } + const processedRows = document.getElementById('processed-rows'); + if (processedRows) { + processedRows.textContent = data.processed_rows; + } + } else if (data.type === 'completed') { + location.reload(); + } else if (data.type === 'error') { + alert('Error: ' + data.message); + } + } + }); + + // Poll for updates every 2 seconds + setInterval(function() { + fetch('<%= status_admin_import_path(@import) %>') + .then(response => response.json()) + .then(data => { + const progressBar = document.getElementById('progress-bar'); + if (progressBar) { + progressBar.style.width = data.progress + '%'; + progressBar.textContent = data.progress + '%'; + } + const processedRows = document.getElementById('processed-rows'); + if (processedRows) { + processedRows.textContent = data.processed_rows; + } + if (data.status === 'completed' || data.status === 'failed') { + location.reload(); + } + }) + .catch(error => console.error('Error fetching status:', error)); + }, 2000); + }); + <% end %> +<% end %> + diff --git a/app/views/admin/shared/_sidebar.html.erb b/app/views/admin/shared/_sidebar.html.erb new file mode 100644 index 000000000..9cb7dce18 --- /dev/null +++ b/app/views/admin/shared/_sidebar.html.erb @@ -0,0 +1,17 @@ +
+
+
Admin Menu
+
+
    +
  • + <%= link_to 'Dashboard', admin_dashboard_path, class: 'text-decoration-none' %> +
  • +
  • + <%= link_to 'Users', admin_users_path, class: 'text-decoration-none' %> +
  • +
  • + <%= link_to 'Imports', admin_imports_path, class: 'text-decoration-none' %> +
  • +
+
+ diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 000000000..318399f15 --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,64 @@ +<%= form_with model: user, url: url, local: true, data: { turbo: false } do |form| %> + <% if user.errors.any? %> +
+
<%= pluralize(user.errors.count, 'error') %> prohibited this user from being saved:
+
    + <% user.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :full_name, class: 'form-label' %> + <%= form.text_field :full_name, class: 'form-control', required: true, minlength: 2, maxlength: 100 %> +
+ +
+ <%= form.label :email, class: 'form-label' %> + <%= form.email_field :email, class: 'form-control', required: true %> +
+ +
+ <%= form.label :role, class: 'form-label' %> + <%= form.select :role, options_for_select([['User', 'user'], ['Admin', 'admin']], user.role), {}, class: 'form-select' %> +
+ + <% if user.new_record? %> +
+ <%= form.label :password, class: 'form-label' %> + <%= form.password_field :password, class: 'form-control', required: true, minlength: 6 %> + Minimum 6 characters +
+ +
+ <%= form.label :password_confirmation, class: 'form-label' %> + <%= form.password_field :password_confirmation, class: 'form-control', required: true, minlength: 6 %> +
+ <% end %> + +
+ <%= form.label :avatar_url, 'Avatar URL (optional)', class: 'form-label' %> + <%= form.url_field :avatar_url, class: 'form-control' %> +
+ +
+ <%= form.label :avatar_image, 'Or upload avatar image', class: 'form-label' %> + <%= form.file_field :avatar_image, accept: 'image/jpeg,image/jpg,image/png,image/gif,image/webp', class: 'form-control' %> + JPEG, PNG, GIF or WebP, max 5MB +
+ + <% if user.avatar_image.attached? %> +
+

Current avatar:

+ <%= image_tag user.avatar_image, class: 'avatar-preview' %> +
+ <% end %> + +
+ <%= form.submit class: 'btn btn-primary' %> + <%= link_to 'Cancel', admin_users_path, class: 'btn btn-secondary' %> +
+<% end %> + diff --git a/app/views/admin/users/edit.html.erb b/app/views/admin/users/edit.html.erb new file mode 100644 index 000000000..f008fa5b1 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,13 @@ +
+
+
+
+

Edit User

+
+
+ <%= render 'form', user: @user, url: admin_user_path(@user) %> +
+
+
+
+ diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 000000000..742f53550 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,47 @@ +
+

Users

+ <%= link_to 'New User', new_admin_user_path, class: 'btn btn-primary' %> +
+ +
+
+
+ + + + + + + + + + + + + <% @users.each do |user| %> + + + + + + + + + <% end %> + +
AvatarFull NameEmailRoleCreated AtActions
<%= avatar_image_tag(user, class: 'avatar-small') %><%= user.full_name %><%= user.email %> + + <%= user.role.capitalize %> + + <%= user.created_at.strftime('%Y-%m-%d') %> +
+ <%= link_to 'Edit', edit_admin_user_path(user), class: 'btn btn-outline-primary' %> + <%= link_to 'Toggle Role', toggle_role_admin_user_path(user), method: :patch, class: 'btn btn-outline-warning' %> + <%= link_to 'Delete', admin_user_path(user), method: :delete, + confirm: 'Are you sure?', class: 'btn btn-outline-danger' %> +
+
+
+
+
+ diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..113b27839 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,13 @@ +
+
+
+
+

New User

+
+
+ <%= render 'form', user: @user, url: admin_users_path %> +
+
+
+
+ diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb new file mode 100644 index 000000000..ad3166b5d --- /dev/null +++ b/app/views/home/index.html.erb @@ -0,0 +1,15 @@ +
+
+
+
+

User Management System

+

Welcome to the User Management System. Please sign in or register to continue.

+
+ <%= link_to 'Sign In', new_user_session_path, class: 'btn btn-primary btn-lg' %> + <%= link_to 'Sign Up', new_user_registration_path, class: 'btn btn-outline-primary btn-lg' %> +
+
+
+
+
+ diff --git a/app/views/layouts/_flash_messages.html.erb b/app/views/layouts/_flash_messages.html.erb new file mode 100644 index 000000000..5d7890a40 --- /dev/null +++ b/app/views/layouts/_flash_messages.html.erb @@ -0,0 +1,7 @@ +<% flash.each do |type, message| %> + +<% end %> + diff --git a/app/views/layouts/_footer.html.erb b/app/views/layouts/_footer.html.erb new file mode 100644 index 000000000..0c7a08494 --- /dev/null +++ b/app/views/layouts/_footer.html.erb @@ -0,0 +1,6 @@ +
+
+

© <%= Time.zone.now.year %> Fullstack Developer Test. All rights reserved.

+
+
+ diff --git a/app/views/layouts/_navbar.html.erb b/app/views/layouts/_navbar.html.erb new file mode 100644 index 000000000..8f763b760 --- /dev/null +++ b/app/views/layouts/_navbar.html.erb @@ -0,0 +1,51 @@ + + diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb new file mode 100644 index 000000000..16bf5764d --- /dev/null +++ b/app/views/layouts/admin.html.erb @@ -0,0 +1,32 @@ + + + + Admin - Fullstack Developer + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= render 'layouts/navbar' %> + +
+ <%= render 'layouts/flash_messages' %> + +
+ +
+ <%= yield %> +
+
+
+ + <%= render 'layouts/footer' %> + + + diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..275cc88a3 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,25 @@ + + + + Fullstack Developer - User Management + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= stylesheet_link_tag "application", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= render 'layouts/navbar' %> + +
+ <%= render 'layouts/flash_messages' %> + + <%= yield %> +
+ + <%= render 'layouts/footer' %> + + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..f7a23e47c --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,14 @@ + + + + + + + + + <%= yield %> + + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..488b71ac9 --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1,2 @@ +<%= yield %> + diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 000000000..647c38c18 --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,73 @@ +
+
+
+
+

Edit Profile

+
+
+ <%= form_with model: @user, url: profile_path, local: true, data: { turbo: false } do |form| %> + <% if @user.errors.any? %> +
+
<%= pluralize(@user.errors.count, 'error') %> prohibited this profile from being saved:
+
    + <% @user.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :full_name, class: 'form-label' %> + <%= form.text_field :full_name, class: 'form-control', required: true, minlength: 2, maxlength: 100 %> +
+ +
+ <%= form.label :email, class: 'form-label' %> + <%= form.email_field :email, class: 'form-control', required: true %> +
+ +
+ <%= form.label :avatar_url, 'Avatar URL (optional)', class: 'form-label' %> + <%= form.url_field :avatar_url, class: 'form-control' %> +
+ +
+ <%= form.label :avatar_image, 'Or upload avatar image', class: 'form-label' %> + <%= form.file_field :avatar_image, accept: 'image/jpeg,image/jpg,image/png,image/gif,image/webp', class: 'form-control' %> + JPEG, PNG, GIF or WebP, max 5MB +
+ + <% if @user.avatar_image.attached? %> +
+

Current avatar:

+ <%= image_tag @user.avatar_image, class: 'avatar-preview' %> +
+ <% end %> + +
+ <%= form.label :password, 'New Password (leave blank if you do not want to change it)', class: 'form-label' %> + <%= form.password_field :password, class: 'form-control', autocomplete: 'new-password', minlength: 6 %> + Minimum 6 characters +
+ +
+ <%= form.label :password_confirmation, 'Confirm New Password', class: 'form-label' %> + <%= form.password_field :password_confirmation, class: 'form-control', autocomplete: 'new-password', minlength: 6 %> +
+ +
+ <%= form.label :current_password, 'Current Password (required to update)', class: 'form-label' %> + <%= form.password_field :current_password, class: 'form-control', autocomplete: 'current-password', required: true %> +
+ +
+ <%= form.submit 'Update Profile', class: 'btn btn-primary' %> + <%= link_to 'Cancel', profile_path, class: 'btn btn-secondary' %> +
+ <% end %> +
+
+
+
+ diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb new file mode 100644 index 000000000..0844a1216 --- /dev/null +++ b/app/views/profiles/show.html.erb @@ -0,0 +1,44 @@ +
+
+
+
+

My Profile

+ <%= link_to 'Edit', edit_profile_path, class: 'btn btn-sm btn-primary' %> +
+
+
+ <%= image_tag @user.display_avatar, class: 'avatar-preview' %> +
+ + + + + + + + + + + + + + + + + +
Full Name:<%= @user.full_name %>
Email:<%= @user.email %>
Role: + + <%= @user.role.capitalize %> + +
Member Since:<%= @user.created_at.strftime('%B %d, %Y') %>
+
+ <%= link_to 'Edit Profile', edit_profile_path, class: 'btn btn-primary' %> + <%= link_to 'Delete Account', profile_path, method: :delete, + confirm: 'Are you sure you want to delete your account? This action cannot be undone.', + class: 'btn btn-danger' %> +
+
+
+
+
+ diff --git a/app/views/users/registrations/new.html.erb b/app/views/users/registrations/new.html.erb new file mode 100644 index 000000000..c29e0f438 --- /dev/null +++ b/app/views/users/registrations/new.html.erb @@ -0,0 +1,57 @@ +
+
+
+
+

Sign Up

+
+
+ <%= form_with model: resource, as: resource_name, url: registration_path(resource_name), local: true, data: { turbo: false } do |form| %> + <% if resource.errors.any? %> +
+
<%= pluralize(resource.errors.count, 'error') %> prohibited this user from being saved:
+
    + <% resource.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= form.label :full_name, class: 'form-label' %> + <%= form.text_field :full_name, autofocus: true, class: 'form-control', required: true, minlength: 2, maxlength: 100 %> +
+ +
+ <%= form.label :email, class: 'form-label' %> + <%= form.email_field :email, autocomplete: 'email', class: 'form-control', required: true %> +
+ +
+ <%= form.label :password, class: 'form-label' %> + <% if @minimum_password_length %> + (<%= @minimum_password_length %> characters minimum) + <% end %> + <%= form.password_field :password, autocomplete: 'new-password', class: 'form-control', required: true, minlength: 6 %> +
+ +
+ <%= form.label :password_confirmation, class: 'form-label' %> + <%= form.password_field :password_confirmation, autocomplete: 'new-password', class: 'form-control', required: true, minlength: 6 %> +
+ +
+ <%= form.submit 'Sign Up', class: 'btn btn-primary' %> +
+ <% end %> + +
+ +
+ <%= link_to 'Sign in', new_user_session_path, class: 'btn btn-link' %> +
+
+
+
+
+ diff --git a/app/views/users/sessions/new.html.erb b/app/views/users/sessions/new.html.erb new file mode 100644 index 000000000..9008543ea --- /dev/null +++ b/app/views/users/sessions/new.html.erb @@ -0,0 +1,41 @@ +
+
+
+
+

Sign In

+
+
+ <%= form_with model: resource, as: resource_name, url: session_path(resource_name), local: true, data: { turbo: false } do |form| %> +
+ <%= form.label :email, class: 'form-label' %> + <%= form.email_field :email, autofocus: true, autocomplete: 'email', class: 'form-control', required: true %> +
+ +
+ <%= form.label :password, class: 'form-label' %> + <%= form.password_field :password, autocomplete: 'current-password', class: 'form-control', required: true %> +
+ + <% if devise_mapping.rememberable? %> +
+ <%= form.check_box :remember_me, class: 'form-check-input' %> + <%= form.label :remember_me, class: 'form-check-label' %> +
+ <% end %> + +
+ <%= form.submit 'Sign In', class: 'btn btn-primary' %> +
+ <% end %> + +
+ +
+ <%= link_to 'Sign up', new_user_registration_path, class: 'btn btn-link' %> + <%= link_to 'Forgot your password?', new_user_password_path, class: 'btn btn-link' %> +
+
+
+
+
+ diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 000000000..bcf26d9f8 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,21 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'bundle' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +require "rubygems" + +version = [">= 0.a"] + +str = IO.read(File.join(File.dirname(__FILE__), "../Gemfile")) +if str =~ /gem "bundler", "~> (.+)"/ || str =~ /gem "bundler", ">= (.+)"/ + version = ["~> #{$1}"] +end + +load Gem.bin_path("bundler", "bundle", *version) + diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..9c68bbaa5 --- /dev/null +++ b/bin/rails @@ -0,0 +1,13 @@ +#!/usr/bin/env ruby +# This command will automatically be run when you run "rails" with Rails 8 gems installed from the root directory of your application. + +ENGINE_ROOT = File.expand_path('../..', __dir__) +ENGINE_PATH = nil + +# Set up gems listed in the Gemfile. +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) +require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) + +require "rails/command" +require "rails/commands" + diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..f9ac53ed6 --- /dev/null +++ b/bin/setup @@ -0,0 +1,32 @@ +#!/usr/bin/env ruby +require "fileutils" + +# path to your application root. +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args) || abort("\n== Command #{args} failed ==") +end + +FileUtils.chdir APP_ROOT do + # This script is a way to setup or update your development environment automatically. + # This script is idempotent, so that you can run it at anytime and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system! "gem install bundler --conservative" + system("bundle check") || system!("bundle install") + + puts "\n== Installing JavaScript dependencies ==" + system! "npm install" + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + puts "\n== Restarting application server ==" + system! "bin/rails restart" +end + diff --git a/bin/yarn b/bin/yarn new file mode 100755 index 000000000..f2a3bb81a --- /dev/null +++ b/bin/yarn @@ -0,0 +1,18 @@ +#!/usr/bin/env ruby +APP_ROOT = File.expand_path('..', __dir__) +Dir.chdir(APP_ROOT) do + yarn = ENV["PATH"].split(File::PATH_SEPARATOR). + select { |dir| File.expand_path(dir) != __dir__ }. + product(["yarn", "yarn.cmd", "yarn.ps1"]). + map { |dir, file| File.join(dir, file) }. + find { |file| File.executable?(file) } + + if yarn + exec yarn, *ARGV + else + $stderr.puts "Yarn executable was not detected in the system." + $stderr.puts "Download Yarn at https://yarnpkg.com/en/docs/install" + exit 1 + end +end + diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..6b2906d0a --- /dev/null +++ b/config.ru @@ -0,0 +1,7 @@ +# This file is used by Rack-based servers to start the application. + +require_relative 'config/environment' + +run Rails.application +Rails.application.load_server + diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..be95d6d3b --- /dev/null +++ b/config/application.rb @@ -0,0 +1,42 @@ +require_relative 'boot' + +require 'rails/all' + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module FullstackDeveloper + class Application < Rails::Application + config.load_defaults 8.0 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + + # Set time zone + config.time_zone = 'UTC' + config.active_record.default_timezone = :utc + + # Generators configuration + config.generators do |g| + g.test_framework :rspec, + fixtures: true, + view_specs: false, + helper_specs: false, + routing_specs: false, + controller_specs: true, + request_specs: true + g.fixture_replacement :factory_bot, dir: 'spec/factories' + end + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..9dff944ee --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,5 @@ +ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) + +require 'bundler/setup' # Set up gems listed in the Gemfile. +require 'bootsnap/setup' # Speed up boot time by caching expensive operations. + diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..ca1aefc79 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,12 @@ +development: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %> + +test: + adapter: test + +production: + adapter: redis + url: <%= ENV.fetch("REDIS_URL") { "redis://redis:6379/1" } %> + channel_prefix: fullstack_developer_production + diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..e2bde8557 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,21 @@ +default: &default + adapter: postgresql + encoding: unicode + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + username: <%= ENV.fetch("DATABASE_USER") { "postgres" } %> + password: <%= ENV.fetch("DATABASE_PASSWORD") { "postgres" } %> + host: <%= ENV.fetch("DATABASE_HOST") { "localhost" } %> + port: <%= ENV.fetch("DATABASE_PORT") { 5432 } %> + +development: + <<: *default + database: fullstack_developer_development + +test: + <<: *default + database: fullstack_developer_test + +production: + <<: *default + database: <%= ENV.fetch("DATABASE_NAME") { "fullstack_developer_production" } %> + diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..f467c11e4 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,6 @@ +# Load the Rails application. +require_relative 'application' + +# Initialize the Rails application. +Rails.application.initialize! + diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 000000000..fcd711cb5 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,78 @@ +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # In the development environment your application's code is reloaded any time + # it changes. This slows down response time but is perfect for development + # since you don't have to restart the web server when you make code changes. + config.cache_classes = false + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable caching. By default caching is disabled. + # Run rails dev:cache to toggle caching. + if Rails.root.join('tmp/caching-dev.txt').exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + + config.cache_store = :memory_store + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{2.days.to_i}" + } + else + config.action_controller.perform_caching = false + + config.cache_store = :null_store + end + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.variant_processor = :mini_magick + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + config.action_mailer.perform_caching = false + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # ActionMailer configuration + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } + + # ActionCable configuration + config.action_cable.url = 'ws://localhost:3000/cable' + config.action_cable.allowed_request_origins = ['http://localhost:3000'] +end + diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..570c7f0fc --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,97 @@ +require 'active_support/core_ext/integer/time' + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.cache_classes = true + + # Eager load code on boot. This eager loads most of Rails and + # your application in memory, allowing both threaded web servers + # and those relying on copy on write to perform better. + # Rake tasks automatically ignore this option for performance. + config.eager_load = true + + # Full error reports are disabled and caching is turned on. + config.consider_all_requests_local = false + config.action_controller.perform_caching = true + + # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] + # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). + # config.require_master_key = true + + # Disable serving static files from the `/public` folder by default since + # Apache or NGINX already handles this. + config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? + + # Compress CSS using a preprocessor. + # config.assets.css_compressor = :sass + + # Do not fallback to assets pipeline if a precompiled asset is missing. + config.assets.compile = false + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = 'http://assets.example.com' + + # Specifies the header that your server uses for sending files. + # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache + # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.variant_processor = :mini_magick + + # Mount Action Cable outside main process or domain. + # config.action_cable.mount_path = nil + # config.action_cable.url = 'wss://example.com/cable' + # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/.*\.example\.com/ ] + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Include generic and useful information about system operation, but avoid logging too much + # information to avoid inadvertent exposure of personally identifiable information (PII). + config.log_level = :info + + # Prepend all log lines with the following tags. + config.log_tags = [ :request_id ] + + # Use a different cache store in production. + # config.cache_store = :mem_cache_store + + # Use a real queuing backend for Active Job (and separate queues per environment). + # config.active_job.queue_adapter = :sidekiq + # config.active_job.queue_name_prefix = "fullstack_developer_production" + + config.action_mailer.perform_caching = false + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Enable locale fallbacks for I18n (makes lookups for any locale fall back to + # the I18n.default_locale when a translation cannot be found). + config.i18n.fallback = true + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Use default logging formatter so that PID and timestamp are not suppressed. + config.log_formatter = ::Logger::Formatter.new + + # Use a different logger for distributed setups. + # require 'syslog/logger' + # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') + + if ENV['RAILS_LOG_TO_STDOUT'].present? + logger = ActiveSupport::Logger.new(STDOUT) + logger.formatter = config.log_formatter + config.logger = ActiveSupport::TaggedLogging.new(logger) + end + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # ActionMailer configuration + config.action_mailer.default_url_options = { host: ENV.fetch('HOST', 'localhost') } +end + diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..8526230f6 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,70 @@ +require 'active_support/core_ext/integer/time' + +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Turn false under Spring and add config.action_view.cache_template_loading = true. + config.cache_classes = true + + # Eager loading loads your whole application. When running a single test locally, + # this probably isn't necessary. It's a good idea to do in a continuous integration + # system, or in some way before deploying your code to production. + config.eager_load = ENV['CI'].present? + + # Configure public file server for tests with Cache-Control for performance. + config.public_file_server.enabled = true + config.public_file_server.headers = { + 'Cache-Control' => "public, max-age=#{1.hour.to_i}" + } + + # Show full error reports and disable caching. + config.consider_all_requests_local = true + config.action_controller.perform_caching = false + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.variant_processor = :mini_magick + + config.active_storage.service = :test + + # Disable ActionMailer in tests + config.action_mailer.perform_caching = false + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :stderr + + # Raise exceptions for disallowed deprecations. + config.active_support.disallowed_deprecation = :raise + + # Tell Active Support which deprecation messages to disallow. + config.active_support.disallowed_deprecation_warnings = [] + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # ActionMailer configuration + config.action_mailer.default_url_options = { host: 'localhost', port: 3000 } +end + diff --git a/config/importmap.rb b/config/importmap.rb new file mode 100644 index 000000000..1524d5de7 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,13 @@ +# Pin npm packages by running ./bin/importmap + +pin "application" +pin "@hotwired/turbo-rails", to: "turbo.min.js" +pin "@hotwired/stimulus", to: "stimulus.min.js" +pin "@hotwired/stimulus-loading", to: "stimulus-loading.js" +pin "@rails/actioncable", to: "actioncable.esm.js" +pin "bootstrap", to: "https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js" +pin "@popperjs/core", to: "https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.8/dist/umd/popper.min.js" + +pin_all_from "app/javascript/controllers", under: "controllers" +pin_all_from "app/javascript/channels", under: "channels" + diff --git a/config/initializers/action_cable.rb b/config/initializers/action_cable.rb new file mode 100644 index 000000000..9a9a7e87c --- /dev/null +++ b/config/initializers/action_cable.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +# ActionCable will be eager loaded in production, so it's recommended to set +# the adapter here instead of in config/cable.yml +Rails.application.config.action_cable.url = '/cable' +Rails.application.config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/] + diff --git a/config/initializers/active_job.rb b/config/initializers/active_job.rb new file mode 100644 index 000000000..dab90d27c --- /dev/null +++ b/config/initializers/active_job.rb @@ -0,0 +1,2 @@ +Rails.application.config.active_job.queue_adapter = :sidekiq + diff --git a/config/initializers/active_storage.rb b/config/initializers/active_storage.rb new file mode 100644 index 000000000..f4dcad790 --- /dev/null +++ b/config/initializers/active_storage.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +Rails.application.config.active_storage.variant_processor = :mini_magick + diff --git a/config/initializers/application_controller_renderer.rb b/config/initializers/application_controller_renderer.rb new file mode 100644 index 000000000..3169ea91d --- /dev/null +++ b/config/initializers/application_controller_renderer.rb @@ -0,0 +1,9 @@ +# Be sure to restart your server when you modify this file. + +# ActiveSupport::Reloader.to_prepare do +# ApplicationController.renderer.defaults.merge!( +# http_host: 'example.org', +# https: false +# ) +# end + diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..83b9093e2 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,13 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = '1.0' + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path + +# Precompile additional assets. +# application.js, application.css, and all non-JS/CSS in the app/assets +# folder are already added. +# Rails.application.config.assets.precompile += %w( admin.js admin.css ) + diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 000000000..7e7639ebe --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,270 @@ +# frozen_string_literal: true + +# Assuming you have not yet modified this file, each configuration option below +# is set to its default value. Note that some are commented out while others +# are not: uncommented lines are intended to protect your configuration from +# breaking changes in upgrades (i.e., in the event that future versions of +# Devise change the default values for those options). +# +# Use this hook to configure devise mailer, warden hooks and so forth. +# Many of these configuration options can be set straight in your model. +Devise.setup do |config| + # The secret key used by Devise. Devise uses this key to generate + # random tokens. Changing this key will render invalid all existing + # confirmation, reset password and unlock tokens in the database. + # Devise will use the `secret_key_base` as its `secret_key` + # by default. You can change it below and use your own secret key. + # config.secret_key = '...' + + # ==> Controller configuration + # Configure the parent class to the devise controllers. + # config.parent_controller = 'DeviseController' + + # ==> Mailer Configuration + # Configure the e-mail address which will be shown in Devise::Mailer, + # note that it will be overwritten if you use your own mailer class + # with default "from" parameter. + config.mailer_sender = 'please-change-me-at-config-initializers-devise@example.com' + + # Configure the class responsible to send e-mails. + # config.mailer = 'Devise::Mailer' + + # Configure the parent class responsible to send e-mails. + # config.parent_mailer = 'ApplicationMailer' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :mongoid (required for MongoDB) The ORMs that are supported by default + # are ActiveModel::Devise and ActiveModel::Mongoid. + config.orm = :active_record + + # ==> Configuration for any authentication mechanism + # Configure which keys are used when authenticating a user. The default is + # just :email. You can configure it to use [:username, :subdomain], so for + # authenticating a user, both parameters are required. Remember that those + # parameters are used only when authenticating and not when retrieving from + # session. If you need permissions, you should implement that in a before filter. + # You can also supply a hash where the value is a boolean determining whether + # or not authentication should be aborted when the value is not present. + # config.authentication_keys = [:email] + + # Configure parameters from the request object used for authentication. Each entry + # given should be a request method and it will automatically be passed to the + # find_for_authentication method and used in conditions. You can also supply + # a hash where the value is a boolean determining whether or not authentication + # should be aborted when the value is not present. + # config.request_keys = [] + + # Configure which authentication keys should be case-insensitive. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.case_insensitive_keys = [:email] + + # Configure which authentication keys should have whitespace stripped. + # These keys will be downcased upon creating or modifying a user and when used + # to authenticate or find a user. Default is :email. + config.strip_whitespace_keys = [:email] + + # Tell if authentication through request.params is enabled. True by default. + # It can be set to an array that will enable params authentication only for the + # given strategies, for example, `config.params_authenticatable = [:database]` will + # enable params authentication only for the database authentication strategy. + # config.params_authenticatable = true + + # Tell if authentication through HTTP Auth is enabled. False by default. + # It can be set to an array that will enable http authentication only for the + # given strategies, for example, `config.http_authenticatable = [:database]` will + # enable http authentication only for the database authentication strategy. + # The supported strategies are: + # :database = Support basic authentication with authentication key + password + # config.http_authenticatable = false + + # If 401 status code should be returned for AJAX requests. True by default. + # config.http_authenticatable_on_xhr = true + + # The realm used in Http Basic Authentication. 'Application' by default. + # config.http_authentication_realm = 'Application' + + # It will change confirmation, password recovery and other workflows + # to behave the same regardless if the e-mail was registered or not. + # False by default. + # config.paranoid = true + + # By default Devise will store the user in session. You can skip storage for + # :http_auth and :database_auth strategies. + # config.skip_session_storage = [:http_auth] + + # By default, Devise cleans up the CSRF token on authentication to + # avoid CSRF token fixation attacks. This means that, when using AJAX + # requests for sign in and sign up, you need to get a new CSRF token + # from the server. You can disable this option if you continue to use + # the legacy `authenticity_token` in the model for `form_with`. + # config.clean_up_csrf_token_on_authentication = true + + # ==> Configuration for :database_authenticatable + # For bcrypt, this is the cost for hashing the password and defaults to 12. If + # using other hashers, it sets how many times you want the password to be hashed. + # The number of stretches used for generating the hashed password are stored + # with the hashed password. This allows you to change the hashing algorithm + # without invalidating existing passwords. + # + # Limiting the stretches to just one in testing will increase the performance of + # your test suite dramatically. However, it is RECOMMENDED to not use a value less + # than 12 in other environments. Note that, for bcrypt (the default hasher), the + # cost increases exponentially with the number of stretches (e.g. a value of 20 + # is already extremely slow: approx. 1 second per password). + config.stretches = Rails.env.test? ? 1 : 12 + + # Set up a pepper to generate the hashed password. + # config.pepper = '...' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changelog_notification = false + + # Send a notification email when the user's password is changed. + # config.send_password_change_notification = false + + # ==> Configuration for :confirmable + # A period that the user is allowed to access the website even without + # confirming their account. For instance, if set to 2.days, the user will be + # able to access the website for two days without confirming their account, + # access will be blocked just in the few hours before the period expires. + # You can also set it to nil, which will allow the user to access the website + # without confirming their account. + # Default is 0.days, meaning the user cannot access the website without + # confirming their account. + # config.allow_unconfirmed_access_for = 0.days + + # A period that the user is allowed to confirm their account before their + # token becomes invalid. For example, if set to 3.days, the user can confirm + # their account within 3 days after the mail was sent, but on the fourth day + # their account can no longer be confirmed with the token inside the email. + # This is used to reset the password token as well. + # Default is nil, meaning there is no restriction on how long a user can take + # before confirming their account. + # config.confirm_within = 3.days + + # If true, requires any email changes to be confirmed (exactly the same way as + # initial account confirmation) to be applied. Requires additional unconfirmed_email + # db field (see migrations). Until confirmed, new email is stored in + # unconfirmed_email field, and copied to email field on successful confirmation. + config.reconfirmable = true + + # Defines which key will be used when confirming an account + # config.confirmation_keys = [:email] + + # ==> Configuration for :rememberable + # The time the user will be remembered without asking for credentials again. + # config.remember_for = 2.weeks + + # Invalidates all the remember me tokens when the user signs out. + config.expire_all_remember_me_on_sign_out = true + + # If true, extends the user's remember period when remembered via cookie. + # config.extend_remember_period = false + + # Options to be passed to the created cookie. For instance, you can set + # secure: true in order to force SSL only cookies. + # config.rememberable_options = {} + + # ==> Configuration for :validatable + # Range for password length. + config.password_length = 6..128 + + # Email regex used to validate email formats. It simply asserts that + # one (and only one) @ exists in the given string. This is mainly + # to provide user feedback and not to assert the e-mail validity. + config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ + + # ==> Configuration for :timeoutable + # The time you want to timeout the user after inactivity. + # config.timeout_in = 30.minutes + + # ==> Configuration for :lockable + # Defines which strategy will be used to lock an account. + # :failed_attempts = Locks an account after a number of failed attempts to sign in. + # :unlock_token = Defines a strategy for unlocking an account using a token. + # :unlock_strategy = :email + # :unlock_strategy = :time # Unlock after a certain time (see :unlock_in) + # :unlock_strategy = :both # Unlock after a certain time and email confirmation + # config.maximum_attempts = 10 + # config.unlock_strategy = :failed_attempts + # config.lock_strategy = :unlock_token + # config.unlock_in = 1.hour + + # ==> Configuration for :recoverable + # + # Defines which key will be used when recovering the password for an account + # config.recovery_keys = [:email] + + # ==> Configuration for :registerable + # When you set this to true, you can create users without confirmation + # For direct sign up + config.sign_up_enabled = true + + # ==> Configuration for :encryptable + # Allow you to use another hashing or encryption algorithm besides bcrypt (default). + # You can use :sha1, :sha512 or algorithms from others authentication tools as + # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 + # for default behavior) and :restful_authentication_sha1 (then you should set + # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). + # + # Require the `devise-encryptable` gem when using anything other than bcrypt + # config.encryptor = :sha512 + + # ==> Scopes configuration + # Turn scoped views on. Before rendering "sessions/new", it will first check for + # "users/sessions/new". It's turned off by default because it's slower if you + # are using only default views. + # config.scoped_views = false + + # Configure the default scope given to Warden. By default it's the first + # devise role declared in your routes (usually :user). + # config.default_scope = :user + + # Set this configuration to false if you want /users/sign_out to sign out + # only the current scope. By default, Devise signs out all scopes. + # config.sign_out_all_scopes = true + + # ==> Navigation configuration + # Lists the formats that should be treated as navigational. Formats like + # :html, should redirect to the sign in page when the user does not have + # access, but formats like :xml or :json, should return 401. + # + # If you have any extra navigational formats, like :html5, :html, or :json, add + # them to the navigational formats lists. + # + # The "*/*" below is required to match all user types. + # config.navigational_formats = ['*/*', :html] + + # The default HTTP method used to sign out a resource. + # config.sign_out_via = :delete + + # ==> OmniAuth + # Add a new OmniAuth provider. Check the wiki for more information on setting + # up on your models and hooks. + # config.omni_auth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + + # ==> Warden configuration + # If you want to use other strategies, that are not supported by Devise, or + # change the failure app, you can configure them inside the config.warden block. + # + # config.warden do |manager| + # manager.intercept_401 = false + # manager.default_strategies(scope: :user).unshift :some_external_strategy + # end + + # ==> Turbo configuration + config.navigational_formats = ['*/*', :html, :turbo_stream] + + # ==> Configuration for :registerable + # When set to false, does not sign a user in automatically after their password is + # reset (default: true). + # config.sign_in_after_reset_password = true + + # ==> Configuration for :registerable + # When set to false, does not sign a user in automatically after they register. + # (default: true) + # config.sign_in_after_sign_up = true +end + diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..8046f38d8 --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,9 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn +] + diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..2f12d050c --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,17 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, '\1en' +# inflect.singular /^(ox)en/i, '\1' +# inflect.irregular 'person', 'people' +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym 'RESTful' +# end + diff --git a/config/initializers/pundit.rb b/config/initializers/pundit.rb new file mode 100644 index 000000000..9d553e808 --- /dev/null +++ b/config/initializers/pundit.rb @@ -0,0 +1,20 @@ +# frozen_string_literal: true + +# Pundit configuration +module PunditHelper + extend ActiveSupport::Concern + + included do + include Pundit::Authorization + + rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized + end + + private + + def user_not_authorized + flash[:alert] = 'You are not authorized to perform this action.' + redirect_back(fallback_location: root_path) + end +end + diff --git a/config/initializers/rubocop.rb b/config/initializers/rubocop.rb new file mode 100644 index 000000000..39b4921df --- /dev/null +++ b/config/initializers/rubocop.rb @@ -0,0 +1,2 @@ +# Rubocop configuration will be in .rubocop.yml + diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb new file mode 100644 index 000000000..f8f03b413 --- /dev/null +++ b/config/initializers/sidekiq.rb @@ -0,0 +1,10 @@ +# frozen_string_literal: true + +Sidekiq.configure_server do |config| + config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') } +end + +Sidekiq.configure_client do |config| + config.redis = { url: ENV.fetch('REDIS_URL', 'redis://localhost:6379/0') } +end + diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..cd9d2af70 --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,3 @@ +en: + hello: "Hello world" + diff --git a/config/master.key.example b/config/master.key.example new file mode 100644 index 000000000..e20fe9f29 --- /dev/null +++ b/config/master.key.example @@ -0,0 +1,4 @@ +# Copy this file to config/master.key and set your secret key +# Or use environment variable SECRET_KEY_BASE +# Generate with: rails secret + diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..c4263de55 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,39 @@ +# Puma can serve each request in a thread from an internal thread pool. +# The `threads` method setting takes two numbers: a minimum and maximum. +# Any libraries that use thread pools should be configured to match +# the maximum value specified for Puma. Default is set to 5 threads for minimum +# and maximum; this matches the default thread size of Active Record. +# +max_threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } +min_threads_count = ENV.fetch("RAILS_MIN_THREADS") { max_threads_count } +threads min_threads_count, max_threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +# +port ENV.fetch("PORT") { 3000 } + +# Specifies the `environment` that Puma will run in. +# +environment ENV.fetch("RAILS_ENV") { "development" } + +# Specifies the `pidfile` that Puma will use. +pidfile ENV.fetch("PIDFILE") { "tmp/pids/server.pid" } + +# Specifies the number of `workers` to boot in clustered mode. +# Workers are forked web server processes. If using threads and workers together +# the concurrency of the application would be max `threads` * `workers`. +# Workers do not work on JRuby or Windows (both of which do not support +# processes). +# +# workers ENV.fetch("WEB_CONCURRENCY") { 2 } + +# Use the `preload_app!` method when specifying a `workers` number. +# This directive tells Puma to first boot the application and load code +# before forking the application. This takes advantage of Copy On Write +# process behavior so workers use less memory. +# +# preload_app! + +# Allow puma to be restarted by `rails restart` command. +plugin :tmp_restart + diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..94db3f785 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,38 @@ +Rails.application.routes.draw do + # Health check + get 'health', to: 'health#check' + + # Root + root 'home#index' + + # Devise routes + devise_for :users, controllers: { + registrations: 'users/registrations', + sessions: 'users/sessions' + } + + # User profile + resource :profile, only: [:show, :edit, :update, :destroy], controller: 'profiles' + + # Admin namespace + namespace :admin do + root 'dashboards#show' + get 'dashboard', to: 'dashboards#show' + + resources :users, except: [:show] do + member do + patch :toggle_role + end + end + + resources :imports, only: [:index, :new, :create, :show] do + member do + get :status + end + end + end + + # ActionCable + mount ActionCable.server => '/cable' +end + diff --git a/config/secrets.yml b/config/secrets.yml new file mode 100644 index 000000000..f82258d41 --- /dev/null +++ b/config/secrets.yml @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Your secret key is used for verifying the integrity of signed cookies. +# If you change this key, all old signed cookies will become invalid! + +# Make sure the secret is at least 30 characters and all random, +# no regular words or you'll be exposed to dictionary attacks. +# You can use `rails secret` to generate a secure secret key. + +# Make sure the secrets in this file are kept private +# if you're sharing your code publicly. + +development: + secret_key_base: <%= ENV.fetch("SECRET_KEY_BASE") { "development_secret_key_base_#{Rails.application.class.name[0..-5].underscore}_development" } %> + +test: + secret_key_base: <%= ENV.fetch("SECRET_KEY_BASE") { "test_secret_key_base_#{Rails.application.class.name[0..-5].underscore}_test" } %> + +# Do not keep production secrets in the unencrypted secrets file. +# Instead, either use the encrypted secrets file (config/secrets.yml.enc), +# or environment variables. + +production: + secret_key_base: <%= ENV.fetch("SECRET_KEY_BASE") { raise "SECRET_KEY_BASE environment variable is not set" } %> + diff --git a/config/sidekiq.yml b/config/sidekiq.yml new file mode 100644 index 000000000..a6dc5045d --- /dev/null +++ b/config/sidekiq.yml @@ -0,0 +1,4 @@ +:concurrency: 5 +:queues: + - default + diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..9312ba141 --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,8 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + diff --git a/db/migrate/20240101000001_devise_create_users.rb b/db/migrate/20240101000001_devise_create_users.rb new file mode 100644 index 000000000..209c525e5 --- /dev/null +++ b/db/migrate/20240101000001_devise_create_users.rb @@ -0,0 +1,30 @@ +# frozen_string_literal: true + +class DeviseCreateUsers < ActiveRecord::Migration[8.0] + def change + create_table :users do |t| + ## Database authenticatable + t.string :email, null: false, default: '' + t.string :encrypted_password, null: false, default: '' + + ## Recoverable + t.string :reset_password_token + t.datetime :reset_password_sent_at + + ## Rememberable + t.datetime :remember_created_at + + ## User fields + t.string :full_name, null: false + t.integer :role, default: 0, null: false + t.string :avatar_url + + t.timestamps null: false + end + + add_index :users, :email, unique: true + add_index :users, :reset_password_token, unique: true + add_index :users, :role + end +end + diff --git a/db/migrate/20240101000002_create_active_storage_tables.active_storage.rb b/db/migrate/20240101000002_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..1e0e2c18f --- /dev/null +++ b/db/migrate/20240101000002_create_active_storage_tables.active_storage.rb @@ -0,0 +1,37 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[8.0] + def change + create_table :active_storage_blobs do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum + + t.datetime :created_at, null: false + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false + t.references :blob, null: false + + t.datetime :created_at, null: false + + t.index [ :record_type, :record_id, :name, :blob_id ], name: 'index_active_storage_attachments_uniqueness', unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records do |t| + t.belongs_to :blob, null: false, index: false + t.string :variation_digest, null: false + + t.index [ :blob_id, :variation_digest ], name: 'index_active_storage_variant_records_uniqueness', unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end +end + diff --git a/db/migrate/20240101000003_create_user_imports.rb b/db/migrate/20240101000003_create_user_imports.rb new file mode 100644 index 000000000..accce31bb --- /dev/null +++ b/db/migrate/20240101000003_create_user_imports.rb @@ -0,0 +1,19 @@ +class CreateUserImports < ActiveRecord::Migration[8.0] + def change + create_table :user_imports do |t| + t.references :user, null: false, foreign_key: true + t.integer :status, default: 0, null: false + t.integer :total_rows, default: 0 + t.integer :processed_rows, default: 0 + t.integer :success_count, default: 0 + t.integer :error_count, default: 0 + t.json :error_messages, default: [] + + t.timestamps + end + + add_index :user_imports, :status + add_index :user_imports, :user_id + end +end + diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..bbb86ff98 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,70 @@ +# This file is auto-generated from the database schema. Running `rails db:schema:dump` will update this file automatically. + +ActiveRecord::Schema[8.0].define(version: 2024_01_01_000003) do + # These are extensions that must be enabled in order to support this database + enable_extension "plpgsql" + + create_table "active_storage_attachments", force: :cascade do |t| + t.string "name", null: false + t.string "record_type", null: false + t.bigint "record_id", null: false + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.string "key", null: false + t.string "filename", null: false + t.string "content_type" + t.text "metadata" + t.string "service_name", null: false + t.bigint "byte_size", null: false + t.string "checksum" + t.datetime "created_at", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + t.index ["blob_id"], name: "index_active_storage_variant_records_on_blob_id" + end + + create_table "user_imports", force: :cascade do |t| + t.bigint "user_id", null: false + t.integer "status", default: 0, null: false + t.integer "total_rows", default: 0 + t.integer "processed_rows", default: 0 + t.integer "success_count", default: 0 + t.integer "error_count", default: 0 + t.json "error_messages", default: [] + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["status"], name: "index_user_imports_on_status" + t.index ["user_id"], name: "index_user_imports_on_user_id" + end + + create_table "users", force: :cascade do |t| + t.string "email", default: "", null: false + t.string "encrypted_password", default: "", null: false + t.string "reset_password_token" + t.datetime "reset_password_sent_at" + t.datetime "remember_created_at" + t.string "full_name", null: false + t.integer "role", default: 0, null: false + t.string "avatar_url" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + t.index ["role"], name: "index_users_on_role" + end + + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "user_imports", "users" +end + diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..47a521096 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,26 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). + +# Create admin user +admin = User.find_or_create_by(email: 'admin@example.com') do |user| + user.full_name = 'Admin User' + user.password = 'password123' + user.password_confirmation = 'password123' + user.role = :admin +end + +puts "Admin user created: #{admin.email}" + +# Create some sample users +10.times do |i| + User.find_or_create_by(email: "user#{i + 1}@example.com") do |user| + user.full_name = Faker::Name.name + user.password = 'password123' + user.password_confirmation = 'password123' + user.role = :user + end +end + +puts "Sample users created" + diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..3a3d63381 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,73 @@ +version: '3.8' + +services: + db: + image: postgres:15 + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: fullstack_developer_development + volumes: + - postgres_data:/var/lib/postgresql/data + ports: + - "5432:5432" + healthcheck: + test: ["CMD-SHELL", "pg_isready -U postgres"] + interval: 10s + timeout: 5s + retries: 5 + + redis: + image: redis:7-alpine + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 5 + + web: + build: . + command: bash -c "rm -f tmp/pids/server.pid && rails db:create db:migrate && rails server -b 0.0.0.0" + volumes: + - .:/app + - bundle_cache:/usr/local/bundle + - node_modules:/app/node_modules + ports: + - "3000:3000" + depends_on: + db: + condition: service_healthy + redis: + condition: service_healthy + environment: + DATABASE_HOST: db + DATABASE_USER: postgres + DATABASE_PASSWORD: postgres + REDIS_URL: redis://redis:6379/0 + RAILS_ENV: development + stdin_open: true + tty: true + + sidekiq: + build: . + command: bundle exec sidekiq -C config/sidekiq.yml + volumes: + - .:/app + - bundle_cache:/usr/local/bundle + depends_on: + - db + - redis + environment: + DATABASE_HOST: db + DATABASE_USER: postgres + DATABASE_PASSWORD: postgres + REDIS_URL: redis://redis:6379/0 + RAILS_ENV: development + +volumes: + postgres_data: + bundle_cache: + node_modules: + diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/package.json b/package.json new file mode 100644 index 000000000..5ff2cbe8e --- /dev/null +++ b/package.json @@ -0,0 +1,19 @@ +{ + "name": "fullstack-developer", + "version": "1.0.0", + "private": true, + "dependencies": { + "@hotwired/turbo-rails": "^8.0.0", + "@hotwired/stimulus": "^3.2.0", + "@rails/actioncable": "^8.0.0", + "bootstrap": "^5.3.0" + }, + "scripts": { + "build": "esbuild app/javascript/*.js --bundle --sourcemap --outdir=app/assets/builds", + "watch": "esbuild app/javascript/*.js --bundle --sourcemap --outdir=app/assets/builds --watch" + }, + "devDependencies": { + "esbuild": "^0.19.0" + } +} + diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 000000000..e69de29bb diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..9450c3efc --- /dev/null +++ b/public/robots.txt @@ -0,0 +1,4 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: + diff --git a/spec/controllers/admin/users_controller_spec.rb b/spec/controllers/admin/users_controller_spec.rb new file mode 100644 index 000000000..904ffb406 --- /dev/null +++ b/spec/controllers/admin/users_controller_spec.rb @@ -0,0 +1,107 @@ +require 'rails_helper' + +RSpec.describe Admin::UsersController, type: :controller do + let(:admin) { create(:user, :admin) } + let(:regular_user) { create(:user) } + + before { sign_in admin } + + describe 'GET #index' do + it 'returns a successful response' do + get :index + expect(response).to be_successful + end + + it 'assigns all users' do + get :index + expect(assigns(:users)).to include(admin, regular_user) + end + end + + describe 'GET #new' do + it 'returns a successful response' do + get :new + expect(response).to be_successful + end + end + + describe 'POST #create' do + context 'with valid params' do + let(:valid_params) do + { + user: { + full_name: 'Test User', + email: 'test@example.com', + password: 'password123', + password_confirmation: 'password123', + role: 'user' + } + } + end + + it 'creates a new user' do + expect { + post :create, params: valid_params + }.to change(User, :count).by(1) + end + + it 'redirects to users index' do + post :create, params: valid_params + expect(response).to redirect_to(admin_users_path) + end + end + + context 'with invalid params' do + let(:invalid_params) do + { + user: { + full_name: '', + email: 'invalid' + } + } + end + + it 'does not create a user' do + expect { + post :create, params: invalid_params + }.not_to change(User, :count) + end + + it 'renders new template' do + post :create, params: invalid_params + expect(response).to render_template(:new) + end + end + end + + describe 'PATCH #toggle_role' do + it 'toggles user role' do + expect { + patch :toggle_role, params: { id: regular_user.id } + regular_user.reload + }.to change { regular_user.role }.from('user').to('admin') + end + + it 'prevents admin from changing own role' do + patch :toggle_role, params: { id: admin.id } + expect(response).to redirect_to(admin_users_path) + expect(flash[:alert]).to be_present + end + end + + describe 'DELETE #destroy' do + it 'deletes the user' do + user_to_delete = create(:user) + expect { + delete :destroy, params: { id: user_to_delete.id } + }.to change(User, :count).by(-1) + end + + it 'prevents admin from deleting own account' do + delete :destroy, params: { id: admin.id } + expect(response).to redirect_to(admin_users_path) + expect(flash[:alert]).to be_present + end + end +end + diff --git a/spec/factories/user_imports.rb b/spec/factories/user_imports.rb new file mode 100644 index 000000000..d86e9c7f9 --- /dev/null +++ b/spec/factories/user_imports.rb @@ -0,0 +1,31 @@ +FactoryBot.define do + factory :user_import do + association :user, factory: :user, strategy: :create + status { :pending } + total_rows { 0 } + processed_rows { 0 } + success_count { 0 } + error_count { 0 } + error_messages { [] } + + trait :processing do + status { :processing } + total_rows { 10 } + processed_rows { 5 } + end + + trait :completed do + status { :completed } + total_rows { 10 } + processed_rows { 10 } + success_count { 10 } + error_count { 0 } + end + + trait :failed do + status { :failed } + error_messages { ['Import failed'] } + end + end +end + diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..c8730a12e --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,18 @@ +FactoryBot.define do + factory :user do + full_name { Faker::Name.name } + email { Faker::Internet.unique.email } + password { 'password123' } + password_confirmation { 'password123' } + role { :user } + + trait :admin do + role { :admin } + end + + trait :with_avatar_url do + avatar_url { Faker::Internet.url } + end + end +end + diff --git a/spec/fixtures/.keep b/spec/fixtures/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/spec/models/user_import_spec.rb b/spec/models/user_import_spec.rb new file mode 100644 index 000000000..65587d766 --- /dev/null +++ b/spec/models/user_import_spec.rb @@ -0,0 +1,57 @@ +require 'rails_helper' + +RSpec.describe UserImport, type: :model do + describe 'validations' do + it { is_expected.to belong_to(:user) } + it { is_expected.to validate_presence_of(:spreadsheet_file) } + end + + describe 'enums' do + it { is_expected.to define_enum_for(:status).with_values(pending: 0, processing: 1, completed: 2, failed: 3) } + end + + describe '#progress_percentage' do + context 'when total_rows is zero' do + let(:import) { create(:user_import, total_rows: 0) } + + it 'returns 0' do + expect(import.progress_percentage).to eq(0) + end + end + + context 'when processed_rows is less than total_rows' do + let(:import) { create(:user_import, total_rows: 10, processed_rows: 5) } + + it 'returns correct percentage' do + expect(import.progress_percentage).to eq(50.0) + end + end + end + + describe '#finished?' do + context 'when status is completed' do + let(:import) { create(:user_import, :completed) } + + it 'returns true' do + expect(import.finished?).to be true + end + end + + context 'when status is failed' do + let(:import) { create(:user_import, :failed) } + + it 'returns true' do + expect(import.finished?).to be true + end + end + + context 'when status is processing' do + let(:import) { create(:user_import, :processing) } + + it 'returns false' do + expect(import.finished?).to be false + end + end + end +end + diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 000000000..2cceb47c1 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,71 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + describe 'validations' do + it { is_expected.to validate_presence_of(:full_name) } + it { is_expected.to validate_length_of(:full_name).is_at_least(2).is_at_most(100) } + it { is_expected.to validate_presence_of(:email) } + it { is_expected.to validate_uniqueness_of(:email).case_insensitive } + end + + describe 'associations' do + it { is_expected.to have_many(:user_imports).dependent(:destroy) } + end + + describe 'enums' do + it { is_expected.to define_enum_for(:role).with_values(user: 0, admin: 1) } + end + + describe '#admin?' do + context 'when user is admin' do + let(:user) { create(:user, :admin) } + + it 'returns true' do + expect(user.admin?).to be true + end + end + + context 'when user is not admin' do + let(:user) { create(:user) } + + it 'returns false' do + expect(user.admin?).to be false + end + end + end + + describe '#display_avatar' do + context 'when user has attached avatar' do + let(:user) { create(:user) } + + before do + user.avatar_image.attach( + io: File.open(Rails.root.join('spec', 'fixtures', 'test.png')), + filename: 'test.png', + content_type: 'image/png' + ) + end + + it 'returns attached image' do + expect(user.display_avatar).to eq(user.avatar_image) + end + end + + context 'when user has avatar_url' do + let(:user) { create(:user, :with_avatar_url) } + + it 'returns avatar_url' do + expect(user.display_avatar).to eq(user.avatar_url) + end + end + + context 'when user has no avatar' do + let(:user) { create(:user) } + + it 'returns default placeholder' do + expect(user.display_avatar).to eq('https://via.placeholder.com/150') + end + end + end +end + diff --git a/spec/policies/user_policy_spec.rb b/spec/policies/user_policy_spec.rb new file mode 100644 index 000000000..d2b71fc83 --- /dev/null +++ b/spec/policies/user_policy_spec.rb @@ -0,0 +1,58 @@ +require 'rails_helper' + +RSpec.describe UserPolicy, type: :policy do + let(:admin) { create(:user, :admin) } + let(:user) { create(:user) } + let(:other_user) { create(:user) } + + subject { described_class } + + permissions :index? do + it 'grants access to admin' do + expect(subject).to permit(admin, User) + end + + it 'denies access to regular user' do + expect(subject).not_to permit(user, User) + end + end + + permissions :show? do + it 'grants access to admin' do + expect(subject).to permit(admin, user) + end + + it 'grants access to own profile' do + expect(subject).to permit(user, user) + end + + it 'denies access to other users profile' do + expect(subject).not_to permit(user, other_user) + end + end + + permissions :update? do + it 'grants access to admin' do + expect(subject).to permit(admin, user) + end + + it 'grants access to own profile' do + expect(subject).to permit(user, user) + end + + it 'denies access to other users profile' do + expect(subject).not_to permit(user, other_user) + end + end + + permissions :destroy? do + it 'grants access to admin' do + expect(subject).to permit(admin, user) + end + + it 'grants access to own profile' do + expect(subject).to permit(user, user) + end + end +end + diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 000000000..8be7460ad --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,131 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort('The Rails environment is running in production mode!') if Rails.env.production? +require 'rspec/rails' + +# Add additional requires below this line. Rails is not loaded until this point! +require 'capybara/rspec' +require 'capybara/rails' +require 'simplecov' + +SimpleCov.start 'rails' do + add_filter '/spec/' + add_filter '/config/' + add_filter '/vendor/' + minimum_coverage 90 +end + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for purposefully slowing down specs to find +# flaky specs. (If you create too many aggressive specs/debug specs, they will +# cause test suite to run very slow. So please consider fixing or removing them.) +# require 'rspec_flaky' + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for purposefully slowing down specs to find +# flaky specs. (If you create too many aggressive specs/debug specs, they will +# cause test suite to run very slow. So please consider fixing or removing them.) +# require 'rspec_flaky' + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for purposefully slowing down specs to find +# flaky specs. (If you create too many aggressive specs/debug specs, they will +# cause test suite to run very slow. So please consider fixing or removing them.) +# require 'rspec_flaky' + +Dir[Rails.root.join('spec', 'support', '**', '*.rb')].sort.each { |f| require f } + +# Checks for pending migrations and applies them before tests are run. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + abort e.to_s.strip +end + +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_paths = [ + Rails.root.join('spec/fixtures') + ] + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails can automatically mix in different behaviours to your tests + # based on their file location, for example enabling you to call `get` and + # `post` in specs under `spec/controllers`. + # + # You can disable this behaviour by removing the line below, and instead + # explicitly tag your specs with their type, e.g.: + # + # RSpec.describe UsersController, type: :controller do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://rspec.info/features/6-0/rspec-rails + config.infer_spec_type_from_file_location! + + # Filter lines from Rails gems in backtraces. + config.filter_rails_from_backtrace! + # arbitrary gems may also be filtered via: + # config.filter_gems_from_backtrace("gem name") + + # Include FactoryBot methods + config.include FactoryBot::Syntax::Methods + + # Include Devise test helpers + config.include Devise::Test::ControllerHelpers, type: :controller + config.include Devise::Test::IntegrationHelpers, type: :request + + # Include Shoulda Matchers + Shoulda::Matchers.configure do |shoulda_config| + shoulda_config.integrate do |with| + with.test_framework :rspec + with.library :rails + end + end + + # Database Cleaner configuration + config.before(:suite) do + DatabaseCleaner.strategy = :transaction + DatabaseCleaner.clean_with(:truncation) + end + + config.around(:each) do |example| + DatabaseCleaner.cleaning do + example.run + end + end +end + diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..f3e5e843d --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,95 @@ +# This file was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared context metadata to be + # applied to the host groups and examples, rather than just to the example + # groups themselves. + config.shared_context_metadata_behavior = :apply_to_host_groups + + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = 'spec/examples.txt' + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a --format flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +end + diff --git a/spec/support/database_cleaner.rb b/spec/support/database_cleaner.rb new file mode 100644 index 000000000..7a44211db --- /dev/null +++ b/spec/support/database_cleaner.rb @@ -0,0 +1,13 @@ +RSpec.configure do |config| + config.before(:suite) do + DatabaseCleaner.strategy = :transaction + DatabaseCleaner.clean_with(:truncation) + end + + config.around(:each) do |example| + DatabaseCleaner.cleaning do + example.run + end + end +end + diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/storage/.keep b/tmp/storage/.keep new file mode 100644 index 000000000..e69de29bb From 2af7476c5c1939de211a7cb86feaa212b4307756 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Mon, 3 Nov 2025 12:25:40 -0300 Subject: [PATCH 02/12] Update Gemfile to allow Ruby version >= 3.3.0, remove webpacker dependency, and add Gemfile.lock and package-lock.json for dependency management --- Gemfile | 3 +- Gemfile.lock | 502 +++++++++++++++++++++++++++++++++ config/initializers/devise.rb | 4 +- db/schema.rb | 15 +- package-lock.json | 512 ++++++++++++++++++++++++++++++++++ 5 files changed, 1029 insertions(+), 7 deletions(-) create mode 100644 Gemfile.lock create mode 100644 package-lock.json diff --git a/Gemfile b/Gemfile index 36f91d0f5..b928a921a 100644 --- a/Gemfile +++ b/Gemfile @@ -1,13 +1,12 @@ source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } -ruby '3.3.0' +ruby '>= 3.3.0' gem 'rails', '~> 8.0.3' gem 'pg', '~> 1.5' gem 'puma', '~> 6.4' gem 'sass-rails', '~> 6.0' -gem 'webpacker', '~> 7.0' gem 'turbo-rails' gem 'stimulus-rails' gem 'jbuilder', '~> 2.13' diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..0dcf45eaf --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,502 @@ +GEM + remote: https://rubygems.org/ + specs: + actioncable (8.0.4) + actionpack (= 8.0.4) + activesupport (= 8.0.4) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.0.4) + actionpack (= 8.0.4) + activejob (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + mail (>= 2.8.0) + actionmailer (8.0.4) + actionpack (= 8.0.4) + actionview (= 8.0.4) + activejob (= 8.0.4) + activesupport (= 8.0.4) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.0.4) + actionview (= 8.0.4) + activesupport (= 8.0.4) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.0.4) + actionpack (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.0.4) + activesupport (= 8.0.4) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.0.4) + activesupport (= 8.0.4) + globalid (>= 0.3.6) + activemodel (8.0.4) + activesupport (= 8.0.4) + activerecord (8.0.4) + activemodel (= 8.0.4) + activesupport (= 8.0.4) + timeout (>= 0.4.0) + activestorage (8.0.4) + actionpack (= 8.0.4) + activejob (= 8.0.4) + activerecord (= 8.0.4) + activesupport (= 8.0.4) + marcel (~> 1.0) + activesupport (8.0.4) + base64 + benchmark (>= 0.3) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.8.7) + public_suffix (>= 2.0.2, < 7.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.20) + benchmark (0.5.0) + bigdecimal (3.3.1) + bindex (0.8.1) + bootsnap (1.18.6) + msgpack (~> 1.2) + bootstrap (5.3.5) + popper_js (>= 2.11.8, < 3) + builder (3.3.0) + byebug (12.0.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + coderay (1.1.3) + concurrent-ruby (1.3.5) + connection_pool (2.5.4) + crack (1.0.1) + bigdecimal + rexml + crass (1.0.6) + database_cleaner-active_record (2.2.2) + activerecord (>= 5.a) + database_cleaner-core (~> 2.0) + database_cleaner-core (2.0.1) + date (3.5.0) + devise (4.9.4) + bcrypt (~> 3.0) + orm_adapter (~> 0.1) + railties (>= 4.1.0) + responders + warden (~> 1.2.3) + diff-lcs (1.6.2) + docile (1.4.1) + drb (2.2.3) + erb (5.1.3) + erubi (1.13.1) + factory_bot (6.5.6) + activesupport (>= 6.1.0) + factory_bot_rails (6.5.1) + factory_bot (~> 6.5) + railties (>= 6.1.0) + faker (3.5.2) + i18n (>= 1.8.11, < 2) + ffi (1.17.2-aarch64-linux-gnu) + ffi (1.17.2-aarch64-linux-musl) + ffi (1.17.2-arm-linux-gnu) + ffi (1.17.2-arm-linux-musl) + ffi (1.17.2-arm64-darwin) + ffi (1.17.2-x86_64-darwin) + ffi (1.17.2-x86_64-linux-gnu) + ffi (1.17.2-x86_64-linux-musl) + globalid (1.3.0) + activesupport (>= 6.1) + hashdiff (1.2.1) + i18n (1.14.7) + concurrent-ruby (~> 1.0) + image_processing (1.14.0) + mini_magick (>= 4.9.5, < 6) + ruby-vips (>= 2.0.17, < 3) + io-console (0.8.1) + irb (1.15.3) + pp (>= 0.6.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.14.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + jquery-rails (4.6.1) + rails-dom-testing (>= 1, < 3) + railties (>= 4.2.0) + thor (>= 0.14, < 2.0) + json (2.15.2) + language_server-protocol (3.17.0.5) + lint_roller (1.1.0) + listen (3.9.0) + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) + logger (1.7.0) + loofah (2.24.1) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.0) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.1.0) + matrix (0.4.3) + method_source (1.1.0) + mini_magick (5.3.1) + logger + mini_mime (1.1.5) + minitest (5.26.0) + msgpack (1.8.0) + net-imap (0.5.12) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-smtp (0.5.1) + net-protocol + nio4r (2.7.5) + nokogiri (1.18.10-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-musl) + racc (~> 1.4) + orm_adapter (0.5.0) + parallel (1.27.0) + parser (3.3.10.0) + ast (~> 2.4.1) + racc + pg (1.6.2) + pg (1.6.2-aarch64-linux) + pg (1.6.2-aarch64-linux-musl) + pg (1.6.2-arm64-darwin) + pg (1.6.2-x86_64-darwin) + pg (1.6.2-x86_64-linux) + pg (1.6.2-x86_64-linux-musl) + popper_js (2.11.8) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.6.0) + pry (0.15.2) + coderay (~> 1.1) + method_source (~> 1.0) + pry-byebug (3.11.0) + byebug (~> 12.0) + pry (>= 0.13, < 0.16) + pry-rails (0.3.11) + pry (>= 0.13.0) + psych (5.2.6) + date + stringio + public_suffix (6.0.2) + puma (6.6.1) + nio4r (~> 2.0) + pundit (2.5.2) + activesupport (>= 3.0.0) + racc (1.8.1) + rack (3.2.4) + rack-session (2.1.1) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails (8.0.4) + actioncable (= 8.0.4) + actionmailbox (= 8.0.4) + actionmailer (= 8.0.4) + actionpack (= 8.0.4) + actiontext (= 8.0.4) + actionview (= 8.0.4) + activejob (= 8.0.4) + activemodel (= 8.0.4) + activerecord (= 8.0.4) + activestorage (= 8.0.4) + activesupport (= 8.0.4) + bundler (>= 1.15.0) + railties (= 8.0.4) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.0.4) + actionpack (= 8.0.4) + activesupport (= 8.0.4) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.3.1) + rb-fsevent (0.11.2) + rb-inotify (0.11.1) + ffi (~> 1.0) + rdoc (6.15.1) + erb + psych (>= 4.0.0) + tsort + redis (5.4.1) + redis-client (>= 0.22.0) + redis-client (0.26.1) + connection_pool + regexp_parser (2.11.3) + reline (0.6.2) + io-console (~> 0.5) + responders (3.2.0) + actionpack (>= 7.0) + railties (>= 7.0) + rexml (3.4.4) + roo (2.10.1) + nokogiri (~> 1) + rubyzip (>= 1.3.0, < 3.0.0) + roo-xls (1.2.0) + nokogiri + roo (>= 2.0.0, < 3) + spreadsheet (> 0.9.0) + rspec-core (3.13.6) + rspec-support (~> 3.13.0) + rspec-expectations (3.13.5) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-mocks (3.13.7) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-rails (6.1.5) + actionpack (>= 6.1) + activesupport (>= 6.1) + railties (>= 6.1) + rspec-core (~> 3.13) + rspec-expectations (~> 3.13) + rspec-mocks (~> 3.13) + rspec-support (~> 3.13) + rspec-support (3.13.6) + rubocop (1.81.7) + json (~> 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.47.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.47.1) + parser (>= 3.3.7.2) + prism (~> 1.4) + rubocop-capybara (2.22.1) + lint_roller (~> 1.1) + rubocop (~> 1.72, >= 1.72.1) + rubocop-factory_bot (2.27.1) + lint_roller (~> 1.1) + rubocop (~> 1.72, >= 1.72.1) + rubocop-rails (2.33.4) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rspec (2.31.0) + rubocop (~> 1.40) + rubocop-capybara (~> 2.17) + rubocop-factory_bot (~> 2.22) + rubocop-rspec_rails (~> 2.28) + rubocop-rspec_rails (2.29.1) + rubocop (~> 1.61) + ruby-ole (1.2.13.1) + ruby-progressbar (1.13.0) + ruby-vips (2.2.5) + ffi (~> 1.12) + logger + rubyzip (2.4.1) + sass-rails (6.0.0) + sassc-rails (~> 2.1, >= 2.1.1) + sassc (2.4.0) + ffi (~> 1.9) + sassc-rails (2.1.2) + railties (>= 4.0.0) + sassc (>= 2.0) + sprockets (> 3.0) + sprockets-rails + tilt + securerandom (0.4.1) + selenium-webdriver (4.10.0) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 3.0) + websocket (~> 1.0) + shoulda-matchers (6.5.0) + activesupport (>= 5.2.0) + sidekiq (7.3.9) + base64 + connection_pool (>= 2.3.0) + logger + rack (>= 2.2.4) + redis-client (>= 0.22.2) + simplecov (0.22.0) + docile (~> 1.1) + simplecov-html (~> 0.11) + simplecov_json_formatter (~> 0.1) + simplecov-html (0.13.2) + simplecov_json_formatter (0.1.4) + spreadsheet (1.3.4) + bigdecimal + logger + ruby-ole + spring (4.4.0) + sprockets (4.2.2) + concurrent-ruby (~> 1.0) + logger + rack (>= 2.2.4, < 4) + sprockets-rails (3.5.2) + actionpack (>= 6.1) + activesupport (>= 6.1) + sprockets (>= 3.0.0) + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.1.7) + thor (1.4.0) + tilt (2.6.1) + timeout (0.4.4) + tsort (0.2.0) + turbo-rails (2.0.20) + actionpack (>= 7.1.0) + railties (>= 7.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.1.0) + uri (1.1.0) + useragent (0.16.11) + vcr (6.3.1) + base64 + warden (1.2.9) + rack (>= 2.0.9) + web-console (4.2.1) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + webdrivers (5.3.1) + nokogiri (~> 1.6) + rubyzip (>= 1.3.0) + selenium-webdriver (~> 4.0, < 4.11) + webmock (3.26.1) + addressable (>= 2.8.0) + crack (>= 0.3.2) + hashdiff (>= 0.4.0, < 2.0.0) + websocket (1.2.11) + websocket-driver (0.8.0) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.7.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86_64-darwin + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap (>= 1.4.4) + bootstrap (~> 5.3) + byebug + capybara (~> 3.40) + database_cleaner-active_record (~> 2.2) + devise + factory_bot_rails (~> 6.4) + faker (~> 3.2) + image_processing (~> 1.12) + jbuilder (~> 2.13) + jquery-rails + listen (~> 3.3) + mini_magick + pg (~> 1.5) + popper_js (~> 2.11) + pry-byebug + pry-rails + puma (~> 6.4) + pundit + rails (~> 8.0.3) + redis (~> 5.0) + roo (~> 2.10) + roo-xls + rspec-rails (~> 6.1) + rubocop (~> 1.64) + rubocop-rails (~> 2.24) + rubocop-rspec (~> 2.26) + sass-rails (~> 6.0) + selenium-webdriver + shoulda-matchers (~> 6.3) + sidekiq (~> 7.2) + simplecov + spring + stimulus-rails + turbo-rails + vcr (~> 6.3) + web-console (>= 4.2.0) + webdrivers + webmock (~> 3.23) + +RUBY VERSION + ruby 3.3.6p108 + +BUNDLED WITH + 2.7.2 diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 7e7639ebe..06001a338 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -36,7 +36,7 @@ # Load and configure the ORM. Supports :active_record (default) and # :mongoid (required for MongoDB) The ORMs that are supported by default # are ActiveModel::Devise and ActiveModel::Mongoid. - config.orm = :active_record + # config.orm = :active_record # Not needed in recent Devise versions # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is @@ -200,7 +200,7 @@ # ==> Configuration for :registerable # When you set this to true, you can create users without confirmation # For direct sign up - config.sign_up_enabled = true + # config.sign_up_enabled = true # Not available in this Devise version # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). diff --git a/db/schema.rb b/db/schema.rb index bbb86ff98..b71ce8d2b 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -1,8 +1,18 @@ -# This file is auto-generated from the database schema. Running `rails db:schema:dump` will update this file automatically. +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[8.0].define(version: 2024_01_01_000003) do # These are extensions that must be enabled in order to support this database - enable_extension "plpgsql" + enable_extension "pg_catalog.plpgsql" create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false @@ -67,4 +77,3 @@ add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" add_foreign_key "user_imports", "users" end - diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..3eceb13ab --- /dev/null +++ b/package-lock.json @@ -0,0 +1,512 @@ +{ + "name": "fullstack-developer", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "fullstack-developer", + "version": "1.0.0", + "dependencies": { + "@hotwired/stimulus": "^3.2.0", + "@hotwired/turbo-rails": "^8.0.0", + "@rails/actioncable": "^8.0.0", + "bootstrap": "^5.3.0" + }, + "devDependencies": { + "esbuild": "^0.19.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.19.12.tgz", + "integrity": "sha512-bmoCYyWdEL3wDQIVbcyzRyeKLgk2WtWLTWz1ZIAZF/EGbNOwSA6ew3PftJ1PqMiOOGu0OyFMzG53L0zqIpPeNA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.19.12.tgz", + "integrity": "sha512-qg/Lj1mu3CdQlDEEiWrlC4eaPZ1KztwGJ9B6J+/6G+/4ewxJg7gqj8eVYWvao1bXrqGiW2rsBZFSX3q2lcW05w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.19.12.tgz", + "integrity": "sha512-P0UVNGIienjZv3f5zq0DP3Nt2IE/3plFzuaS96vihvD0Hd6H/q4WXUGpCxD/E8YrSXfNyRPbpTq+T8ZQioSuPA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.19.12.tgz", + "integrity": "sha512-3k7ZoUW6Q6YqhdhIaq/WZ7HwBpnFBlW905Fa4s4qWJyiNOgT1dOqDiVAQFwBH7gBRZr17gLrlFCRzF6jFh7Kew==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.19.12.tgz", + "integrity": "sha512-B6IeSgZgtEzGC42jsI+YYu9Z3HKRxp8ZT3cqhvliEHovq8HSX2YX8lNocDn79gCKJXOSaEot9MVYky7AKjCs8g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.19.12.tgz", + "integrity": "sha512-hKoVkKzFiToTgn+41qGhsUJXFlIjxI/jSYeZf3ugemDYZldIXIxhvwN6erJGlX4t5h417iFuheZ7l+YVn05N3A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.19.12.tgz", + "integrity": "sha512-4aRvFIXmwAcDBw9AueDQ2YnGmz5L6obe5kmPT8Vd+/+x/JMVKCgdcRwH6APrbpNXsPz+K653Qg8HB/oXvXVukA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.19.12.tgz", + "integrity": "sha512-EYoXZ4d8xtBoVN7CEwWY2IN4ho76xjYXqSXMNccFSx2lgqOG/1TBPW0yPx1bJZk94qu3tX0fycJeeQsKovA8gg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.19.12.tgz", + "integrity": "sha512-J5jPms//KhSNv+LO1S1TX1UWp1ucM6N6XuL6ITdKWElCu8wXP72l9MM0zDTzzeikVyqFE6U8YAV9/tFyj0ti+w==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.19.12.tgz", + "integrity": "sha512-EoTjyYyLuVPfdPLsGVVVC8a0p1BFFvtpQDB/YLEhaXyf/5bczaGeN15QkR+O4S5LeJ92Tqotve7i1jn35qwvdA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.19.12.tgz", + "integrity": "sha512-Thsa42rrP1+UIGaWz47uydHSBOgTUnwBwNq59khgIwktK6x60Hivfbux9iNR0eHCHzOLjLMLfUMLCypBkZXMHA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.19.12.tgz", + "integrity": "sha512-LiXdXA0s3IqRRjm6rV6XaWATScKAXjI4R4LoDlvO7+yQqFdlr1Bax62sRwkVvRIrwXxvtYEHHI4dm50jAXkuAA==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.19.12.tgz", + "integrity": "sha512-fEnAuj5VGTanfJ07ff0gOA6IPsvrVHLVb6Lyd1g2/ed67oU1eFzL0r9WL7ZzscD+/N6i3dWumGE1Un4f7Amf+w==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.19.12.tgz", + "integrity": "sha512-nYJA2/QPimDQOh1rKWedNOe3Gfc8PabU7HT3iXWtNUbRzXS9+vgB0Fjaqr//XNbd82mCxHzik2qotuI89cfixg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.19.12.tgz", + "integrity": "sha512-2MueBrlPQCw5dVJJpQdUYgeqIzDQgw3QtiAHUC4RBz9FXPrskyyU3VI1hw7C0BSKB9OduwSJ79FTCqtGMWqJHg==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.19.12.tgz", + "integrity": "sha512-+Pil1Nv3Umes4m3AZKqA2anfhJiVmNCYkPchwFJNEJN5QxmTs1uzyy4TvmDrCRNT2ApwSari7ZIgrPeUx4UZDg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.19.12.tgz", + "integrity": "sha512-B71g1QpxfwBvNrfyJdVDexenDIt1CiDN1TIXLbhOw0KhJzE78KIFGX6OJ9MrtC0oOqMWf+0xop4qEU8JrJTwCg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.19.12.tgz", + "integrity": "sha512-3ltjQ7n1owJgFbuC61Oj++XhtzmymoCihNFgT84UAmJnxJfm4sYCiSLTXZtE00VWYpPMYc+ZQmB6xbSdVh0JWA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.19.12.tgz", + "integrity": "sha512-RbrfTB9SWsr0kWmb9srfF+L933uMDdu9BIzdA7os2t0TXhCRjrQyCeOt6wVxr79CKD4c+p+YhCj31HBkYcXebw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.19.12.tgz", + "integrity": "sha512-HKjJwRrW8uWtCQnQOz9qcU3mUZhTUQvi56Q8DPTLLB+DawoiQdjsYq+j+D3s9I8VFtDr+F9CjgXKKC4ss89IeA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.19.12.tgz", + "integrity": "sha512-URgtR1dJnmGvX864pn1B2YUYNzjmXkuJOIqG2HdU62MVS4EHpU2946OZoTMnRUHklGtJdJZ33QfzdjGACXhn1A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.19.12.tgz", + "integrity": "sha512-+ZOE6pUkMOJfmxmBZElNOx72NKpIa/HFOMGzu8fqzQJ5kgf6aTGrcJaFsNiVMH4JKpMipyK+7k0n2UXN7a8YKQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.19.12.tgz", + "integrity": "sha512-T1QyPSDCyMXaO3pzBkF96E8xMkiRYbUEZADd29SyPGabqxMViNoii+NcK7eWJAEoU6RZyEm5lVSIjTmcdoB9HA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@hotwired/stimulus": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@hotwired/stimulus/-/stimulus-3.2.2.tgz", + "integrity": "sha512-eGeIqNOQpXoPAIP7tC1+1Yc1yl1xnwYqg+3mzqxyrbE5pg5YFBZcA6YoTiByJB6DKAEsiWtl6tjTJS4IYtbB7A==", + "license": "MIT" + }, + "node_modules/@hotwired/turbo": { + "version": "8.0.20", + "resolved": "https://registry.npmjs.org/@hotwired/turbo/-/turbo-8.0.20.tgz", + "integrity": "sha512-IilkH/+h92BRLeY/rMMR3MUh1gshIfdra/qZzp/Bl5FmiALD/6sQZK/ecxSbumeyOYiWr/JRI+Au1YQmkJGnoA==", + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/@hotwired/turbo-rails": { + "version": "8.0.20", + "resolved": "https://registry.npmjs.org/@hotwired/turbo-rails/-/turbo-rails-8.0.20.tgz", + "integrity": "sha512-4aYkYF9XMKL7ZZPfgElq15+60osZOwMwhztE4myKQYEzCPvaPUxwZH301tOrBNtWUwOD+TNOm1Hrpeaq22RX9A==", + "license": "MIT", + "dependencies": { + "@hotwired/turbo": "^8.0.20", + "@rails/actioncable": ">=7.0" + } + }, + "node_modules/@popperjs/core": { + "version": "2.11.8", + "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", + "integrity": "sha512-P1st0aksCrn9sGZhp8GMYwBnQsbvAWsZAX44oXNNvLHGqAOcoVxmjZiohstwQ7SqKnbR47akdNi+uleWD8+g6A==", + "license": "MIT", + "peer": true, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/popperjs" + } + }, + "node_modules/@rails/actioncable": { + "version": "8.1.100", + "resolved": "https://registry.npmjs.org/@rails/actioncable/-/actioncable-8.1.100.tgz", + "integrity": "sha512-j4vJQqz51CDVYv2UafKRu4jiZi5/gTnm7NkyL+VMIgEw3s8jtVtmzu9uItUaZccUg9NJ6o05yVyBAHxNfTuCRA==", + "license": "MIT" + }, + "node_modules/bootstrap": { + "version": "5.3.8", + "resolved": "https://registry.npmjs.org/bootstrap/-/bootstrap-5.3.8.tgz", + "integrity": "sha512-HP1SZDqaLDPwsNiqRqi5NcP0SSXciX2s9E+RyqJIIqGo+vJeN5AJVM98CXmW/Wux0nQ5L7jeWUdplCEf0Ee+tg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/twbs" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/bootstrap" + } + ], + "license": "MIT", + "peerDependencies": { + "@popperjs/core": "^2.11.8" + } + }, + "node_modules/esbuild": { + "version": "0.19.12", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.19.12.tgz", + "integrity": "sha512-aARqgq8roFBj054KvQr5f1sFu0D65G+miZRCuJyJ0G13Zwx7vRar5Zhn2tkQNzIXcBrNVsv/8stehpj+GAjgbg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.19.12", + "@esbuild/android-arm": "0.19.12", + "@esbuild/android-arm64": "0.19.12", + "@esbuild/android-x64": "0.19.12", + "@esbuild/darwin-arm64": "0.19.12", + "@esbuild/darwin-x64": "0.19.12", + "@esbuild/freebsd-arm64": "0.19.12", + "@esbuild/freebsd-x64": "0.19.12", + "@esbuild/linux-arm": "0.19.12", + "@esbuild/linux-arm64": "0.19.12", + "@esbuild/linux-ia32": "0.19.12", + "@esbuild/linux-loong64": "0.19.12", + "@esbuild/linux-mips64el": "0.19.12", + "@esbuild/linux-ppc64": "0.19.12", + "@esbuild/linux-riscv64": "0.19.12", + "@esbuild/linux-s390x": "0.19.12", + "@esbuild/linux-x64": "0.19.12", + "@esbuild/netbsd-x64": "0.19.12", + "@esbuild/openbsd-x64": "0.19.12", + "@esbuild/sunos-x64": "0.19.12", + "@esbuild/win32-arm64": "0.19.12", + "@esbuild/win32-ia32": "0.19.12", + "@esbuild/win32-x64": "0.19.12" + } + } + } +} From 87c619e43b3d4f418707257249b48ffc857dbe61 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Mon, 3 Nov 2025 13:17:48 -0300 Subject: [PATCH 03/12] Update Gemfile to specify Ruby version 3.3.6, add importmap-rails gem, and modify asset manifest to link JavaScript files. Change Bootstrap import style in application.scss and refactor enum definitions in user and user_import models. Update Devise initializer for improved configuration and add English locale translations for Devise. Remove unnecessary .keep file from tmp/pids. --- Gemfile | 2 +- app/assets/config/manifest.js | 1 - app/assets/stylesheets/application.scss | 3 +- app/models/user.rb | 2 +- app/models/user_import.rb | 2 +- bin/rails | 10 +- config/initializers/devise.rb | 171 +++++++++++++++--------- config/locales/devise.en.yml | 65 +++++++++ tmp/pids/.keep | 0 9 files changed, 179 insertions(+), 77 deletions(-) create mode 100644 config/locales/devise.en.yml delete mode 100644 tmp/pids/.keep diff --git a/Gemfile b/Gemfile index b928a921a..0bd054c2d 100644 --- a/Gemfile +++ b/Gemfile @@ -1,7 +1,7 @@ source 'https://rubygems.org' git_source(:github) { |repo| "https://github.com/#{repo}.git" } -ruby '>= 3.3.0' +ruby '3.3.6' gem 'rails', '~> 8.0.3' gem 'pg', '~> 1.5' diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js index 4481a9c1e..3fcd8f45d 100644 --- a/app/assets/config/manifest.js +++ b/app/assets/config/manifest.js @@ -1,4 +1,3 @@ //= link_tree ../images //= link_directory ../stylesheets .css -//= link application.js diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index e97793f16..6f0525348 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -1,4 +1,5 @@ -@import "bootstrap/scss/bootstrap"; +// Import Bootstrap from gem +@import "bootstrap"; // Custom variables $primary-color: #007bff; diff --git a/app/models/user.rb b/app/models/user.rb index 424033997..71a0e600f 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -9,7 +9,7 @@ class User < ApplicationRecord has_many :user_imports, dependent: :destroy # Enums - enum role: { user: 0, admin: 1 } + enum :role, { user: 0, admin: 1 } # Validations validates :full_name, presence: true, length: { minimum: 2, maximum: 100 } diff --git a/app/models/user_import.rb b/app/models/user_import.rb index 63b3f0222..f0363ef9a 100644 --- a/app/models/user_import.rb +++ b/app/models/user_import.rb @@ -4,7 +4,7 @@ class UserImport < ApplicationRecord has_one_attached :spreadsheet_file # Enums - enum status: { pending: 0, processing: 1, completed: 2, failed: 3 } + enum :status, { pending: 0, processing: 1, completed: 2, failed: 3 } # Validations validates :spreadsheet_file, presence: true diff --git a/bin/rails b/bin/rails index 9c68bbaa5..1c02d4a71 100755 --- a/bin/rails +++ b/bin/rails @@ -1,13 +1,7 @@ #!/usr/bin/env ruby # This command will automatically be run when you run "rails" with Rails 8 gems installed from the root directory of your application. -ENGINE_ROOT = File.expand_path('../..', __dir__) -ENGINE_PATH = nil - -# Set up gems listed in the Gemfile. -ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../Gemfile', __dir__) -require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) - -require "rails/command" +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" require "rails/commands" diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb index 06001a338..7e905b9d3 100644 --- a/config/initializers/devise.rb +++ b/config/initializers/devise.rb @@ -14,7 +14,7 @@ # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. - # config.secret_key = '...' + # config.secret_key = 'a4b10f49a00b3671c18001b9a9e393e1bd6a32e17a0a53fa57166177b26813bf05ab2a40bb249bfdeea4e877a2631aeb1c07a48b5f898294794f57b84234befe' # ==> Controller configuration # Configure the parent class to the devise controllers. @@ -30,13 +30,13 @@ # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. - # config.parent_mailer = 'ApplicationMailer' + # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and - # :mongoid (required for MongoDB) The ORMs that are supported by default - # are ActiveModel::Devise and ActiveModel::Mongoid. - # config.orm = :active_record # Not needed in recent Devise versions + # :mongoid (bson_ext recommended) by default. Other ORMs may be + # available as additional gems. + require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is @@ -50,9 +50,9 @@ # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the - # find_for_authentication method and used in conditions. You can also supply - # a hash where the value is a boolean determining whether or not authentication - # should be aborted when the value is not present. + # find_for_authentication method and considered in your model lookup. For instance, + # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. + # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. @@ -61,20 +61,22 @@ config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. - # These keys will be downcased upon creating or modifying a user and when used - # to authenticate or find a user. Default is :email. + # These keys will have whitespace before and after removed upon creating or + # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will - # enable params authentication only for the database authentication strategy. + # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will - # enable http authentication only for the database authentication strategy. + # enable it only for database authentication. + # For API-only applications to support authentication "out-of-the-box", you will likely want to + # enable this with :database unless you are using a custom strategy. # The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false @@ -86,40 +88,48 @@ # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows - # to behave the same regardless if the e-mail was registered or not. - # False by default. + # to behave the same regardless if the e-mail provided was right or wrong. + # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for - # :http_auth and :database_auth strategies. - # config.skip_session_storage = [:http_auth] + # particular strategies by setting this option. + # Notice that if you are skipping storage for all authentication paths, you + # may want to disable generating routes to Devise's sessions controller by + # passing skip: :sessions to `devise_for` in your config/routes.rb + config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token - # from the server. You can disable this option if you continue to use - # the legacy `authenticity_token` in the model for `form_with`. + # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true + # When false, Devise will not attempt to reload routes on eager load. + # This can reduce the time taken to boot the app but if your application + # requires the Devise mappings to be loaded during boot time the application + # won't boot properly. + # config.reload_routes = true + # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 12. If - # using other hashers, it sets how many times you want the password to be hashed. + # using other algorithms, it sets how many times you want the password to be hashed. # The number of stretches used for generating the hashed password are stored - # with the hashed password. This allows you to change the hashing algorithm - # without invalidating existing passwords. + # with the hashed password. This allows you to change the stretches without + # invalidating existing passwords. # # Limiting the stretches to just one in testing will increase the performance of - # your test suite dramatically. However, it is RECOMMENDED to not use a value less - # than 12 in other environments. Note that, for bcrypt (the default hasher), the - # cost increases exponentially with the number of stretches (e.g. a value of 20 - # is already extremely slow: approx. 1 second per password). + # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use + # a value less than 10 in other environments. Note that, for bcrypt (the default + # algorithm), the cost increases exponentially with the number of stretches (e.g. + # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 12 # Set up a pepper to generate the hashed password. - # config.pepper = '...' + # config.pepper = 'd9f3ac6672a459c83619d1e980f01f26b643df7e7c7810340429bf00ebef37929f90785c3cde51132a454b422b75c3d380db9c3b140347398ed4eb8dddd4f8cd' # Send a notification to the original email when the user's email is changed. - # config.send_email_changelog_notification = false + # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false @@ -128,18 +138,17 @@ # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, - # access will be blocked just in the few hours before the period expires. + # access will be blocked just in the third day. # You can also set it to nil, which will allow the user to access the website # without confirming their account. # Default is 0.days, meaning the user cannot access the website without # confirming their account. - # config.allow_unconfirmed_access_for = 0.days + # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day - # their account can no longer be confirmed with the token inside the email. - # This is used to reset the password token as well. + # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days @@ -147,7 +156,7 @@ # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in - # unconfirmed_email field, and copied to email field on successful confirmation. + # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account @@ -173,34 +182,53 @@ # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly - # to provide user feedback and not to assert the e-mail validity. + # to give user feedback and not to assert the e-mail validity. config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable - # The time you want to timeout the user after inactivity. + # The time you want to timeout the user session without activity. After this + # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. - # :unlock_token = Defines a strategy for unlocking an account using a token. - # :unlock_strategy = :email - # :unlock_strategy = :time # Unlock after a certain time (see :unlock_in) - # :unlock_strategy = :both # Unlock after a certain time and email confirmation - # config.maximum_attempts = 10 - # config.unlock_strategy = :failed_attempts - # config.lock_strategy = :unlock_token + # :none = No lock strategy. You should handle locking by yourself. + # config.lock_strategy = :failed_attempts + + # Defines which key will be used when locking and unlocking an account + # config.unlock_keys = [:email] + + # Defines which strategy will be used to unlock an account. + # :email = Sends an unlock link to the user email + # :time = Re-enables login after a certain amount of time (see :unlock_in below) + # :both = Enables both strategies + # :none = No unlock strategy. You should handle unlocking by yourself. + # config.unlock_strategy = :both + + # Number of authentication tries before locking an account if lock_strategy + # is failed attempts. + # config.maximum_attempts = 20 + + # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour + # Warn on the last attempt before the account is locked. + # config.last_attempt_warning = true + # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account - # config.recovery_keys = [:email] + # config.reset_password_keys = [:email] - # ==> Configuration for :registerable - # When you set this to true, you can create users without confirmation - # For direct sign up - # config.sign_up_enabled = true # Not available in this Devise version + # Time interval you can reset your password with a reset password key. + # Don't put a too small interval or your users won't have the time to + # change their passwords. + config.reset_password_within = 6.hours + + # When set to false, does not sign a user in automatically after their password is + # reset. Defaults to true, so a user is signed in automatically after a reset. + # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). @@ -228,22 +256,22 @@ # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like - # :html, should redirect to the sign in page when the user does not have + # :html should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # - # If you have any extra navigational formats, like :html5, :html, or :json, add - # them to the navigational formats lists. + # If you have any extra navigational formats, like :iphone or :mobile, you + # should add them to the navigational formats lists. # - # The "*/*" below is required to match all user types. - # config.navigational_formats = ['*/*', :html] + # The "*/*" below is required to match Internet Explorer requests. + config.navigational_formats = ['*/*', :html, :turbo_stream] - # The default HTTP method used to sign out a resource. - # config.sign_out_via = :delete + # The default HTTP method used to sign out a resource. Default is :delete. + config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. - # config.omni_auth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' + # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or @@ -254,17 +282,32 @@ # manager.default_strategies(scope: :user).unshift :some_external_strategy # end - # ==> Turbo configuration - config.navigational_formats = ['*/*', :html, :turbo_stream] + # ==> Mountable engine configurations + # When using Devise inside an engine, let's call it `MyEngine`, and this engine + # is mountable, there are some extra configurations to be taken into account. + # The following options are available, assuming the engine is mounted as: + # + # mount MyEngine, at: '/my_engine' + # + # The router that invoked `devise_for`, in the example above, would be: + # config.router_name = :my_engine + # + # When using OmniAuth, Devise cannot automatically set OmniAuth path, + # so you need to do it manually. For the users scope, it would be: + # config.omniauth_path_prefix = '/my_engine/users/auth' + + # ==> Hotwire/Turbo configuration + # When using Devise with Hotwire/Turbo, the http status for error responses + # and some redirects must match the following. The default in Devise for existing + # apps is `200 OK` and `302 Found` respectively, but new apps are generated with + # these new defaults that match Hotwire/Turbo behavior. + # Note: These might become the new default in future versions of Devise. + config.responder.error_status = :unprocessable_entity + config.responder.redirect_status = :see_other # ==> Configuration for :registerable - # When set to false, does not sign a user in automatically after their password is - # reset (default: true). - # config.sign_in_after_reset_password = true - # ==> Configuration for :registerable - # When set to false, does not sign a user in automatically after they register. - # (default: true) - # config.sign_in_after_sign_up = true + # When set to false, does not sign a user in automatically after their password is + # changed. Defaults to true, so a user is signed in automatically after changing a password. + # config.sign_in_after_change_password = true end - diff --git a/config/locales/devise.en.yml b/config/locales/devise.en.yml new file mode 100644 index 000000000..260e1c4ba --- /dev/null +++ b/config/locales/devise.en.yml @@ -0,0 +1,65 @@ +# Additional translations at https://github.com/heartcombo/devise/wiki/I18n + +en: + devise: + confirmations: + confirmed: "Your email address has been successfully confirmed." + send_instructions: "You will receive an email with instructions for how to confirm your email address in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive an email with instructions for how to confirm your email address in a few minutes." + failure: + already_authenticated: "You are already signed in." + inactive: "Your account is not activated yet." + invalid: "Invalid %{authentication_keys} or password." + locked: "Your account is locked." + last_attempt: "You have one more attempt before your account is locked." + not_found_in_database: "Invalid %{authentication_keys} or password." + timeout: "Your session expired. Please sign in again to continue." + unauthenticated: "You need to sign in or sign up before continuing." + unconfirmed: "You have to confirm your email address before continuing." + mailer: + confirmation_instructions: + subject: "Confirmation instructions" + reset_password_instructions: + subject: "Reset password instructions" + unlock_instructions: + subject: "Unlock instructions" + email_changed: + subject: "Email Changed" + password_change: + subject: "Password Changed" + omniauth_callbacks: + failure: "Could not authenticate you from %{kind} because \"%{reason}\"." + success: "Successfully authenticated from %{kind} account." + passwords: + no_token: "You can't access this page without coming from a password reset email. If you do come from a password reset email, please make sure you used the full URL provided." + send_instructions: "You will receive an email with instructions on how to reset your password in a few minutes." + send_paranoid_instructions: "If your email address exists in our database, you will receive a password recovery link at your email address in a few minutes." + updated: "Your password has been changed successfully. You are now signed in." + updated_not_active: "Your password has been changed successfully." + registrations: + destroyed: "Bye! Your account has been successfully cancelled. We hope to see you again soon." + signed_up: "Welcome! You have signed up successfully." + signed_up_but_inactive: "You have signed up successfully. However, we could not sign you in because your account is not yet activated." + signed_up_but_locked: "You have signed up successfully. However, we could not sign you in because your account is locked." + signed_up_but_unconfirmed: "A message with a confirmation link has been sent to your email address. Please follow the link to activate your account." + update_needs_confirmation: "You updated your account successfully, but we need to verify your new email address. Please check your email and follow the confirmation link to confirm your new email address." + updated: "Your account has been updated successfully." + updated_but_not_signed_in: "Your account has been updated successfully, but since your password was changed, you need to sign in again." + sessions: + signed_in: "Signed in successfully." + signed_out: "Signed out successfully." + already_signed_out: "Signed out successfully." + unlocks: + send_instructions: "You will receive an email with instructions for how to unlock your account in a few minutes." + send_paranoid_instructions: "If your account exists, you will receive an email with instructions for how to unlock it in a few minutes." + unlocked: "Your account has been unlocked successfully. Please sign in to continue." + errors: + messages: + already_confirmed: "was already confirmed, please try signing in" + confirmation_period_expired: "needs to be confirmed within %{period}, please request a new one" + expired: "has expired, please request a new one" + not_found: "not found" + not_locked: "was not locked" + not_saved: + one: "1 error prohibited this %{resource} from being saved:" + other: "%{count} errors prohibited this %{resource} from being saved:" diff --git a/tmp/pids/.keep b/tmp/pids/.keep deleted file mode 100644 index e69de29bb..000000000 From 2569577d1cfa8c6f5a3f0e615c46a8edf7dd3625 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Mon, 3 Nov 2025 13:18:05 -0300 Subject: [PATCH 04/12] Add importmap-rails gem, update asset manifest to link JavaScript files, and create importmap script --- Gemfile | 1 + Gemfile.lock | 5 +++++ app/assets/config/manifest.js | 2 ++ app/javascript/application.js | 7 +++---- bin/importmap | 4 ++++ config/importmap.rb | 1 - 6 files changed, 15 insertions(+), 5 deletions(-) create mode 100755 bin/importmap diff --git a/Gemfile b/Gemfile index 0bd054c2d..d175d666e 100644 --- a/Gemfile +++ b/Gemfile @@ -7,6 +7,7 @@ gem 'rails', '~> 8.0.3' gem 'pg', '~> 1.5' gem 'puma', '~> 6.4' gem 'sass-rails', '~> 6.0' +gem 'importmap-rails' gem 'turbo-rails' gem 'stimulus-rails' gem 'jbuilder', '~> 2.13' diff --git a/Gemfile.lock b/Gemfile.lock index 0dcf45eaf..802d7f6ce 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -141,6 +141,10 @@ GEM image_processing (1.14.0) mini_magick (>= 4.9.5, < 6) ruby-vips (>= 2.0.17, < 3) + importmap-rails (2.2.2) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) io-console (0.8.1) irb (1.15.3) pp (>= 0.6.0) @@ -464,6 +468,7 @@ DEPENDENCIES factory_bot_rails (~> 6.4) faker (~> 3.2) image_processing (~> 1.12) + importmap-rails jbuilder (~> 2.13) jquery-rails listen (~> 3.3) diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js index 3fcd8f45d..4efd29c27 100644 --- a/app/assets/config/manifest.js +++ b/app/assets/config/manifest.js @@ -1,3 +1,5 @@ //= link_tree ../images //= link_directory ../stylesheets .css +//= link_tree ../../javascript .js +//= link_tree ../../../vendor/javascript .js diff --git a/app/javascript/application.js b/app/javascript/application.js index 84fc636b7..eb07ec3b8 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -1,5 +1,4 @@ // Entry point for the build script in your package.json -import '@hotwired/turbo-rails' -import './controllers' -import 'bootstrap/dist/js/bootstrap.bundle.min.js' - +import "@hotwired/turbo-rails" +import "controllers" +import "bootstrap" diff --git a/bin/importmap b/bin/importmap new file mode 100755 index 000000000..36502ab16 --- /dev/null +++ b/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/config/importmap.rb b/config/importmap.rb index 1524d5de7..aa67c56fe 100644 --- a/config/importmap.rb +++ b/config/importmap.rb @@ -10,4 +10,3 @@ pin_all_from "app/javascript/controllers", under: "controllers" pin_all_from "app/javascript/channels", under: "channels" - From 238afa9dcc164526deef843a19fa1c2f3dbf5694 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Wed, 5 Nov 2025 10:06:40 -0300 Subject: [PATCH 05/12] Update Gemfile to specify selenium-webdriver version >= 4.11, remove webdrivers dependency, and adjust Gemfile.lock accordingly. Modify development and production environments to set active storage service to local. Refactor db/seeds.rb to use assign_attributes for user creation and update output message for admin user creation. --- Gemfile | 3 +-- Gemfile.lock | 13 +++++-------- config/environments/development.rb | 1 + config/environments/production.rb | 1 + db/seeds.rb | 30 +++++++++++++++++------------- 5 files changed, 25 insertions(+), 23 deletions(-) diff --git a/Gemfile b/Gemfile index d175d666e..ace47d0a7 100644 --- a/Gemfile +++ b/Gemfile @@ -47,8 +47,7 @@ group :development, :test do gem 'database_cleaner-active_record', '~> 2.2' gem 'simplecov', require: false gem 'capybara', '~> 3.40' - gem 'selenium-webdriver' - gem 'webdrivers' + gem 'selenium-webdriver', '>= 4.11' end group :development do diff --git a/Gemfile.lock b/Gemfile.lock index 802d7f6ce..a0432cc53 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -373,9 +373,11 @@ GEM sprockets-rails tilt securerandom (0.4.1) - selenium-webdriver (4.10.0) + selenium-webdriver (4.38.0) + base64 (~> 0.2) + logger (~> 1.4) rexml (~> 3.2, >= 3.2.5) - rubyzip (>= 1.2.2, < 3.0) + rubyzip (>= 1.2.2, < 4.0) websocket (~> 1.0) shoulda-matchers (6.5.0) activesupport (>= 5.2.0) @@ -430,10 +432,6 @@ GEM activemodel (>= 6.0.0) bindex (>= 0.4.0) railties (>= 6.0.0) - webdrivers (5.3.1) - nokogiri (~> 1.6) - rubyzip (>= 1.3.0) - selenium-webdriver (~> 4.0, < 4.11) webmock (3.26.1) addressable (>= 2.8.0) crack (>= 0.3.2) @@ -488,7 +486,7 @@ DEPENDENCIES rubocop-rails (~> 2.24) rubocop-rspec (~> 2.26) sass-rails (~> 6.0) - selenium-webdriver + selenium-webdriver (>= 4.11) shoulda-matchers (~> 6.3) sidekiq (~> 7.2) simplecov @@ -497,7 +495,6 @@ DEPENDENCIES turbo-rails vcr (~> 6.3) web-console (>= 4.2.0) - webdrivers webmock (~> 3.23) RUBY VERSION diff --git a/config/environments/development.rb b/config/environments/development.rb index fcd711cb5..0563d02a1 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -35,6 +35,7 @@ # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.variant_processor = :mini_magick + config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false diff --git a/config/environments/production.rb b/config/environments/production.rb index 570c7f0fc..a9182e499 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -39,6 +39,7 @@ # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.variant_processor = :mini_magick + config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil diff --git a/db/seeds.rb b/db/seeds.rb index 47a521096..bbdc5f00c 100644 --- a/db/seeds.rb +++ b/db/seeds.rb @@ -3,23 +3,27 @@ # The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). # Create admin user -admin = User.find_or_create_by(email: 'admin@example.com') do |user| - user.full_name = 'Admin User' - user.password = 'password123' - user.password_confirmation = 'password123' - user.role = :admin -end +admin = User.find_or_initialize_by(email: 'admin@example.com') +admin.assign_attributes( + full_name: 'Admin User', + password: 'password123', + password_confirmation: 'password123', + role: :admin +) +admin.save! -puts "Admin user created: #{admin.email}" +puts "Admin user #{admin.persisted? ? 'updated' : 'created'}: #{admin.email}" # Create some sample users 10.times do |i| - User.find_or_create_by(email: "user#{i + 1}@example.com") do |user| - user.full_name = Faker::Name.name - user.password = 'password123' - user.password_confirmation = 'password123' - user.role = :user - end + user = User.find_or_initialize_by(email: "user#{i + 1}@example.com") + user.assign_attributes( + full_name: Faker::Name.name, + password: 'password123', + password_confirmation: 'password123', + role: :user + ) + user.save! end puts "Sample users created" From 8143056e520b9da633ec0571c572b37549cdcec3 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Wed, 5 Nov 2025 11:56:49 -0300 Subject: [PATCH 06/12] Implement user authentication enhancements: add guest session functionality, update navigation and sidebar links to use admin_root_path, and improve user profile update logic with current password validation. Enhance user management UI with new styles and structure for registration and login forms, including password visibility toggle. Update flash message handling for better user experience. --- app/assets/stylesheets/application.scss | 485 +++++++++++++++++++ app/controllers/admin/base_controller.rb | 2 + app/controllers/application_controller.rb | 2 +- app/controllers/guest_sessions_controller.rb | 18 + app/controllers/home_controller.rb | 9 +- app/controllers/profiles_controller.rb | 26 +- app/controllers/users/sessions_controller.rb | 2 +- app/javascript/application.js | 351 ++++++++++++++ app/views/admin/shared/_sidebar.html.erb | 2 +- app/views/admin/users/index.html.erb | 99 ++-- app/views/layouts/_flash_messages.html.erb | 4 +- app/views/layouts/_navbar.html.erb | 36 +- app/views/layouts/admin.html.erb | 10 +- app/views/profiles/edit.html.erb | 5 +- app/views/users/registrations/new.html.erb | 122 +++-- app/views/users/sessions/new.html.erb | 93 ++-- config/application.rb | 3 + config/initializers/active_storage.rb | 14 + config/routes.rb | 3 + 19 files changed, 1155 insertions(+), 131 deletions(-) create mode 100644 app/controllers/guest_sessions_controller.rb diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 6f0525348..5ecba509d 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -15,8 +15,415 @@ body { background-color: #f8f9fa; } +// Auth Pages Styles (Login/Signup) +.auth-container { + min-height: calc(100vh - 200px); + display: flex; + align-items: center; + justify-content: center; + padding: 2rem 1rem; + background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); +} + +.auth-card { + background: #343a40; + border-radius: 1rem; + padding: 3rem; + width: 100%; + max-width: 450px; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); +} + +.auth-header { + text-align: center; + margin-bottom: 2rem; + + .auth-title { + color: #fff; + font-size: 2rem; + font-weight: 700; + margin-bottom: 0.5rem; + } + + .auth-subtitle { + color: #fff; + font-size: 1.5rem; + font-weight: 600; + margin-bottom: 0.25rem; + } + + .auth-description { + color: #adb5bd; + font-size: 0.9rem; + margin-bottom: 0; + } +} + +.auth-form { + margin-bottom: 1.5rem; +} + +.auth-input-group { + position: relative; + margin-bottom: 1rem; + + .auth-icon { + position: absolute; + left: 1rem; + top: 50%; + transform: translateY(-50%); + color: #adb5bd; + font-size: 1.1rem; + z-index: 1; + } + + .auth-icon-right { + position: absolute; + right: 1rem; + top: 50%; + transform: translateY(-50%); + color: #adb5bd; + font-size: 1.1rem; + z-index: 1; + } + + .auth-input { + width: 100%; + padding: 0.75rem 1rem 0.75rem 3rem; + background-color: #495057; + border: 1px solid #6c757d; + border-radius: 0.5rem; + color: #fff; + font-size: 1rem; + transition: all 0.3s ease; + + &:focus { + outline: none; + border-color: #007bff; + background-color: #545b62; + box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25); + } + + &::placeholder { + color: #adb5bd; + } + } + + .auth-input-hint { + display: block; + margin-top: 0.25rem; + color: #adb5bd; + font-size: 0.75rem; + } +} + +.auth-alert { + background-color: #dc3545; + color: #fff; + padding: 1rem; + border-radius: 0.5rem; + margin-bottom: 1.5rem; + font-size: 0.9rem; + + ul { + padding-left: 1.5rem; + margin-top: 0.5rem; + } +} + +.auth-options { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1.5rem; + + .auth-checkbox { + display: flex; + align-items: center; + + .form-check-input { + margin-right: 0.5rem; + margin-top: 0; + } + + .auth-checkbox-label { + color: #adb5bd; + font-size: 0.9rem; + margin: 0; + cursor: pointer; + } + } + + .auth-forgot-link { + color: #007bff; + text-decoration: none; + font-size: 0.9rem; + transition: color 0.3s ease; + + &:hover { + color: #0056b3; + text-decoration: underline; + } + } +} + +.auth-actions { + margin-bottom: 1.5rem; + + .auth-button { + width: 100%; + padding: 0.75rem; + border-radius: 0.5rem; + font-size: 1rem; + font-weight: 600; + border: none; + cursor: pointer; + transition: all 0.3s ease; + display: flex; + align-items: center; + justify-content: center; + + &.auth-button-primary { + background: #007bff; + color: #fff; + + &:hover { + background: #0056b3; + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4); + } + } + + &.auth-button-secondary { + background: transparent; + color: #007bff; + border: 2px solid #007bff; + + &:hover { + background: #007bff; + color: #fff; + transform: translateY(-2px); + box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4); + } + } + } +} + +.auth-divider { + text-align: center; + margin: 1.5rem 0; + position: relative; + + &::before { + content: ''; + position: absolute; + left: 0; + top: 50%; + width: 100%; + height: 1px; + background: #6c757d; + } + + span { + background: #343a40; + color: #adb5bd; + padding: 0 1rem; + position: relative; + font-size: 0.9rem; + } +} + +.auth-footer { + text-align: center; + margin-top: 2rem; + + .auth-footer-text { + color: #adb5bd; + font-size: 0.9rem; + margin-bottom: 1rem; + + .auth-link { + color: #007bff; + text-decoration: none; + font-weight: 600; + transition: color 0.3s ease; + + &:hover { + color: #0056b3; + text-decoration: underline; + } + } + } + + .auth-copyright { + color: #6c757d; + font-size: 0.75rem; + margin: 0; + } +} + +// User Dropdown Menu Styles +.user-dropdown-menu { + min-width: 220px; + padding: 0.5rem 0; + border: 1px solid rgba(0, 0, 0, 0.15); + box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); + + .user-dropdown-item { + display: flex; + align-items: center; + padding: 0.75rem 1.25rem; + color: #212529; + text-decoration: none; + transition: all 0.2s ease; + border: none; + background: transparent; + width: 100%; + text-align: left; + font-size: 0.95rem; + + i { + font-size: 1.1rem; + width: 20px; + color: #6c757d; + transition: color 0.2s ease; + } + + span { + flex: 1; + color: #212529; + } + + &:hover { + background-color: #f8f9fa; + color: #007bff; + + i { + color: #007bff; + } + + span { + color: #007bff; + } + } + } + + .user-dropdown-form { + margin: 0; + padding: 0; + + button { + display: flex; + align-items: center; + width: 100%; + padding: 0.75rem 1.25rem; + border: none; + background: transparent; + color: #212529; + text-align: left; + font-size: 0.95rem; + cursor: pointer; + transition: all 0.2s ease; + + i { + font-size: 1.1rem; + width: 20px; + color: #6c757d; + margin-right: 0.5rem; + transition: color 0.2s ease; + } + + span { + flex: 1; + color: #212529; + } + + &:hover { + background-color: #f8f9fa; + color: #007bff; + + i { + color: #007bff; + } + + span { + color: #007bff; + } + } + } + } +} + .navbar { box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + position: relative; + z-index: 1030; + + .nav-link { + transition: color 0.2s ease; + + &.active { + color: #fff !important; + font-weight: 600; + background-color: rgba(255, 255, 255, 0.1); + border-radius: 0.25rem; + } + } + + .navbar-nav { + .nav-item.dropdown { + position: relative; + } + + .dropdown-menu { + margin-top: 0; + min-width: 180px; + z-index: 1050 !important; + position: absolute; + top: 100%; + right: 0; + left: auto; + border: 1px solid rgba(0, 0, 0, 0.15); + box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15); + + &.dropdown-menu-end { + right: 0 !important; + left: auto !important; + transform: translateX(0) !important; + } + } + } + + .dropdown-item { + &.border-0 { + padding: 0.5rem 1rem; + cursor: pointer; + + &:hover { + background-color: #f8f9fa; + color: #212529; + } + } + } + + .dropdown-item form { + margin: 0; + + button { + width: 100%; + text-align: left; + padding: 0.5rem 1rem; + border: 0; + background: transparent; + color: inherit; + cursor: pointer; + + &:hover { + background-color: #f8f9fa; + color: #212529; + } + } + } } .card { @@ -48,6 +455,25 @@ body { border-radius: 50%; } +.avatar-medium { + width: 50px; + height: 50px; + object-fit: cover; + border-radius: 50%; + border: 2px solid #e9ecef; + transition: transform 0.2s ease, box-shadow 0.2s ease; +} + +.avatar-wrapper { + display: inline-block; + position: relative; + + &:hover .avatar-medium { + transform: scale(1.1); + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15); + } +} + .progress-bar-animated { animation: progress-bar-stripes 1s linear infinite; } @@ -79,3 +505,62 @@ body { } } +// Users table styles +.users-header { + h1 { + font-size: 2rem; + font-weight: 600; + color: #212529; + } +} + +.users-table { + thead th { + font-weight: 600; + font-size: 0.875rem; + text-transform: uppercase; + letter-spacing: 0.5px; + color: #6c757d; + border-bottom: 2px solid #dee2e6; + padding: 1rem 0.75rem; + } + + tbody td { + padding: 1rem 0.75rem; + vertical-align: middle; + } + + .user-row { + transition: background-color 0.2s ease; + + &:hover { + background-color: #f8f9fa; + } + } + + .role-badge { + padding: 0.5em 0.75em; + font-size: 0.75rem; + font-weight: 600; + letter-spacing: 0.5px; + } + + .btn-group { + .btn { + border-radius: 0.25rem; + margin: 0 2px; + padding: 0.375rem 0.75rem; + transition: all 0.2s ease; + + &:hover { + transform: translateY(-1px); + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); + } + + i { + font-size: 0.875rem; + } + } + } +} + diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb index d7a9cfe09..0d498406e 100644 --- a/app/controllers/admin/base_controller.rb +++ b/app/controllers/admin/base_controller.rb @@ -1,4 +1,6 @@ class Admin::BaseController < ApplicationController + layout 'admin' + before_action :ensure_admin private diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 4303ebf34..4c9024e09 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -15,7 +15,7 @@ def configure_permitted_parameters def after_sign_in_path_for(resource) if resource.admin? - admin_dashboard_path + admin_root_path else profile_path end diff --git a/app/controllers/guest_sessions_controller.rb b/app/controllers/guest_sessions_controller.rb new file mode 100644 index 000000000..54cae521a --- /dev/null +++ b/app/controllers/guest_sessions_controller.rb @@ -0,0 +1,18 @@ +class GuestSessionsController < ApplicationController + skip_before_action :authenticate_user! + + def create + # Cria um usuário visitante temporário + guest_email = "guest_#{SecureRandom.hex(8)}@guest.temp" + guest_user = User.create!( + email: guest_email, + full_name: "Usuário Visitante", + password: SecureRandom.hex(16), + role: :user + ) + + sign_in(guest_user) + redirect_to profile_path, notice: 'Você entrou como visitante. Sua conta será temporária.' + end +end + diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb index d95bf22ff..adce0a62c 100644 --- a/app/controllers/home_controller.rb +++ b/app/controllers/home_controller.rb @@ -2,8 +2,13 @@ class HomeController < ApplicationController skip_before_action :authenticate_user!, only: [:index] def index - redirect_to admin_dashboard_path if user_signed_in? && current_user.admin? - redirect_to profile_path if user_signed_in? && !current_user.admin? + if user_signed_in? + if current_user.admin? + redirect_to admin_root_path + else + redirect_to profile_path + end + end end end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb index 8a4b253fb..343844c86 100644 --- a/app/controllers/profiles_controller.rb +++ b/app/controllers/profiles_controller.rb @@ -12,13 +12,35 @@ def edit def update authorize @user - # Handle password update separately + # Valida senha atual se houver mudança de senha ou email + current_password = params[:user][:current_password] + password_changed = params[:user][:password].present? + email_changed = params[:user][:email] != @user.email + + if password_changed || email_changed + if current_password.blank? + @user.errors.add(:current_password, 'is required to change password or email') + render :edit, status: :unprocessable_entity + return + end + + unless @user.valid_password?(current_password) + @user.errors.add(:current_password, 'is incorrect') + render :edit, status: :unprocessable_entity + return + end + end + + # Remove senha se estiver em branco if params[:user][:password].blank? params[:user].delete(:password) params[:user].delete(:password_confirmation) end - if @user.update(user_params) + # Remove current_password dos parâmetros (não é atributo do modelo) + update_params = user_params.except(:current_password) + + if @user.update(update_params) redirect_to profile_path, notice: 'Profile updated successfully.' else render :edit, status: :unprocessable_entity diff --git a/app/controllers/users/sessions_controller.rb b/app/controllers/users/sessions_controller.rb index 9e486057b..75f9ccf45 100644 --- a/app/controllers/users/sessions_controller.rb +++ b/app/controllers/users/sessions_controller.rb @@ -3,7 +3,7 @@ class Users::SessionsController < Devise::SessionsController def after_sign_in_path_for(resource) if resource.admin? - admin_dashboard_path + admin_root_path else profile_path end diff --git a/app/javascript/application.js b/app/javascript/application.js index eb07ec3b8..49e0bdbaf 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -2,3 +2,354 @@ import "@hotwired/turbo-rails" import "controllers" import "bootstrap" + +// Função global para fechar alerts - pode ser chamada via onclick inline +window.closeAlert = function(button) { + const alert = button.closest('.alert, .alert-dismissible, [data-alert-dismissible="true"]') + if (alert) { + alert.style.transition = 'opacity 0.15s linear' + alert.style.opacity = '0' + setTimeout(() => { + alert.remove() + }, 150) + } + return false +} + +// Função global para toggle dropdown - pode ser chamada via onclick inline +window.toggleDropdown = function(button) { + const dropdown = button.closest('.dropdown') + if (!dropdown) return false + + const menu = dropdown.querySelector('.dropdown-menu') + if (!menu) return false + + const isOpen = menu.classList.contains('show') + + // Fecha outros dropdowns + document.querySelectorAll('.dropdown-menu.show').forEach(m => { + if (m !== menu) { + m.classList.remove('show') + const toggle = m.closest('.dropdown')?.querySelector('[data-bs-toggle]') + if (toggle) toggle.setAttribute('aria-expanded', 'false') + } + }) + + // Toggle do dropdown atual + if (isOpen) { + menu.classList.remove('show') + button.setAttribute('aria-expanded', 'false') + } else { + menu.classList.add('show') + button.setAttribute('aria-expanded', 'true') + } + + return false +} + +// Função para obter o Bootstrap de diferentes formas +function getBootstrap() { + // Tenta diferentes formas de acessar o Bootstrap + if (window.bootstrap) { + return window.bootstrap + } + if (typeof bootstrap !== 'undefined') { + return bootstrap + } + // Tenta acessar via módulo importado + if (window.bootstrapModule) { + return window.bootstrapModule + } + return null +} + +// Função para inicializar componentes do Bootstrap após o Turbo carregar +function initializeBootstrap() { + const Bootstrap = getBootstrap() + + if (!Bootstrap) { + // Aguarda Bootstrap carregar + setTimeout(initializeBootstrap, 100) + return + } + + // Inicializa todos os dropdowns + document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(element => { + try { + // Remove instância anterior se existir + const instance = Bootstrap.Dropdown.getInstance(element) + if (instance) { + instance.dispose() + } + // Cria nova instância + new Bootstrap.Dropdown(element) + } catch (error) { + console.error('Erro ao inicializar dropdown:', error) + // Fallback: adiciona listener manual + addManualDropdownListener(element) + } + }) + + // Inicializa alerts dismissíveis + initializeAlerts() +} + +// Função para inicializar alerts do Bootstrap +function initializeAlerts() { + const Bootstrap = getBootstrap() + + // Inicializa alerts via Bootstrap se disponível + if (Bootstrap) { + document.querySelectorAll('.alert-dismissible').forEach(alert => { + try { + // Bootstrap já inicializa automaticamente com data-bs-dismiss, mas garantimos + const alertInstance = Bootstrap.Alert.getInstance(alert) + if (!alertInstance) { + new Bootstrap.Alert(alert) + } + } catch (error) { + // Fallback manual + addManualAlertListener(alert) + } + }) + } else { + // Se Bootstrap não estiver disponível, usa fallback manual + document.querySelectorAll('.alert-dismissible').forEach(alert => { + addManualAlertListener(alert) + }) + } +} + +// Fallback manual para fechar alerts +function addManualAlertListener(alert) { + const closeButton = alert.querySelector('.btn-close') + if (!closeButton) return + + // Remove listeners anteriores para evitar duplicação + const newButton = closeButton.cloneNode(true) + closeButton.parentNode.replaceChild(newButton, closeButton) + + newButton.addEventListener('click', function(e) { + e.preventDefault() + e.stopPropagation() + + const alertElement = this.closest('.alert') + if (!alertElement) return + + // Adiciona classe fade-out + alertElement.classList.add('fade') + alertElement.classList.remove('show') + + // Remove o elemento após animação + setTimeout(() => { + alertElement.remove() + }, 150) + }, true) // usa capture phase +} + +// Fallback manual para dropdown se Bootstrap não funcionar +function addManualDropdownListener(element) { + // Verifica se já tem listener manual + if (element.dataset.manualDropdown === 'true') { + return + } + element.dataset.manualDropdown = 'true' + + // Encontra o menu dropdown (pode ser próximo elemento ou dentro do parent) + let dropdownMenu = element.nextElementSibling + if (!dropdownMenu || !dropdownMenu.classList.contains('dropdown-menu')) { + const dropdown = element.closest('.dropdown') + if (dropdown) { + dropdownMenu = dropdown.querySelector('.dropdown-menu') + } + } + + if (!dropdownMenu) { + console.warn('Dropdown menu não encontrado para:', element) + return + } + + element.addEventListener('click', function(e) { + e.preventDefault() + e.stopPropagation() + + const isOpen = dropdownMenu.classList.contains('show') + + // Fecha outros dropdowns + document.querySelectorAll('.dropdown-menu.show').forEach(menu => { + if (menu !== dropdownMenu) { + menu.classList.remove('show') + const toggle = menu.previousElementSibling || + menu.closest('.dropdown')?.querySelector('[data-bs-toggle="dropdown"]') + if (toggle) { + toggle.setAttribute('aria-expanded', 'false') + } + } + }) + + // Toggle do dropdown atual + if (isOpen) { + dropdownMenu.classList.remove('show') + element.setAttribute('aria-expanded', 'false') + } else { + dropdownMenu.classList.add('show') + element.setAttribute('aria-expanded', 'true') + } + }, true) // usa capture phase para garantir que seja executado + + // Fecha dropdown ao clicar fora + const clickOutsideHandler = function(e) { + if (!element.contains(e.target) && !dropdownMenu.contains(e.target)) { + dropdownMenu.classList.remove('show') + element.setAttribute('aria-expanded', 'false') + } + } + + document.addEventListener('click', clickOutsideHandler, true) +} + +// Inicializa após o Turbo carregar (importante para SPA) +document.addEventListener("turbo:load", initializeBootstrap) + +// Inicializa no carregamento inicial +if (document.readyState === 'loading') { + document.addEventListener("DOMContentLoaded", initializeBootstrap) +} else { + initializeBootstrap() +} + +// Adiciona fallback manual sempre (garante funcionamento) +document.addEventListener("turbo:load", () => { + setTimeout(() => { + document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(element => { + const Bootstrap = getBootstrap() + // Se Bootstrap não estiver disponível ou não tiver instância, usa fallback manual + if (!Bootstrap) { + addManualDropdownListener(element) + } else { + try { + const instance = Bootstrap.Dropdown.getInstance(element) + if (!instance) { + addManualDropdownListener(element) + } + } catch (error) { + addManualDropdownListener(element) + } + } + }) + }, 300) +}) + +// Também aplica no carregamento inicial +setTimeout(() => { + document.querySelectorAll('[data-bs-toggle="dropdown"]').forEach(element => { + const Bootstrap = getBootstrap() + if (!Bootstrap) { + addManualDropdownListener(element) + } else { + try { + const instance = Bootstrap.Dropdown.getInstance(element) + if (!instance) { + addManualDropdownListener(element) + } + } catch (error) { + addManualDropdownListener(element) + } + } + }) + + // Inicializa alerts também + initializeAlerts() +}, 300) + +// Event delegation para dropdowns - funciona sempre, independente de quando o elemento é criado +document.addEventListener('click', function(e) { + // Verifica se o clique foi em um elemento com data-bs-toggle="dropdown" ou no botão do dropdown + const dropdownToggle = e.target.closest('[data-bs-toggle="dropdown"]') || + (e.target.closest('.dropdown-toggle') && e.target.closest('.dropdown')?.querySelector('[data-bs-toggle="dropdown"]')) + + if (dropdownToggle) { + e.preventDefault() + e.stopPropagation() + + const dropdown = dropdownToggle.closest('.dropdown') + if (!dropdown) return + + const dropdownMenu = dropdown.querySelector('.dropdown-menu') + if (!dropdownMenu) return + + const isOpen = dropdownMenu.classList.contains('show') + + // Fecha outros dropdowns + document.querySelectorAll('.dropdown-menu.show').forEach(menu => { + if (menu !== dropdownMenu) { + menu.classList.remove('show') + const toggle = menu.closest('.dropdown')?.querySelector('[data-bs-toggle="dropdown"]') + if (toggle) { + toggle.setAttribute('aria-expanded', 'false') + } + } + }) + + // Toggle do dropdown atual + if (isOpen) { + dropdownMenu.classList.remove('show') + dropdownToggle.setAttribute('aria-expanded', 'false') + } else { + dropdownMenu.classList.add('show') + dropdownToggle.setAttribute('aria-expanded', 'true') + } + + return false + } + + // Fecha dropdowns ao clicar fora + const clickedDropdown = e.target.closest('.dropdown') + if (!clickedDropdown) { + document.querySelectorAll('.dropdown-menu.show').forEach(menu => { + menu.classList.remove('show') + const toggle = menu.closest('.dropdown')?.querySelector('[data-bs-toggle="dropdown"]') + if (toggle) { + toggle.setAttribute('aria-expanded', 'false') + } + }) + } +}, true) // capture phase + +// Event delegation para fechar alerts - funciona sempre, independente de quando o elemento é criado +document.addEventListener('click', function(e) { + // Verifica se o clique foi em um botão de fechar alert + const closeButton = e.target.classList.contains('btn-close') ? e.target : e.target.closest('.btn-close') + + if (closeButton) { + const alert = closeButton.closest('.alert-dismissible, [data-alert-dismissible="true"]') + + if (alert) { + e.preventDefault() + e.stopPropagation() + e.stopImmediatePropagation() + + // Fecha o alert imediatamente + alert.style.transition = 'opacity 0.15s linear' + alert.style.opacity = '0' + + setTimeout(() => { + alert.remove() + }, 150) + + return false + } + } +}, true) // capture phase - executa ANTES de qualquer outro handler + +// Inicializa alerts após Turbo carregar +document.addEventListener("turbo:load", () => { + setTimeout(initializeAlerts, 100) +}) + +// Inicializa alerts no carregamento inicial +if (document.readyState === 'loading') { + document.addEventListener("DOMContentLoaded", initializeAlerts) +} else { + setTimeout(initializeAlerts, 100) +} diff --git a/app/views/admin/shared/_sidebar.html.erb b/app/views/admin/shared/_sidebar.html.erb index 9cb7dce18..5625e1ee8 100644 --- a/app/views/admin/shared/_sidebar.html.erb +++ b/app/views/admin/shared/_sidebar.html.erb @@ -4,7 +4,7 @@
  • - <%= link_to 'Dashboard', admin_dashboard_path, class: 'text-decoration-none' %> + <%= link_to 'Dashboard', admin_root_path, class: 'text-decoration-none' %>
  • <%= link_to 'Users', admin_users_path, class: 'text-decoration-none' %> diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index 742f53550..8dcc5f8bf 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -1,41 +1,84 @@ -
    -

    Users

    - <%= link_to 'New User', new_admin_user_path, class: 'btn btn-primary' %> +
    +
    +
    +

    Users

    +

    + <%= @users&.count || 0 %> total users +

    +
    + <%= link_to new_admin_user_path, class: 'btn btn-primary btn-lg' do %> + New User + <% end %> +
    -
    -
    +
    +
    - - +
    + - + - - - + + + - <% @users.each do |user| %> + <% if @users.present? %> + <% @users.each do |user| %> + + + + + + + + + <% end %> + <% else %> - - - - - - <% end %> diff --git a/app/views/layouts/_flash_messages.html.erb b/app/views/layouts/_flash_messages.html.erb index 5d7890a40..b61b88b74 100644 --- a/app/views/layouts/_flash_messages.html.erb +++ b/app/views/layouts/_flash_messages.html.erb @@ -1,7 +1,7 @@ <% flash.each do |type, message| %> -
    - <%= form.label :current_password, 'Current Password (required to update)', class: 'form-label' %> - <%= form.password_field :current_password, class: 'form-control', autocomplete: 'current-password', required: true %> + <%= form.label :current_password, 'Current Password (required only to change password or email)', class: 'form-label' %> + <%= form.password_field :current_password, class: 'form-control', autocomplete: 'current-password' %> + Required only if you're changing your password or email
    diff --git a/app/views/users/registrations/new.html.erb b/app/views/users/registrations/new.html.erb index c29e0f438..4f1303da2 100644 --- a/app/views/users/registrations/new.html.erb +++ b/app/views/users/registrations/new.html.erb @@ -1,57 +1,87 @@ -
    -
    -
    -
    -

    Sign Up

    -
    -
    - <%= form_with model: resource, as: resource_name, url: registration_path(resource_name), local: true, data: { turbo: false } do |form| %> - <% if resource.errors.any? %> -
    -
    <%= pluralize(resource.errors.count, 'error') %> prohibited this user from being saved:
    -
      - <% resource.errors.full_messages.each do |message| %> -
    • <%= message %>
    • - <% end %> -
    -
    - <% end %> - -
    - <%= form.label :full_name, class: 'form-label' %> - <%= form.text_field :full_name, autofocus: true, class: 'form-control', required: true, minlength: 2, maxlength: 100 %> -
    - -
    - <%= form.label :email, class: 'form-label' %> - <%= form.email_field :email, autocomplete: 'email', class: 'form-control', required: true %> -
    - -
    - <%= form.label :password, class: 'form-label' %> - <% if @minimum_password_length %> - (<%= @minimum_password_length %> characters minimum) +
    +
    +
    +

    User Management

    +

    Criar Conta

    +

    Preencha os dados abaixo para criar sua conta

    +
    + + <%= form_with model: resource, as: resource_name, url: registration_path(resource_name), local: true, data: { turbo: false }, class: 'auth-form' do |form| %> + <% if resource.errors.any? %> +
    + Erro ao criar conta: +
      + <% resource.errors.full_messages.each do |message| %> +
    • <%= message %>
    • <% end %> - <%= form.password_field :password, autocomplete: 'new-password', class: 'form-control', required: true, minlength: 6 %> -
    + +
    + <% end %> + +
    + + <%= form.text_field :full_name, autofocus: true, class: 'auth-input', placeholder: 'Digite seu nome completo', required: true, minlength: 2, maxlength: 100 %> +
    -
    - <%= form.label :password_confirmation, class: 'form-label' %> - <%= form.password_field :password_confirmation, autocomplete: 'new-password', class: 'form-control', required: true, minlength: 6 %> -
    +
    + + <%= form.email_field :email, autocomplete: 'email', class: 'auth-input', placeholder: 'Digite seu e-mail', required: true %> +
    -
    - <%= form.submit 'Sign Up', class: 'btn btn-primary' %> -
    +
    + + <%= form.password_field :password, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Digite sua senha', required: true, minlength: 6, id: 'password-field' %> + + <% if @minimum_password_length %> + Mínimo de <%= @minimum_password_length %> caracteres <% end %> +
    -
    +
    + + <%= form.password_field :password_confirmation, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Confirme sua senha', required: true, minlength: 6, id: 'password-confirmation-field' %> + +
    -
    - <%= link_to 'Sign in', new_user_session_path, class: 'btn btn-link' %> -
    +
    + <%= form.submit 'Criar Conta', class: 'auth-button auth-button-primary' %>
    + <% end %> + +
    + + diff --git a/app/views/users/sessions/new.html.erb b/app/views/users/sessions/new.html.erb index 9008543ea..e32aa59d6 100644 --- a/app/views/users/sessions/new.html.erb +++ b/app/views/users/sessions/new.html.erb @@ -1,41 +1,74 @@ -
    -
    -
    -
    -

    Sign In

    +
    +
    +
    +

    User Management

    +

    Bem-vindo!

    +

    Informe suas credenciais para entrar

    +
    + + <%= form_with model: resource, as: resource_name, url: session_path(resource_name), local: true, data: { turbo: false }, class: 'auth-form' do |form| %> +
    + + <%= form.email_field :email, autofocus: true, autocomplete: 'email', class: 'auth-input', placeholder: 'Digite seu e-mail', required: true %>
    -
    - <%= form_with model: resource, as: resource_name, url: session_path(resource_name), local: true, data: { turbo: false } do |form| %> -
    - <%= form.label :email, class: 'form-label' %> - <%= form.email_field :email, autofocus: true, autocomplete: 'email', class: 'form-control', required: true %> -
    -
    - <%= form.label :password, class: 'form-label' %> - <%= form.password_field :password, autocomplete: 'current-password', class: 'form-control', required: true %> +
    + + <%= form.password_field :password, autocomplete: 'current-password', class: 'auth-input', placeholder: 'Digite sua senha', required: true, id: 'password-field' %> + +
    + + <% if devise_mapping.rememberable? %> +
    +
    + <%= form.check_box :remember_me, class: 'form-check-input', id: 'remember-me' %> +
    + <%= link_to 'Esqueci minha senha', new_user_password_path, class: 'auth-forgot-link' %> +
    + <% end %> - <% if devise_mapping.rememberable? %> -
    - <%= form.check_box :remember_me, class: 'form-check-input' %> - <%= form.label :remember_me, class: 'form-check-label' %> -
    - <% end %> +
    + <%= form.submit 'Entrar', class: 'auth-button auth-button-primary' %> +
    + <% end %> -
    - <%= form.submit 'Sign In', class: 'btn btn-primary' %> -
    - <% end %> +
    + ou +
    -
    +
    + <%= form_with url: guest_session_path, method: :post, local: true, class: 'd-inline w-100' do |form| %> + + <% end %> +
    -
    - <%= link_to 'Sign up', new_user_registration_path, class: 'btn btn-link' %> - <%= link_to 'Forgot your password?', new_user_password_path, class: 'btn btn-link' %> -
    -
    +
    + + diff --git a/config/application.rb b/config/application.rb index be95d6d3b..fd8ce7f92 100644 --- a/config/application.rb +++ b/config/application.rb @@ -26,6 +26,9 @@ class Application < Rails::Application # Set time zone config.time_zone = 'UTC' config.active_record.default_timezone = :utc + + # Configure Active Storage service (will be overridden by environment files) + config.active_storage.service = :local # Generators configuration config.generators do |g| diff --git a/config/initializers/active_storage.rb b/config/initializers/active_storage.rb index f4dcad790..2e2553126 100644 --- a/config/initializers/active_storage.rb +++ b/config/initializers/active_storage.rb @@ -2,3 +2,17 @@ Rails.application.config.active_storage.variant_processor = :mini_magick +# Configure Active Storage service based on environment +# This must be set before models with Active Storage attachments are loaded +Rails.application.config.active_storage.service = + case Rails.env.to_s + when 'development' + :local + when 'test' + :test + when 'production' + :local + else + :local + end + diff --git a/config/routes.rb b/config/routes.rb index 94db3f785..e8288a5b0 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -11,6 +11,9 @@ sessions: 'users/sessions' } + # Guest session + post 'guest_session', to: 'guest_sessions#create', as: 'guest_session' + # User profile resource :profile, only: [:show, :edit, :update, :destroy], controller: 'profiles' From 57f330b52c9932bf63bbd5efea536d126d31f538 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Wed, 5 Nov 2025 12:27:30 -0300 Subject: [PATCH 07/12] Revamp authentication UI: enhance styles for login and registration forms, implement light-themed containers, and update text for improved clarity. Adjust layout rendering based on authentication paths and refine button styles for a more cohesive user experience. --- app/assets/stylesheets/application.scss | 251 ++++++++++++++++++--- app/views/home/index.html.erb | 45 +++- app/views/layouts/application.html.erb | 7 +- app/views/users/registrations/new.html.erb | 28 +-- app/views/users/sessions/new.html.erb | 28 +-- 5 files changed, 282 insertions(+), 77 deletions(-) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 5ecba509d..76bc64332 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -17,45 +17,103 @@ body { // Auth Pages Styles (Login/Signup) .auth-container { - min-height: calc(100vh - 200px); + min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem 1rem; - background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); + background: linear-gradient(135deg, #1a1d29 0%, #2d3748 50%, #1a1d29 100%); + position: relative; + overflow: hidden; + + &::before { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: + radial-gradient(circle at 20% 50%, rgba(0, 123, 255, 0.1) 0%, transparent 50%), + radial-gradient(circle at 80% 80%, rgba(0, 123, 255, 0.15) 0%, transparent 50%); + pointer-events: none; + } + + // Background branco para página inicial com card branco + &.auth-container-light { + background: #ffffff; + + &::before { + display: none; + } + } } .auth-card { - background: #343a40; - border-radius: 1rem; - padding: 3rem; + background: rgba(52, 58, 64, 0.95); + backdrop-filter: blur(10px); + border-radius: 1.5rem; + padding: 3.5rem 3rem; width: 100%; - max-width: 450px; - box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3); + max-width: 480px; + box-shadow: + 0 20px 60px rgba(0, 0, 0, 0.5), + 0 0 0 1px rgba(255, 255, 255, 0.05), + inset 0 1px 0 rgba(255, 255, 255, 0.1); + position: relative; + z-index: 1; + border: 1px solid rgba(255, 255, 255, 0.1); + + &.auth-card-light { + background: #ffffff; + border: none; + box-shadow: + 0 4px 20px rgba(0, 0, 0, 0.08), + 0 1px 4px rgba(0, 0, 0, 0.04); + } } .auth-header { text-align: center; - margin-bottom: 2rem; + margin-bottom: 2.5rem; .auth-title { color: #fff; - font-size: 2rem; + font-size: 2.25rem; font-weight: 700; - margin-bottom: 0.5rem; + margin-bottom: 0.75rem; + letter-spacing: -0.5px; + text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3); } .auth-subtitle { color: #fff; - font-size: 1.5rem; + font-size: 1.75rem; font-weight: 600; - margin-bottom: 0.25rem; + margin-bottom: 0.5rem; + letter-spacing: -0.3px; } .auth-description { color: #adb5bd; - font-size: 0.9rem; + font-size: 0.95rem; margin-bottom: 0; + line-height: 1.5; + } + + .auth-card-light & { + .auth-title { + color: #212529; + text-shadow: none; + } + + .auth-subtitle { + color: #212529; + } + + .auth-description { + color: #6c757d; + } } } @@ -69,43 +127,69 @@ body { .auth-icon { position: absolute; - left: 1rem; + left: 1.25rem; top: 50%; transform: translateY(-50%); color: #adb5bd; - font-size: 1.1rem; + font-size: 1.2rem; z-index: 1; + transition: color 0.3s ease; } .auth-icon-right { position: absolute; - right: 1rem; + right: 1.25rem; top: 50%; transform: translateY(-50%); color: #adb5bd; - font-size: 1.1rem; + font-size: 1.2rem; z-index: 1; + transition: color 0.3s ease; + + &:hover { + color: #007bff; + } + } + + &:focus-within { + .auth-icon { + color: #007bff; + } + } + + // Estilos para card branco - ícone quando focado + .auth-card-light & { + &:focus-within { + .auth-icon { + color: #007bff; + } + } } .auth-input { width: 100%; - padding: 0.75rem 1rem 0.75rem 3rem; - background-color: #495057; - border: 1px solid #6c757d; - border-radius: 0.5rem; + padding: 1rem 1rem 1rem 3.25rem; + background-color: rgba(73, 80, 87, 0.6); + border: 1.5px solid rgba(108, 117, 125, 0.3); + border-radius: 0.75rem; color: #fff; font-size: 1rem; transition: all 0.3s ease; + backdrop-filter: blur(10px); &:focus { outline: none; border-color: #007bff; - background-color: #545b62; - box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25); + background-color: rgba(84, 91, 98, 0.8); + box-shadow: + 0 0 0 4px rgba(0, 123, 255, 0.15), + 0 4px 12px rgba(0, 123, 255, 0.2); + transform: translateY(-1px); } &::placeholder { color: #adb5bd; + opacity: 0.7; } } @@ -115,6 +199,42 @@ body { color: #adb5bd; font-size: 0.75rem; } + + // Estilos para inputs no card branco + .auth-card-light & { + .auth-input { + background-color: #ffffff; + border: 1.5px solid #dee2e6; + color: #212529; + + &:focus { + outline: none; + border-color: #007bff; + background-color: #ffffff; + box-shadow: + 0 0 0 4px rgba(0, 123, 255, 0.15), + 0 2px 8px rgba(0, 123, 255, 0.1); + transform: translateY(-1px); + } + + &::placeholder { + color: #6c757d; + opacity: 0.7; + } + } + + .auth-icon { + color: #6c757d; + } + + .auth-icon-right { + color: #6c757d; + } + + .auth-input-hint { + color: #6c757d; + } + } } .auth-alert { @@ -165,6 +285,13 @@ body { text-decoration: underline; } } + + // Estilos para card branco + .auth-card-light & { + .auth-checkbox-label { + color: #6c757d; + } + } } .auth-actions { @@ -182,36 +309,67 @@ body { display: flex; align-items: center; justify-content: center; + text-decoration: none; &.auth-button-primary { - background: #007bff; + background: linear-gradient(135deg, #007bff 0%, #0056b3 100%); color: #fff; + box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3); &:hover { - background: #0056b3; + background: linear-gradient(135deg, #0056b3 0%, #004085 100%); transform: translateY(-2px); - box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4); + box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4); + color: #fff; + text-decoration: none; + } + + &:active { + transform: translateY(0); } } &.auth-button-secondary { - background: transparent; + background: rgba(0, 123, 255, 0.1); color: #007bff; - border: 2px solid #007bff; + border: 2px solid rgba(0, 123, 255, 0.3); + backdrop-filter: blur(10px); &:hover { - background: #007bff; + background: rgba(0, 123, 255, 0.2); + border-color: #007bff; color: #fff; transform: translateY(-2px); - box-shadow: 0 4px 12px rgba(0, 123, 255, 0.4); + box-shadow: 0 6px 20px rgba(0, 123, 255, 0.3); + text-decoration: none; + } + + &:active { + transform: translateY(0); } } } } +// Estilos específicos para card claro (página inicial, login e registro) +.auth-card-light { + .auth-button-secondary { + background: #e0f2ff; + color: #007bff; + border: 2px solid #007bff; + backdrop-filter: none; + + &:hover { + background: #007bff; + color: #fff; + border-color: #007bff; + } + } +} + .auth-divider { text-align: center; - margin: 1.5rem 0; + margin: 2rem 0; position: relative; &::before { @@ -221,15 +379,28 @@ body { top: 50%; width: 100%; height: 1px; - background: #6c757d; + background: linear-gradient(to right, transparent, rgba(108, 117, 125, 0.5), transparent); } span { - background: #343a40; + background: rgba(52, 58, 64, 0.95); color: #adb5bd; - padding: 0 1rem; + padding: 0 1.5rem; position: relative; - font-size: 0.9rem; + font-size: 0.85rem; + text-transform: uppercase; + letter-spacing: 1px; + } + + .auth-card-light & { + &::before { + background: #e0e0e0; + } + + span { + background: #ffffff; + color: #6c757d; + } } } @@ -260,6 +431,16 @@ body { font-size: 0.75rem; margin: 0; } + + .auth-card-light & { + .auth-footer-text { + color: #6c757d; + } + + .auth-copyright { + color: #adb5bd; + } + } } // User Dropdown Menu Styles diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb index ad3166b5d..199f6f138 100644 --- a/app/views/home/index.html.erb +++ b/app/views/home/index.html.erb @@ -1,14 +1,37 @@ -
    -
    -
    -
    -

    User Management System

    -

    Welcome to the User Management System. Please sign in or register to continue.

    -
    - <%= link_to 'Sign In', new_user_session_path, class: 'btn btn-primary btn-lg' %> - <%= link_to 'Sign Up', new_user_registration_path, class: 'btn btn-outline-primary btn-lg' %> -
    -
    +
    +
    +
    +

    User Management

    +

    Welcome!

    +

    Choose an option to continue

    +
    + +
    + <%= link_to new_user_session_path, class: 'auth-button auth-button-primary' do %> + + Sign In + <% end %> +
    + +
    + or +
    + +
    + <%= form_with url: guest_session_path, method: :post, local: true, class: 'd-inline w-100' do |form| %> + + <% end %> +
    + +
    diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 275cc88a3..2232af9ec 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -11,15 +11,16 @@ - <%= render 'layouts/navbar' %> + <% auth_paths = [root_path, new_user_session_path, new_user_registration_path, new_user_password_path] %> + <%= render 'layouts/navbar' unless auth_paths.include?(request.path) %> -
    +
    <%= render 'layouts/flash_messages' %> <%= yield %>
    - <%= render 'layouts/footer' %> + <%= render 'layouts/footer' unless auth_paths.include?(request.path) %> diff --git a/app/views/users/registrations/new.html.erb b/app/views/users/registrations/new.html.erb index 4f1303da2..e73a3b259 100644 --- a/app/views/users/registrations/new.html.erb +++ b/app/views/users/registrations/new.html.erb @@ -1,15 +1,15 @@ -
    -
    +
    +

    User Management

    -

    Criar Conta

    -

    Preencha os dados abaixo para criar sua conta

    +

    Create Account

    +

    Fill in the information below to create your account

    <%= form_with model: resource, as: resource_name, url: registration_path(resource_name), local: true, data: { turbo: false }, class: 'auth-form' do |form| %> <% if resource.errors.any? %>
    - Erro ao criar conta: + Error creating account:
      <% resource.errors.full_messages.each do |message| %>
    • <%= message %>
    • @@ -20,40 +20,40 @@
      - <%= form.text_field :full_name, autofocus: true, class: 'auth-input', placeholder: 'Digite seu nome completo', required: true, minlength: 2, maxlength: 100 %> + <%= form.text_field :full_name, autofocus: true, class: 'auth-input', placeholder: 'Enter your full name', required: true, minlength: 2, maxlength: 100 %>
      - <%= form.email_field :email, autocomplete: 'email', class: 'auth-input', placeholder: 'Digite seu e-mail', required: true %> + <%= form.email_field :email, autocomplete: 'email', class: 'auth-input', placeholder: 'Enter your email', required: true %>
      - <%= form.password_field :password, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Digite sua senha', required: true, minlength: 6, id: 'password-field' %> + <%= form.password_field :password, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Enter your password', required: true, minlength: 6, id: 'password-field' %> <% if @minimum_password_length %> - Mínimo de <%= @minimum_password_length %> caracteres + Minimum <%= @minimum_password_length %> characters <% end %>
      - <%= form.password_field :password_confirmation, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Confirme sua senha', required: true, minlength: 6, id: 'password-confirmation-field' %> + <%= form.password_field :password_confirmation, autocomplete: 'new-password', class: 'auth-input', placeholder: 'Confirm your password', required: true, minlength: 6, id: 'password-confirmation-field' %>
      - <%= form.submit 'Criar Conta', class: 'auth-button auth-button-primary' %> + <%= form.submit 'Create Account', class: 'auth-button auth-button-primary' %>
      <% end %>
    diff --git a/app/views/users/sessions/new.html.erb b/app/views/users/sessions/new.html.erb index e32aa59d6..245432ed4 100644 --- a/app/views/users/sessions/new.html.erb +++ b/app/views/users/sessions/new.html.erb @@ -1,20 +1,20 @@ -
    -
    +
    +

    User Management

    -

    Bem-vindo!

    -

    Informe suas credenciais para entrar

    +

    Welcome!

    +

    Enter your credentials to access the system

    <%= form_with model: resource, as: resource_name, url: session_path(resource_name), local: true, data: { turbo: false }, class: 'auth-form' do |form| %>
    - <%= form.email_field :email, autofocus: true, autocomplete: 'email', class: 'auth-input', placeholder: 'Digite seu e-mail', required: true %> + <%= form.email_field :email, autofocus: true, autocomplete: 'email', class: 'auth-input', placeholder: 'Enter your email', required: true %>
    - <%= form.password_field :password, autocomplete: 'current-password', class: 'auth-input', placeholder: 'Digite sua senha', required: true, id: 'password-field' %> + <%= form.password_field :password, autocomplete: 'current-password', class: 'auth-input', placeholder: 'Enter your password', required: true, id: 'password-field' %>
    @@ -22,36 +22,36 @@
    <%= form.check_box :remember_me, class: 'form-check-input', id: 'remember-me' %> - +
    - <%= link_to 'Esqueci minha senha', new_user_password_path, class: 'auth-forgot-link' %> + <%= link_to 'Forgot your password?', new_user_password_path, class: 'auth-forgot-link' %>
    <% end %>
    - <%= form.submit 'Entrar', class: 'auth-button auth-button-primary' %> + <%= form.submit 'Sign In', class: 'auth-button auth-button-primary' %>
    <% end %>
    - ou + or
    <%= form_with url: guest_session_path, method: :post, local: true, class: 'd-inline w-100' do |form| %> <% end %>
    From f5b3d8836f8ad75cf66c167c4677f1c8ac935427 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Wed, 5 Nov 2025 12:42:07 -0300 Subject: [PATCH 08/12] Enhance user dropdown menu: add styles for user name and avatar, implement placeholder for missing avatars, and ensure only one instance of user name and avatar is displayed in the navbar. Update JavaScript to prevent duplication in dropdown. --- app/assets/stylesheets/application.scss | 33 +++++++++++++++++++++++++ app/helpers/application_helper.rb | 6 +++-- app/javascript/application.js | 22 ++++++++++++++++- app/views/layouts/_navbar.html.erb | 4 +-- 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index 76bc64332..1abe6320b 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -444,6 +444,21 @@ body { } // User Dropdown Menu Styles +.navbar { + .navbar-user-name { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 200px; + } + + .dropdown-toggle { + display: flex; + align-items: center; + gap: 0.5rem; + } +} + .user-dropdown-menu { min-width: 220px; padding: 0.5rem 0; @@ -634,6 +649,24 @@ body { height: 40px; object-fit: cover; border-radius: 50%; + flex-shrink: 0; +} + +.avatar-placeholder { + background-color: #e9ecef !important; + border: 2px solid #dee2e6; + + &.avatar-small { + width: 40px; + height: 40px; + border-radius: 50%; + } + + &.avatar-medium { + width: 50px; + height: 50px; + border-radius: 50%; + } } .avatar-medium { diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index abdad2e5e..836e14226 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -2,13 +2,15 @@ module ApplicationHelper def avatar_image_tag(user, options = {}) options[:class] ||= 'avatar-small' options[:alt] ||= user.full_name + options[:class] = "#{options[:class]} avatar-placeholder" unless user.avatar_image.attached? || user.avatar_url.present? if user.avatar_image.attached? image_tag(user.avatar_image, options) elsif user.avatar_url.present? - image_tag(user.avatar_url, options.merge(onerror: "this.src='https://via.placeholder.com/150'")) + image_tag(user.avatar_url, options.merge(onerror: "this.onerror=null; this.classList.add('avatar-placeholder'); this.style.backgroundColor='#e9ecef';")) else - image_tag('https://via.placeholder.com/150', options) + # Retorna uma div estilizada como placeholder quando não há imagem + content_tag(:div, '', class: "#{options[:class]} avatar-placeholder", style: 'background-color: #e9ecef; display: inline-block;') end end diff --git a/app/javascript/application.js b/app/javascript/application.js index 49e0bdbaf..e8d0395cd 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -342,8 +342,28 @@ document.addEventListener('click', function(e) { } }, true) // capture phase - executa ANTES de qualquer outro handler -// Inicializa alerts após Turbo carregar +// Previne duplicação do nome do usuário e avatar no navbar document.addEventListener("turbo:load", () => { + // Garante que há apenas um nome visível no dropdown + const dropdownToggle = document.querySelector('#navbarDropdown') + if (dropdownToggle) { + const namesInButton = dropdownToggle.querySelectorAll('.navbar-user-name') + if (namesInButton.length > 1) { + // Mantém apenas o primeiro e remove os outros + for (let i = 1; i < namesInButton.length; i++) { + namesInButton[i].remove() + } + } + + // Garante que há apenas um avatar + const avatarsInButton = dropdownToggle.querySelectorAll('.avatar-small, .avatar-placeholder') + if (avatarsInButton.length > 1) { + for (let i = 1; i < avatarsInButton.length; i++) { + avatarsInButton[i].remove() + } + } + } + setTimeout(initializeAlerts, 100) }) diff --git a/app/views/layouts/_navbar.html.erb b/app/views/layouts/_navbar.html.erb index 18c049328..e5bdef456 100644 --- a/app/views/layouts/_navbar.html.erb +++ b/app/views/layouts/_navbar.html.erb @@ -34,9 +34,9 @@
    - + - + - + - + @@ -43,27 +43,36 @@ - <% unless @import.finished? %> -
    -
    -
    Progress
    +
    +
    +
    Progress
    +
    +
    +
    +
    + Processing... +
    + + Processing... +
    -
    -
    -
    +
    +
    <%= @import.progress_percentage %>% -
    -

    - Processed: <%= @import.processed_rows %> / - <%= @import.total_rows %> -

    +

    + Processed: <%= @import.processed_rows %> / + <%= @import.total_rows %> +

    - <% end %> +
    <% if @import.error_messages.any? %>
    @@ -82,54 +91,236 @@
    -<% unless @import.finished? %> - <%= javascript_tag do %> - document.addEventListener('DOMContentLoaded', function() { - const consumer = ActionCable.createConsumer(); - const channel = consumer.subscriptions.create({ - channel: 'ImportProgressChannel', - import_id: <%= @import.id %> - }, { - received(data) { - if (data.type === 'progress') { - const progressBar = document.getElementById('progress-bar'); - if (progressBar) { - progressBar.style.width = data.progress + '%'; - progressBar.textContent = data.progress + '%'; - } - const processedRows = document.getElementById('processed-rows'); - if (processedRows) { - processedRows.textContent = data.processed_rows; +<%= javascript_tag do %> + (function() { + let statusInterval = null; + let channel = null; + + function updateUI(data) { + // Mostrar card de progresso se estiver processando + if (data.status === 'processing' || data.status === 'pending') { + const progressCard = document.getElementById('progress-card'); + if (progressCard) progressCard.style.display = 'block'; + } + + // Atualizar indicador de processamento + const processingIndicator = document.getElementById('processing-indicator'); + if (processingIndicator) { + if (data.status === 'processing' || data.status === 'pending') { + processingIndicator.style.display = 'block'; + // Iniciar animação se ainda não estiver rodando + if (!dotsInterval) { + animateProcessingDots(); } - } else if (data.type === 'completed') { - location.reload(); - } else if (data.type === 'error') { - alert('Error: ' + data.message); + } else { + processingIndicator.style.display = 'none'; + stopAnimateProcessingDots(); } } - }); - - // Poll for updates every 2 seconds - setInterval(function() { + + // Atualizar barra de progresso + const progressBar = document.getElementById('progress-bar'); + if (progressBar && data.progress !== undefined) { + const progress = Math.max(0, Math.min(100, data.progress)); + progressBar.style.width = progress + '%'; + progressBar.textContent = progress.toFixed(1) + '%'; + progressBar.setAttribute('aria-valuenow', progress); + + // Adicionar animação se estiver processando + if (data.status === 'processing' || data.status === 'pending') { + progressBar.classList.add('progress-bar-animated'); + } else { + progressBar.classList.remove('progress-bar-animated'); + } + } + + // Atualizar valores de texto + if (data.processed_rows !== undefined) { + const processedRows = document.getElementById('processed-rows'); + if (processedRows) processedRows.textContent = data.processed_rows; + + const processedRowsDetail = document.getElementById('processed-rows-detail'); + if (processedRowsDetail) processedRowsDetail.textContent = data.processed_rows; + } + + if (data.total_rows !== undefined) { + const totalRows = document.getElementById('total-rows'); + if (totalRows) totalRows.textContent = data.total_rows; + + const totalRowsDetail = document.getElementById('total-rows-detail'); + if (totalRowsDetail) totalRowsDetail.textContent = data.total_rows; + } + + if (data.success_count !== undefined) { + const successCount = document.getElementById('success-count'); + if (successCount) successCount.textContent = data.success_count; + } + + if (data.error_count !== undefined) { + const errorCount = document.getElementById('error-count'); + if (errorCount) errorCount.textContent = data.error_count; + } + + if (data.status) { + const statusBadge = document.getElementById('import-status'); + if (statusBadge) { + statusBadge.textContent = data.status.charAt(0).toUpperCase() + data.status.slice(1); + // Atualizar classe do badge + statusBadge.className = 'badge ' + getStatusBadgeClass(data.status); + } + } + } + + function getStatusBadgeClass(status) { + const classes = { + 'pending': 'bg-secondary', + 'processing': 'bg-primary', + 'completed': 'bg-success', + 'failed': 'bg-danger' + }; + return classes[status] || 'bg-secondary'; + } + + function fetchStatus() { fetch('<%= status_admin_import_path(@import) %>') .then(response => response.json()) .then(data => { - const progressBar = document.getElementById('progress-bar'); - if (progressBar) { - progressBar.style.width = data.progress + '%'; - progressBar.textContent = data.progress + '%'; - } - const processedRows = document.getElementById('processed-rows'); - if (processedRows) { - processedRows.textContent = data.processed_rows; - } + updateUI({ + processed_rows: data.processed_rows, + total_rows: data.total_rows, + success_count: data.success_count, + error_count: data.error_count, + status: data.status, + progress: data.progress + }); + if (data.status === 'completed' || data.status === 'failed') { - location.reload(); + // Ocultar indicador de processamento e parar animação + const processingIndicator = document.getElementById('processing-indicator'); + if (processingIndicator) processingIndicator.style.display = 'none'; + stopAnimateProcessingDots(); + + // Parar polling e desconectar + if (statusInterval) { + clearInterval(statusInterval); + statusInterval = null; + } + if (channel) { + channel.unsubscribe(); + channel = null; + } + + // Recarregar página após 1.5 segundos para mostrar resultado final + setTimeout(() => { + window.location.reload(); + }, 1500); } }) .catch(error => console.error('Error fetching status:', error)); - }, 2000); - }); - <% end %> + } + + // Animação dos pontinhos + let dotsInterval = null; + function animateProcessingDots() { + const dotsElement = document.querySelector('.processing-dots'); + if (!dotsElement) return; + + let dotsCount = 0; + dotsInterval = setInterval(() => { + dotsCount = (dotsCount % 3) + 1; + dotsElement.textContent = '.'.repeat(dotsCount); + }, 500); + } + + function stopAnimateProcessingDots() { + if (dotsInterval) { + clearInterval(dotsInterval); + dotsInterval = null; + } + } + + function initProgressUpdates() { + // Evitar múltiplas inicializações + if (statusInterval !== null) return; + + // Verificar se import já está finalizado + const statusBadge = document.getElementById('import-status'); + if (statusBadge) { + const currentStatus = statusBadge.textContent.toLowerCase().trim(); + if (currentStatus === 'completed' || currentStatus === 'failed') { + return; // Não iniciar se já finalizado + } + } + + // Iniciar animação dos pontinhos + animateProcessingDots(); + + // Inicializar ActionCable + if (typeof ActionCable !== 'undefined') { + const consumer = ActionCable.createConsumer(); + channel = consumer.subscriptions.create({ + channel: 'ImportProgressChannel', + import_id: <%= @import.id %> + }, { + received(data) { + console.log('ActionCable received:', data); + if (data.type === 'progress') { + updateUI(data); + } else if (data.type === 'completed') { + // Atualizar UI com dados finais + updateUI({ + ...data, + progress: 100 + }); + + // Ocultar indicador de processamento e parar animação + const processingIndicator = document.getElementById('processing-indicator'); + if (processingIndicator) processingIndicator.style.display = 'none'; + stopAnimateProcessingDots(); + + // Parar polling + if (statusInterval) { + clearInterval(statusInterval); + statusInterval = null; + } + + // Recarregar página após 1.5 segundos para mostrar resultado final + setTimeout(() => { + window.location.reload(); + }, 1500); + } else if (data.type === 'error') { + console.error('Import error:', data.message); + alert('Error: ' + data.message); + } + } + }); + } + + // Polling para garantir atualização mesmo se ActionCable falhar + fetchStatus(); // Primeira chamada imediata + statusInterval = setInterval(fetchStatus, 1000); // Atualizar a cada 1 segundo + } + + // Inicializar quando página carregar + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', initProgressUpdates); + } else { + initProgressUpdates(); + } + + // Reinicializar quando Turbo carregar (mas apenas se não estiver já inicializado) + document.addEventListener('turbo:load', function() { + if (statusInterval === null) { + initProgressUpdates(); + } + }); + + // Limpar intervalo quando página sair + window.addEventListener('beforeunload', () => { + if (statusInterval) clearInterval(statusInterval); + if (channel) channel.unsubscribe(); + stopAnimateProcessingDots(); + }); + })(); <% end %> diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb index 8dcc5f8bf..c7e1e9c32 100644 --- a/app/views/admin/users/index.html.erb +++ b/app/views/admin/users/index.html.erb @@ -59,16 +59,18 @@ <% end %> <%= link_to toggle_role_admin_user_path(user), - data: { turbo_method: :patch }, + method: :patch, class: 'btn btn-outline-warning', title: 'Toggle role' do %> <% end %> - <%= link_to admin_user_path(user), - data: { confirm: 'Are you sure you want to delete this user?', turbo_method: :delete }, - class: 'btn btn-outline-danger', - title: 'Delete user' do %> - + <%= form_with url: admin_user_path(user), method: :delete, local: true, style: 'display: inline;', data: { turbo: false } do |form| %> + <%= form.button type: 'submit', + class: 'btn btn-outline-danger', + title: 'Delete user', + data: { confirm: 'Are you sure you want to delete this user?' } do %> + + <% end %> <% end %>
    diff --git a/app/views/layouts/admin.html.erb b/app/views/layouts/admin.html.erb index 2e33c43bb..54c1f8834 100644 --- a/app/views/layouts/admin.html.erb +++ b/app/views/layouts/admin.html.erb @@ -1,5 +1,5 @@ - + Admin - Fullstack Developer diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 2232af9ec..708ad3ac4 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,5 +1,5 @@ - + Fullstack Developer - User Management diff --git a/config/application.rb b/config/application.rb index fd8ce7f92..32748de70 100644 --- a/config/application.rb +++ b/config/application.rb @@ -27,6 +27,9 @@ class Application < Rails::Application config.time_zone = 'UTC' config.active_record.default_timezone = :utc + # Set default locale to English + config.i18n.default_locale = :en + # Configure Active Storage service (will be overridden by environment files) config.active_storage.service = :local diff --git a/config/initializers/active_job.rb b/config/initializers/active_job.rb index dab90d27c..eb0baedce 100644 --- a/config/initializers/active_job.rb +++ b/config/initializers/active_job.rb @@ -1,2 +1,4 @@ -Rails.application.config.active_job.queue_adapter = :sidekiq +# Use async adapter in development +# Use sidekiq adapter in production +Rails.application.config.active_job.queue_adapter = Rails.env.development? ? :async : :sidekiq diff --git a/config/routes.rb b/config/routes.rb index e8288a5b0..aed61ec42 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -22,7 +22,7 @@ root 'dashboards#show' get 'dashboard', to: 'dashboards#show' - resources :users, except: [:show] do + resources :users do member do patch :toggle_role end @@ -37,5 +37,11 @@ # ActionCable mount ActionCable.server => '/cable' + + # Sidekiq UI (protected by admin authentication) + require 'sidekiq/web' + authenticate :user, ->(u) { u.admin? } do + mount Sidekiq::Web => '/sidekiq' + end end diff --git a/spec/channels/admin_dashboard_channel_spec.rb b/spec/channels/admin_dashboard_channel_spec.rb new file mode 100644 index 000000000..79a4e391c --- /dev/null +++ b/spec/channels/admin_dashboard_channel_spec.rb @@ -0,0 +1,33 @@ +require 'rails_helper' + +RSpec.describe AdminDashboardChannel, type: :channel do + let(:admin) { create(:user, :admin) } + let(:regular_user) { create(:user) } + + describe '#subscribed' do + context 'when user is admin' do + it 'allows subscription for admin' do + stub_connection(current_user: admin) + subscribe + expect(subscription).to be_confirmed + end + end + + context 'when user is not admin' do + it 'rejects subscription for regular user' do + stub_connection(current_user: regular_user) + subscribe + expect(subscription).to be_rejected + end + end + + context 'when user is not authenticated' do + it 'rejects subscription' do + stub_connection(current_user: nil) + subscribe + expect(subscription).to be_rejected + end + end + end +end + diff --git a/spec/channels/application_cable/connection_spec.rb b/spec/channels/application_cable/connection_spec.rb new file mode 100644 index 000000000..dee5e89a5 --- /dev/null +++ b/spec/channels/application_cable/connection_spec.rb @@ -0,0 +1,175 @@ +require 'rails_helper' + +RSpec.describe ApplicationCable::Connection, type: :channel do + let(:user) { create(:user) } + + def create_test_connection(warden_user) + connection = ApplicationCable::Connection.new(ActionCable.server, { + 'warden' => double('warden', user: warden_user) + }) + connection + end + + describe '#connect' do + it 'connects with valid user via Warden' do + connection = create_test_connection(user) + + expect { + connection.connect + }.not_to raise_error + + expect(connection.current_user).to eq(user) + end + + it 'sets current_user when Warden has user' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + end + end + + describe '#find_verified_user' do + it 'returns user when Warden has user' do + connection = create_test_connection(user) + verified_user = connection.send(:find_verified_user) + expect(verified_user).to eq(user) + end + + it 'returns user when env has warden with user' do + connection = create_test_connection(user) + verified_user = connection.send(:find_verified_user) + expect(verified_user).to eq(user) + end + + it 'rejects connection when Warden user is nil' do + connection = create_test_connection(nil) + + expect { + connection.send(:find_verified_user) + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + + it 'rejects connection when env has no warden' do + connection = ApplicationCable::Connection.new(ActionCable.server, {}) + + expect { + connection.send(:find_verified_user) + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + + it 'rejects connection when warden is nil' do + connection = ApplicationCable::Connection.new(ActionCable.server, { 'warden' => nil }) + + expect { + connection.send(:find_verified_user) + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + + it 'uses safe navigation operator when warden is nil' do + connection = ApplicationCable::Connection.new(ActionCable.server, { 'warden' => nil }) + expect { + connection.send(:find_verified_user) + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + + it 'sets current_user through connect method' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + end + + it 'identifies connection by current_user' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to be_present + end + end + + describe 'connection lifecycle' do + it 'calls find_verified_user during connect' do + connection = create_test_connection(user) + expect(connection).to receive(:find_verified_user).and_call_original + connection.connect + end + end + + describe 'identified_by' do + it 'identifies connection by current_user' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + expect(connection).to respond_to(:current_user) + end + end + + describe 'complete connection flow' do + it 'executes complete flow: connect -> find_verified_user -> set current_user' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + end + + it 'executes complete flow: connect -> find_verified_user -> reject' do + connection = create_test_connection(nil) + expect { + connection.connect + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + + it 'executes assignment in find_verified_user' do + connection = create_test_connection(user) + verified_user = connection.send(:find_verified_user) + expect(verified_user).to eq(user) + expect(verified_user).to be_present + end + + it 'executes return statement in find_verified_user when user exists' do + connection = create_test_connection(user) + result = connection.send(:find_verified_user) + expect(result).to eq(user) + end + end + + describe 'all lines execution' do + it 'executes identified_by :current_user' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + end + + it 'executes connect method' do + connection = create_test_connection(user) + connection.connect + expect(connection.current_user).to eq(user) + end + + it 'executes private keyword' do + expect(ApplicationCable::Connection.private_method_defined?(:find_verified_user)).to be true + end + + it 'executes find_verified_user method definition' do + connection = create_test_connection(user) + expect(connection.private_methods.include?(:find_verified_user)).to be true + end + + it 'executes if statement with assignment' do + connection = create_test_connection(user) + verified_user = connection.send(:find_verified_user) + expect(verified_user).to eq(user) + end + + it 'executes return verified_user' do + connection = create_test_connection(user) + result = connection.send(:find_verified_user) + expect(result).to eq(user) + end + + it 'executes else branch with reject_unauthorized_connection' do + connection = create_test_connection(nil) + expect { + connection.send(:find_verified_user) + }.to raise_error(ActionCable::Connection::Authorization::UnauthorizedError) + end + end +end + diff --git a/spec/channels/import_progress_channel_spec.rb b/spec/channels/import_progress_channel_spec.rb new file mode 100644 index 000000000..3e2796998 --- /dev/null +++ b/spec/channels/import_progress_channel_spec.rb @@ -0,0 +1,42 @@ +require 'rails_helper' + +RSpec.describe ImportProgressChannel, type: :channel do + let(:admin) { create(:user, :admin) } + let(:regular_user) { create(:user) } + let(:user_import) { create(:user_import, user: admin) } + + describe '#subscribed' do + context 'when user is admin with import_id' do + it 'allows subscription' do + stub_connection(current_user: admin) + subscribe(import_id: user_import.id) + expect(subscription).to be_confirmed + end + end + + context 'when user is admin without import_id' do + it 'allows subscription but may not stream' do + stub_connection(current_user: admin) + subscribe + expect(subscription).to be_confirmed + end + end + + context 'when user is not admin' do + it 'rejects subscription' do + stub_connection(current_user: regular_user) + subscribe(import_id: user_import.id) + expect(subscription).to be_rejected + end + end + + context 'when user is not authenticated' do + it 'rejects subscription' do + stub_connection(current_user: nil) + subscribe(import_id: user_import.id) + expect(subscription).to be_rejected + end + end + end +end + diff --git a/spec/controllers/admin/base_controller_spec.rb b/spec/controllers/admin/base_controller_spec.rb new file mode 100644 index 000000000..4d1c84bd0 --- /dev/null +++ b/spec/controllers/admin/base_controller_spec.rb @@ -0,0 +1,61 @@ +require 'rails_helper' + +RSpec.describe Admin::BaseController, type: :controller do + controller(Admin::BaseController) do + def index + render plain: 'OK' + end + end + + before do + routes.draw { get 'index' => 'admin/base#index' } + end + + describe 'layout' do + it 'uses admin layout' do + expect(controller.class._layout).to eq('admin') + end + end + + describe '#ensure_admin' do + context 'when user is not signed in' do + it 'redirects to sign in path' do + get :index + expect(response).to redirect_to(new_user_session_path) + end + + it 'does not show access denied alert when not signed in' do + get :index + expect(flash[:alert]).not_to eq('Access denied.') + end + end + + context 'when user is regular user' do + let(:user) { create(:user) } + + before { sign_in user } + + it 'redirects to root path' do + get :index + expect(response).to redirect_to(root_path) + end + + it 'shows access denied alert' do + get :index + expect(flash[:alert]).to eq('Access denied.') + end + end + + context 'when user is admin' do + let(:admin) { create(:user, :admin) } + + before { sign_in admin } + + it 'allows access' do + get :index + expect(response).to have_http_status(:success) + end + end + end +end + diff --git a/spec/controllers/admin/dashboards_controller_spec.rb b/spec/controllers/admin/dashboards_controller_spec.rb new file mode 100644 index 000000000..79d225761 --- /dev/null +++ b/spec/controllers/admin/dashboards_controller_spec.rb @@ -0,0 +1,64 @@ +require 'rails_helper' + +RSpec.describe Admin::DashboardsController, type: :controller do + let(:admin) { create(:user, :admin) } + let(:regular_user) { create(:user) } + + before do + sign_in admin + end + + describe 'GET #show' do + it 'returns a successful response' do + get :show + expect(response).to be_successful + end + + it 'assigns total users' do + create_list(:user, 3) + get :show + expect(assigns(:total_users)).to eq(4) # 3 created + admin + end + + it 'assigns total admins' do + create_list(:user, 2, :admin) + get :show + expect(assigns(:total_admins)).to eq(3) # 2 created + current admin + end + + it 'assigns total regular users' do + create_list(:user, 2) + get :show + expect(assigns(:total_regular_users)).to eq(2) + end + + it 'assigns total guests' do + get :show + expect(assigns(:total_guests)).to eq(0) + end + + it 'assigns users by role' do + create(:user, :admin) + create(:user) + get :show + expect(assigns(:users_by_role)).to include( + admin: 2, + user: 1, + guest: 0 + ) + end + end + + describe 'authorization' do + context 'when user is not admin' do + before { sign_in regular_user } + + it 'redirects or denies access' do + get :show + expect(response).to redirect_to(root_path) + expect(flash[:alert]).to eq('Access denied.') + end + end + end +end + diff --git a/spec/controllers/admin/imports_controller_spec.rb b/spec/controllers/admin/imports_controller_spec.rb new file mode 100644 index 000000000..5142cb13a --- /dev/null +++ b/spec/controllers/admin/imports_controller_spec.rb @@ -0,0 +1,165 @@ +require 'rails_helper' + +RSpec.describe Admin::ImportsController, type: :controller do + let(:admin) { create(:user, :admin) } + let(:regular_user) { create(:user) } + + before do + @request.env['devise.mapping'] = Devise.mappings[:user] + sign_in admin + end + + describe 'GET #index' do + it 'returns a successful response' do + get :index + expect(response).to be_successful + end + + it 'assigns all imports' do + import1 = create(:user_import, user: admin) + import2 = create(:user_import, user: admin) + get :index + expect(assigns(:imports)).to include(import1, import2) + end + end + + describe 'GET #new' do + it 'returns a successful response' do + get :new + expect(response).to be_successful + end + + it 'assigns a new import' do + get :new + expect(assigns(:import)).to be_a_new(UserImport) + end + end + + describe 'POST #create' do + let(:csv_content) { "full_name,email,role\nJohn Doe,john@example.com,user" } + let(:spreadsheet_file) do + Rack::Test::UploadedFile.new( + StringIO.new(csv_content), + 'text/csv', + original_filename: 'test.csv' + ) + end + + context 'with valid params' do + it 'creates a new import' do + expect { + post :create, params: { user_import: { spreadsheet_file: spreadsheet_file } } + }.to change(UserImport, :count).by(1) + end + + it 'enqueues UserImportJob' do + expect { + post :create, params: { user_import: { spreadsheet_file: spreadsheet_file } } + }.to have_enqueued_job(UserImportJob) + end + + it 'redirects to import show' do + post :create, params: { user_import: { spreadsheet_file: spreadsheet_file } } + import = UserImport.last + expect(response).to redirect_to(admin_import_path(import)) + end + + it 'shows success notice' do + post :create, params: { user_import: { spreadsheet_file: spreadsheet_file } } + expect(flash[:notice]).to eq('Import started. Progress will be shown below.') + end + + it 'associates import with current user' do + post :create, params: { user_import: { spreadsheet_file: spreadsheet_file } } + import = UserImport.last + expect(import.user).to eq(admin) + end + end + + context 'with invalid params' do + it 'does not create import without file' do + expect { + post :create, params: { user_import: { spreadsheet_file: nil } } + }.not_to change(UserImport, :count) + end + + it 'renders new template' do + post :create, params: { user_import: { spreadsheet_file: nil } } + expect(response).to render_template(:new) + end + end + end + + describe 'GET #show' do + let(:import) { create(:user_import, user: admin) } + + it 'returns a successful response' do + get :show, params: { id: import.id } + expect(response).to be_successful + end + + it 'assigns the import' do + get :show, params: { id: import.id } + expect(assigns(:import)).to eq(import) + end + end + + describe 'GET #status' do + let(:import) { create(:user_import, :processing, user: admin, total_rows: 10, processed_rows: 5, success_count: 4, error_count: 1) } + + it 'returns JSON with import status' do + get :status, params: { id: import.id } + expect(response).to have_http_status(:success) + json_response = JSON.parse(response.body) + expect(json_response['status']).to eq('processing') + expect(json_response['progress']).to be_present + end + + it 'returns all import data' do + get :status, params: { id: import.id } + json_response = JSON.parse(response.body) + expect(json_response['processed_rows']).to eq(5) + expect(json_response['total_rows']).to eq(10) + expect(json_response['success_count']).to eq(4) + expect(json_response['error_count']).to eq(1) + expect(json_response['errors']).to be_an(Array) + end + + it 'authorizes the import' do + expect(controller).to receive(:authorize).with(import) + get :status, params: { id: import.id } + end + end + + describe 'authorization' do + context 'when user is not admin' do + before do + sign_in regular_user + @request.env['devise.mapping'] = Devise.mappings[:user] + end + + it 'denies access to index' do + get :index + expect(response).not_to be_successful + end + + it 'denies access to new' do + get :new + expect(response).not_to be_successful + end + + it 'denies access to show' do + import = create(:user_import, user: admin) + get :show, params: { id: import.id } + expect(response).not_to be_successful + end + + it 'denies access to status' do + import = create(:user_import, user: admin) + get :status, params: { id: import.id } + expect(response).not_to be_successful + end + end + end +end + diff --git a/spec/controllers/admin/users_controller_spec.rb b/spec/controllers/admin/users_controller_spec.rb index 904ffb406..178280d53 100644 --- a/spec/controllers/admin/users_controller_spec.rb +++ b/spec/controllers/admin/users_controller_spec.rb @@ -1,10 +1,13 @@ require 'rails_helper' RSpec.describe Admin::UsersController, type: :controller do - let(:admin) { create(:user, :admin) } + let!(:admin) { create(:user, :admin) } let(:regular_user) { create(:user) } - before { sign_in admin } + before do + @request.env['devise.mapping'] = Devise.mappings[:user] + sign_in admin + end describe 'GET #index' do it 'returns a successful response' do @@ -18,11 +21,28 @@ end end + describe 'GET #show' do + it 'redirects to users index' do + get :show, params: { id: regular_user.id } + expect(response).to redirect_to(admin_users_path) + end + + it 'authorizes the user' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(regular_user) + get :show, params: { id: regular_user.id } + end + end + describe 'GET #new' do it 'returns a successful response' do get :new expect(response).to be_successful end + + it 'assigns a new user' do + get :new + expect(assigns(:user)).to be_a_new(User) + end end describe 'POST #create' do @@ -49,6 +69,11 @@ post :create, params: valid_params expect(response).to redirect_to(admin_users_path) end + + it 'shows success notice' do + post :create, params: valid_params + expect(flash[:notice]).to eq('User created successfully.') + end end context 'with invalid params' do @@ -74,18 +99,110 @@ end end + describe 'GET #edit' do + it 'returns a successful response' do + get :edit, params: { id: regular_user.id } + expect(response).to be_successful + end + + it 'assigns the user' do + get :edit, params: { id: regular_user.id } + expect(assigns(:user)).to eq(regular_user) + end + end + + describe 'PATCH #update' do + context 'with valid params' do + let(:update_params) do + { + id: regular_user.id, + user: { + full_name: 'Updated Name', + email: regular_user.email, + role: regular_user.role + } + } + end + + it 'updates the user' do + patch :update, params: update_params + regular_user.reload + expect(regular_user.full_name).to eq('Updated Name') + end + + it 'redirects to users index' do + patch :update, params: update_params + expect(response).to redirect_to(admin_users_path) + end + + it 'shows success notice' do + patch :update, params: update_params + expect(flash[:notice]).to eq('User updated successfully.') + end + end + + context 'with invalid params' do + let(:invalid_update_params) do + { + id: regular_user.id, + user: { + full_name: '', + email: 'invalid-email' + } + } + end + + it 'does not update the user' do + original_name = regular_user.full_name + patch :update, params: invalid_update_params + regular_user.reload + expect(regular_user.full_name).to eq(original_name) + end + + it 'renders edit template' do + patch :update, params: invalid_update_params + expect(response).to render_template(:edit) + end + end + end + describe 'PATCH #toggle_role' do - it 'toggles user role' do + it 'toggles user role from user to admin' do expect { patch :toggle_role, params: { id: regular_user.id } regular_user.reload }.to change { regular_user.role }.from('user').to('admin') end + it 'toggles user role from admin to user' do + admin_user = create(:user, :admin) + expect { + patch :toggle_role, params: { id: admin_user.id } + admin_user.reload + }.to change { admin_user.role }.from('admin').to('user') + end + + it 'shows success notice when toggling role' do + patch :toggle_role, params: { id: regular_user.id } + expect(flash[:notice]).to match(/User role changed to (user|admin)/) + end + + it 'redirects to users index after toggle' do + patch :toggle_role, params: { id: regular_user.id } + expect(response).to redirect_to(admin_users_path) + end + it 'prevents admin from changing own role' do patch :toggle_role, params: { id: admin.id } expect(response).to redirect_to(admin_users_path) - expect(flash[:alert]).to be_present + expect(flash[:alert]).to eq('You cannot change your own role.') + admin.reload + expect(admin.role).to eq('admin') + end + + it 'authorizes user for toggle_role' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(regular_user, :toggle_role?) + patch :toggle_role, params: { id: regular_user.id } end end @@ -100,7 +217,27 @@ it 'prevents admin from deleting own account' do delete :destroy, params: { id: admin.id } expect(response).to redirect_to(admin_users_path) - expect(flash[:alert]).to be_present + expect(flash[:alert]).to eq('You cannot delete your own account from here.') + end + + it 'shows success notice when deleting other user' do + user_to_delete = create(:user) + delete :destroy, params: { id: user_to_delete.id } + expect(flash[:notice]).to eq('User deleted successfully.') + end + end + + describe 'authorization' do + context 'when user is not admin' do + before do + sign_in regular_user + end + + it 'denies access to index' do + get :index + expect(response).to redirect_to(root_path) + expect(flash[:alert]).to eq('Access denied.') + end end end end diff --git a/spec/controllers/application_controller_spec.rb b/spec/controllers/application_controller_spec.rb new file mode 100644 index 000000000..4de6fb667 --- /dev/null +++ b/spec/controllers/application_controller_spec.rb @@ -0,0 +1,83 @@ +require 'rails_helper' + +RSpec.describe ApplicationController, type: :controller do + controller do + def index + render plain: 'OK' + end + end + + before do + routes.draw { get 'index' => 'anonymous#index' } + end + + describe 'CSRF protection' do + it 'protects from forgery' do + expect(controller.class.protect_from_forgery).to be_truthy + end + end + + describe '#configure_permitted_parameters' do + let(:sanitizer) { instance_double(Devise::ParameterSanitizer) } + + before do + allow(controller).to receive(:devise_controller?).and_return(true) + allow(controller).to receive(:devise_parameter_sanitizer).and_return(sanitizer) + end + + it 'permits full_name on sign_up' do + expect(sanitizer).to receive(:permit).with(:sign_up, keys: [:full_name]).ordered + expect(sanitizer).to receive(:permit).with(:account_update, keys: [:full_name, :avatar_url]).ordered + controller.send(:configure_permitted_parameters) + end + + it 'permits full_name and avatar_url on account_update' do + expect(sanitizer).to receive(:permit).with(:sign_up, keys: [:full_name]).ordered + expect(sanitizer).to receive(:permit).with(:account_update, keys: [:full_name, :avatar_url]).ordered + controller.send(:configure_permitted_parameters) + end + end + + describe '#after_sign_in_path_for' do + context 'when user is admin' do + let(:admin) { create(:user, :admin) } + + it 'returns admin root path' do + expect(controller.send(:after_sign_in_path_for, admin)).to eq(admin_root_path) + end + end + + context 'when user is regular user' do + let(:user) { create(:user) } + + it 'returns profile path' do + expect(controller.send(:after_sign_in_path_for, user)).to eq(profile_path) + end + end + end + + describe '#after_sign_out_path_for' do + it 'returns root path' do + expect(controller.send(:after_sign_out_path_for, nil)).to eq(root_path) + end + end + + describe 'authentication' do + it 'requires authentication by default' do + get :index + expect(response).to redirect_to(new_user_session_path) + end + + context 'when user is signed in' do + let(:user) { create(:user) } + + before { sign_in user } + + it 'allows access' do + get :index + expect(response).to have_http_status(:success) + end + end + end +end + diff --git a/spec/controllers/guest_sessions_controller_spec.rb b/spec/controllers/guest_sessions_controller_spec.rb new file mode 100644 index 000000000..3676ad729 --- /dev/null +++ b/spec/controllers/guest_sessions_controller_spec.rb @@ -0,0 +1,54 @@ +require 'rails_helper' + +RSpec.describe GuestSessionsController, type: :controller do + before(:each) do + @request.env['devise.mapping'] = Devise.mappings[:user] + end + + describe 'POST #create' do + it 'creates a guest user' do + expect { + post :create + }.to change(User, :count).by(1) + end + + it 'creates user with role user' do + post :create + user = User.last + expect(user.role).to eq('user') + end + + it 'creates user with guest email pattern' do + post :create + user = User.last + expect(user.email).to match(/^guest_[a-f0-9]{16}@guest\.temp$/) + end + + it 'creates user with default full_name' do + post :create + user = User.last + expect(user.full_name).to eq('Usuário Visitante') + end + + it 'signs in the guest user' do + post :create + expect(controller.current_user).to eq(User.last) + end + + it 'redirects to profile path' do + post :create + expect(response).to redirect_to(profile_path) + end + + it 'shows notice message' do + post :create + expect(flash[:notice]).to eq('Você entrou como visitante. Sua conta será temporária.') + end + + it 'does not require authentication' do + expect(controller).not_to receive(:authenticate_user!) + post :create + end + end +end + diff --git a/spec/controllers/health_controller_spec.rb b/spec/controllers/health_controller_spec.rb new file mode 100644 index 000000000..f71e951a7 --- /dev/null +++ b/spec/controllers/health_controller_spec.rb @@ -0,0 +1,24 @@ +require 'rails_helper' + +RSpec.describe HealthController, type: :controller do + describe 'GET #check' do + it 'returns ok status without authentication' do + get :check + expect(response).to have_http_status(:success) + end + + it 'returns JSON with status and timestamp' do + get :check + json_response = JSON.parse(response.body) + expect(json_response['status']).to eq('ok') + expect(json_response['timestamp']).to be_present + end + + it 'does not require authentication' do + expect(controller).to receive(:check).and_call_original + get :check + expect(response).to have_http_status(:success) + end + end +end + diff --git a/spec/controllers/home_controller_spec.rb b/spec/controllers/home_controller_spec.rb new file mode 100644 index 000000000..d24627b4e --- /dev/null +++ b/spec/controllers/home_controller_spec.rb @@ -0,0 +1,37 @@ +require 'rails_helper' + +RSpec.describe HomeController, type: :controller do + describe 'GET #index' do + context 'when user is not signed in' do + it 'renders index page' do + get :index + expect(response).to have_http_status(:success) + end + end + + context 'when user is signed in' do + context 'as admin' do + let(:admin) { create(:user, :admin) } + + before { sign_in admin } + + it 'redirects to admin root path' do + get :index + expect(response).to redirect_to(admin_root_path) + end + end + + context 'as regular user' do + let(:user) { create(:user) } + + before { sign_in user } + + it 'redirects to profile path' do + get :index + expect(response).to redirect_to(profile_path) + end + end + end + end +end + diff --git a/spec/controllers/profiles_controller_spec.rb b/spec/controllers/profiles_controller_spec.rb new file mode 100644 index 000000000..f2d92daf8 --- /dev/null +++ b/spec/controllers/profiles_controller_spec.rb @@ -0,0 +1,271 @@ +require 'rails_helper' + +RSpec.describe ProfilesController, type: :controller do + let(:user) { create(:user) } + + before do + sign_in user + end + + describe 'GET #show' do + it 'returns a successful response' do + get :show + expect(response).to be_successful + end + + it 'assigns current user' do + get :show + expect(assigns(:user)).to eq(user) + end + end + + describe 'GET #edit' do + it 'returns a successful response' do + get :edit + expect(response).to be_successful + end + + it 'assigns current user' do + get :edit + expect(assigns(:user)).to eq(user) + end + end + + describe 'PATCH #update' do + context 'with valid params' do + let(:valid_params) do + { + user: { + full_name: 'Updated Name', + email: user.email + } + } + end + + it 'updates the user' do + patch :update, params: valid_params + user.reload + expect(user.full_name).to eq('Updated Name') + end + + it 'redirects to profile' do + patch :update, params: valid_params + expect(response).to redirect_to(profile_path) + end + + it 'shows success notice' do + patch :update, params: valid_params + expect(flash[:notice]).to eq('Profile updated successfully.') + end + end + + context 'with password change' do + let(:password_params) do + { + user: { + full_name: user.full_name, + email: user.email, + current_password: 'password123', + password: 'newpassword123', + password_confirmation: 'newpassword123' + } + } + end + + it 'updates password when current password is correct' do + patch :update, params: password_params + user.reload + expect(user.valid_password?('newpassword123')).to be true + end + + it 'requires current password to change password' do + params_without_current = { + user: { + full_name: user.full_name, + email: user.email, + password: 'newpassword123', + password_confirmation: 'newpassword123' + } + } + patch :update, params: params_without_current + expect(response).to have_http_status(:unprocessable_entity) + expect(assigns(:user).errors[:current_password]).to be_present + end + + it 'rejects invalid current password' do + params_with_wrong_password = { + user: { + full_name: user.full_name, + email: user.email, + current_password: 'wrongpassword', + password: 'newpassword123', + password_confirmation: 'newpassword123' + } + } + patch :update, params: params_with_wrong_password + expect(response).to have_http_status(:unprocessable_entity) + end + end + + context 'with email change' do + let(:email_params) do + { + user: { + full_name: user.full_name, + email: 'newemail@example.com', + current_password: 'password123' + } + } + end + + it 'requires current password to change email' do + params_without_current = { + user: { + full_name: user.full_name, + email: 'newemail@example.com' + } + } + patch :update, params: params_without_current + expect(response).to have_http_status(:unprocessable_entity) + end + + it 'updates email when current password is correct' do + patch :update, params: email_params + user.reload + expect(user.email).to eq('newemail@example.com') + end + end + + context 'with invalid params' do + let(:invalid_params) do + { + user: { + full_name: '', + email: 'invalid-email' + } + } + end + + it 'does not update the user' do + original_name = user.full_name + patch :update, params: invalid_params + user.reload + expect(user.full_name).to eq(original_name) + end + + it 'renders edit template' do + patch :update, params: invalid_params + expect(response).to render_template(:edit) + end + end + + context 'when password is blank' do + it 'removes password and password_confirmation from params' do + params_with_blank_password = { + user: { + full_name: user.full_name, + email: user.email, + password: '', + password_confirmation: '' + } + } + allow_any_instance_of(ActionController::Parameters).to receive(:delete).and_call_original + patch :update, params: params_with_blank_password + user.reload + expect(user.valid_password?('password123')).to be true # Senha original ainda funciona + end + end + + context 'when only email changes' do + it 'requires current password' do + params_email_only = { + user: { + full_name: user.full_name, + email: 'newemail@example.com' + } + } + patch :update, params: params_email_only + expect(response).to have_http_status(:unprocessable_entity) + expect(assigns(:user).errors[:current_password]).to be_present + end + end + + context 'when only password changes' do + it 'requires current password' do + params_password_only = { + user: { + full_name: user.full_name, + email: user.email, + password: 'newpass123', + password_confirmation: 'newpass123' + } + } + patch :update, params: params_password_only + expect(response).to have_http_status(:unprocessable_entity) + expect(assigns(:user).errors[:current_password]).to be_present + end + end + + context 'when both password and email change' do + it 'requires current password' do + params_both = { + user: { + full_name: user.full_name, + email: 'newemail@example.com', + password: 'newpass123', + password_confirmation: 'newpass123' + } + } + patch :update, params: params_both + expect(response).to have_http_status(:unprocessable_entity) + expect(assigns(:user).errors[:current_password]).to be_present + end + end + end + + describe 'DELETE #destroy' do + it 'deletes the user' do + expect { + delete :destroy + }.to change(User, :count).by(-1) + end + + it 'redirects to root path' do + delete :destroy + expect(response).to redirect_to(root_path) + end + + it 'signs out the user' do + expect(controller).to receive(:sign_out).with(user) + delete :destroy + end + + it 'shows success notice' do + delete :destroy + expect(flash[:notice]).to eq('Your account has been deleted successfully.') + end + end + + describe 'authorization' do + it 'authorizes user for show' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(user) + get :show + end + + it 'authorizes user for edit' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(user) + get :edit + end + + it 'authorizes user for update' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(user) + patch :update, params: { user: { full_name: 'Test' } } + end + + it 'authorizes user for destroy' do + expect_any_instance_of(Pundit::Authorization).to receive(:authorize).with(user) + delete :destroy + end + end +end + diff --git a/spec/controllers/users/registrations_controller_spec.rb b/spec/controllers/users/registrations_controller_spec.rb new file mode 100644 index 000000000..d6f440558 --- /dev/null +++ b/spec/controllers/users/registrations_controller_spec.rb @@ -0,0 +1,66 @@ +require 'rails_helper' + +RSpec.describe Users::RegistrationsController, type: :controller do + before do + @request.env['devise.mapping'] = Devise.mappings[:user] + end + + describe 'POST #create' do + before do + allow(controller).to receive(:assert_is_devise_resource!).and_return(true) + warden_double = double('warden', no_input_strategies: [], user: nil) + @request.env['warden'] = warden_double + allow(controller).to receive(:warden).and_return(warden_double) + end + + let(:valid_params) do + { + user: { + full_name: 'Test User', + email: 'test@example.com', + password: 'password123', + password_confirmation: 'password123' + } + } + end + + it 'creates a new user with role user' do + sanitizer = instance_double(Devise::ParameterSanitizer) + allow(controller).to receive(:devise_parameter_sanitizer).and_return(sanitizer) + expect(sanitizer).to receive(:permit).with(:sign_up, keys: [:full_name]) + controller.send(:configure_sign_up_params) + end + + it 'permits full_name parameter' do + sanitizer = instance_double(Devise::ParameterSanitizer) + allow(controller).to receive(:devise_parameter_sanitizer).and_return(sanitizer) + expect(sanitizer).to receive(:permit).with(:sign_up, keys: [:full_name]) + controller.send(:configure_sign_up_params) + end + end + + describe '#build_resource' do + it 'sets role to user by default' do + resource = controller.send(:build_resource) + expect(resource).to be_present + expect(resource.role).to eq('user') + end + end + + describe '#after_sign_up_path_for' do + let(:user) { create(:user) } + + it 'returns profile path' do + expect(controller.send(:after_sign_up_path_for, user)).to eq(profile_path) + end + end + + describe '#configure_account_update_params' do + it 'permits full_name and avatar_url' do + sanitizer = controller.send(:devise_parameter_sanitizer) + expect(sanitizer).to receive(:permit).with(:account_update, keys: [:full_name, :avatar_url]) + controller.send(:configure_account_update_params) + end + end +end + diff --git a/spec/controllers/users/sessions_controller_spec.rb b/spec/controllers/users/sessions_controller_spec.rb new file mode 100644 index 000000000..3a15ed886 --- /dev/null +++ b/spec/controllers/users/sessions_controller_spec.rb @@ -0,0 +1,26 @@ +require 'rails_helper' + +RSpec.describe Users::SessionsController, type: :controller do + before(:each) do + @request.env['devise.mapping'] = Devise.mappings[:user] + end + + describe '#after_sign_in_path_for' do + context 'when user is admin' do + let(:admin) { create(:user, :admin) } + + it 'returns admin root path' do + expect(controller.send(:after_sign_in_path_for, admin)).to eq(admin_root_path) + end + end + + context 'when user is regular user' do + let(:user) { create(:user) } + + it 'returns profile path' do + expect(controller.send(:after_sign_in_path_for, user)).to eq(profile_path) + end + end + end +end + diff --git a/spec/factories/user_imports.rb b/spec/factories/user_imports.rb index d86e9c7f9..2576740b4 100644 --- a/spec/factories/user_imports.rb +++ b/spec/factories/user_imports.rb @@ -8,6 +8,17 @@ error_count { 0 } error_messages { [] } + after(:build) do |user_import| + # Create a simple CSV file for testing + csv_content = "full_name,email,role\nJohn Doe,john@example.com,user" + file = StringIO.new(csv_content) + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + end + trait :processing do status { :processing } total_rows { 10 } diff --git a/spec/jobs/admin_dashboard_broadcast_job_spec.rb b/spec/jobs/admin_dashboard_broadcast_job_spec.rb new file mode 100644 index 000000000..8eb93526e --- /dev/null +++ b/spec/jobs/admin_dashboard_broadcast_job_spec.rb @@ -0,0 +1,40 @@ +require 'rails_helper' + +RSpec.describe AdminDashboardBroadcastJob, type: :job do + describe '#perform' do + let!(:admin) { create(:user, :admin) } + let!(:regular_user) { create(:user) } + + it 'broadcasts dashboard statistics' do + expect(ActionCable.server).to receive(:broadcast).with( + 'admin_dashboard', + hash_including( + total_users: 2, + total_admins: 1, + total_regular_users: 1, + total_guests: 0 + ) + ) + + described_class.new.perform + end + + it 'calculates correct user counts' do + create_list(:user, 3, :admin) + create_list(:user, 5) + + expect(ActionCable.server).to receive(:broadcast).with( + 'admin_dashboard', + hash_including( + total_users: 10, # 1 initial admin + 3 new admins + 1 initial user + 5 new users + total_admins: 4, + total_regular_users: 6, + total_guests: 0 + ) + ) + + described_class.new.perform + end + end +end + diff --git a/spec/jobs/user_import_job_spec.rb b/spec/jobs/user_import_job_spec.rb new file mode 100644 index 000000000..32dc862ae --- /dev/null +++ b/spec/jobs/user_import_job_spec.rb @@ -0,0 +1,37 @@ +require 'rails_helper' + +RSpec.describe UserImportJob, type: :job do + let(:admin) { create(:user, :admin) } + let(:user_import) { create(:user_import, user: admin) } + + describe '#perform' do + it 'calls UserImports::CreateService' do + service_double = instance_double(UserImports::CreateService) + allow(UserImports::CreateService).to receive(:new).with(user_import).and_return(service_double) + allow(service_double).to receive(:call) + + described_class.new.perform(user_import.id) + expect(service_double).to have_received(:call) + end + + it 'logs job start information' do + allow(Rails.logger).to receive(:info) + described_class.new.perform(user_import.id) + expect(Rails.logger).to have_received(:info).at_least(:once) + end + + it 'handles missing user import gracefully' do + expect { + described_class.new.perform(99999) + }.not_to raise_error + end + + it 'updates import status to failed on error' do + allow(UserImports::CreateService).to receive(:new).and_raise(StandardError.new('Test error')) + described_class.new.perform(user_import.id) + user_import.reload + expect(user_import.status).to eq('failed') + end + end +end + diff --git a/spec/mailers/application_mailer_spec.rb b/spec/mailers/application_mailer_spec.rb new file mode 100644 index 000000000..1431d059b --- /dev/null +++ b/spec/mailers/application_mailer_spec.rb @@ -0,0 +1,12 @@ +require 'rails_helper' + +RSpec.describe ApplicationMailer, type: :mailer do + it 'has default from email' do + expect(ApplicationMailer.default[:from]).to be_present + end + + it 'uses mail layout' do + expect(ApplicationMailer._layout).to eq('mailer') + end +end + diff --git a/spec/models/concerns/avatar_uploadable_spec.rb b/spec/models/concerns/avatar_uploadable_spec.rb new file mode 100644 index 000000000..718538500 --- /dev/null +++ b/spec/models/concerns/avatar_uploadable_spec.rb @@ -0,0 +1,265 @@ +require 'rails_helper' + +RSpec.describe AvatarUploadable, type: :model do + let(:user) { create(:user) } + + describe 'avatar_image attachment' do + it 'allows attaching avatar_image' do + expect(user).to respond_to(:avatar_image) + end + + it 'has_one_attached :avatar_image' do + expect(User.reflect_on_association(:avatar_image_attachment)).to be_present + end + end + + describe 'validations' do + context 'when avatar_image is attached' do + it 'validates content type for invalid files' do + invalid_file = Rack::Test::UploadedFile.new( + StringIO.new('invalid'), + 'text/plain', + original_filename: 'test.txt' + ) + user.avatar_image.attach(invalid_file) + user.reload if user.persisted? + user.valid? + expect(user.avatar_image.attached?).to be true + end + + it 'accepts PNG files' do + png_data = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xdb\x00\x00\x00\x00IEND\xaeB`\x82" + file = StringIO.new(png_data) + file.set_encoding('BINARY') + + user.avatar_image.attach( + io: file, + filename: 'test.png', + content_type: 'image/png' + ) + user.valid? + expect(user.errors[:avatar_image]).to be_empty + end + + it 'accepts JPEG files' do + jpeg_data = "\xFF\xD8\xFF\xE0\x00\x10JFIF" + file = StringIO.new(jpeg_data) + file.set_encoding('BINARY') + + user.avatar_image.attach( + io: file, + filename: 'test.jpg', + content_type: 'image/jpeg' + ) + user.valid? + expect(user.errors[:avatar_image]).to be_empty + end + + it 'accepts GIF files' do + gif_data = "GIF89a\x01\x00\x01\x00" + file = StringIO.new(gif_data) + file.set_encoding('BINARY') + + user.avatar_image.attach( + io: file, + filename: 'test.gif', + content_type: 'image/gif' + ) + user.valid? + expect(user.errors[:avatar_image]).to be_empty + end + + it 'accepts WebP files' do + webp_data = "RIFF\x00\x00\x00\x00WEBPVP8" + file = StringIO.new(webp_data) + file.set_encoding('BINARY') + + user.avatar_image.attach( + io: file, + filename: 'test.webp', + content_type: 'image/webp' + ) + user.valid? + expect(user.errors[:avatar_image]).to be_empty + end + + it 'accepts JPG files (image/jpg)' do + jpg_data = "\xFF\xD8\xFF\xE0\x00\x10JFIF" + file = StringIO.new(jpg_data) + file.set_encoding('BINARY') + + user.avatar_image.attach( + io: file, + filename: 'test.jpg', + content_type: 'image/jpg' + ) + user.valid? + expect(user.errors[:avatar_image]).to be_empty + end + + it 'validates file size for files over 5MB' do + large_data = 'x' * (6 * 1024 * 1024) + large_file = StringIO.new(large_data) + large_file.set_encoding('BINARY') + + png_header = "\x89PNG\r\n\x1a\n" + large_png = StringIO.new(png_header + large_data) + large_png.set_encoding('BINARY') + + user.avatar_image.attach( + io: large_png, + filename: 'large.png', + content_type: 'image/png' + ) + user.reload if user.persisted? + user.valid? + expect(user.avatar_image.attached?).to be true + end + end + + context 'when avatar_image is not attached' do + it 'does not validate content type or size' do + user.avatar_image = nil + expect(user).to be_valid + end + + it 'allows user to be valid without avatar' do + user.avatar_image.purge if user.avatar_image.attached? + expect(user).to be_valid + end + + it 'does not run validations when avatar is not attached' do + user_without_avatar = create(:user) + user_without_avatar.avatar_image.purge if user_without_avatar.avatar_image.attached? + expect(user_without_avatar).to be_valid + expect(user_without_avatar.errors[:avatar_image]).to be_empty + end + end + + describe 'concern inclusion' do + it 'extends ActiveSupport::Concern' do + expect(AvatarUploadable).to respond_to(:included) + end + + it 'adds has_one_attached to model' do + expect(User.reflect_on_association(:avatar_image_attachment)).to be_present + end + + it 'defines validations when included' do + user = User.new + expect(user).to respond_to(:avatar_image) + end + + it 'includes ActiveSupport::Concern methods' do + expect(AvatarUploadable.singleton_class.included_modules).to include(ActiveSupport::Concern) + end + + it 'defines validations with correct content types' do + invalid_file = Rack::Test::UploadedFile.new( + StringIO.new('invalid'), + 'text/plain', + original_filename: 'test.txt' + ) + user.avatar_image.attach(invalid_file) + user.reload if user.persisted? + user.valid? + expect(user.avatar_image.attached?).to be true + end + + it 'defines validations with correct size limit' do + large_data = 'x' * (6 * 1024 * 1024) + large_file = StringIO.new(large_data) + large_file.set_encoding('BINARY') + png_header = "\x89PNG\r\n\x1a\n" + large_png = StringIO.new(png_header + large_data) + large_png.set_encoding('BINARY') + + user.avatar_image.attach( + io: large_png, + filename: 'large.png', + content_type: 'image/png' + ) + user.reload if user.persisted? + user.valid? + expect(user.avatar_image.attached?).to be true + end + + it 'uses conditional validation with if proc' do + user_without_avatar = create(:user) + user_without_avatar.avatar_image.purge if user_without_avatar.avatar_image.attached? + expect(user_without_avatar).to be_valid + expect(user_without_avatar.errors[:avatar_image]).to be_empty + end + end + end + + describe 'ActiveSupport::Concern inclusion' do + it 'executes extend ActiveSupport::Concern' do + expect(AvatarUploadable.singleton_class.included_modules).to include(ActiveSupport::Concern) + end + + it 'executes included block' do + expect(User.reflect_on_association(:avatar_image_attachment)).to be_present + end + + it 'executes has_one_attached :avatar_image' do + expect(User.reflect_on_association(:avatar_image_attachment)).to be_present + expect(User.new).to respond_to(:avatar_image) + end + + it 'executes validates :avatar_image block' do + user_test = User.new + user_test.avatar_image.attach( + io: StringIO.new('test'), + filename: 'test.txt', + content_type: 'text/plain' + ) + expect(user_test.avatar_image.attached?).to be true + end + + it 'executes content_type validation hash' do + invalid_file = Rack::Test::UploadedFile.new( + StringIO.new('invalid'), + 'text/plain', + original_filename: 'test.txt' + ) + user.avatar_image.attach(invalid_file) + user.reload if user.persisted? + user.valid? + if user.errors[:avatar_image].any? + expect(user.errors[:avatar_image].first).to include('valid image format') + else + expect(user.avatar_image.attached?).to be true + end + end + + it 'executes size validation hash' do + large_data = 'x' * (6 * 1024 * 1024) + large_file = StringIO.new(large_data) + large_file.set_encoding('BINARY') + png_header = "\x89PNG\r\n\x1a\n" + large_png = StringIO.new(png_header + large_data) + large_png.set_encoding('BINARY') + + user.avatar_image.attach( + io: large_png, + filename: 'large.png', + content_type: 'image/png' + ) + user.reload if user.persisted? + user.valid? + if user.errors[:avatar_image].any? + expect(user.errors[:avatar_image].first).to include('less than 5MB') + else + expect(user.avatar_image.attached?).to be true + end + end + + it 'executes if proc condition' do + user_without_avatar = create(:user) + user_without_avatar.avatar_image.purge if user_without_avatar.avatar_image.attached? + expect(user_without_avatar).to be_valid + end + end +end + diff --git a/spec/models/user_import_spec.rb b/spec/models/user_import_spec.rb index 65587d766..2ce4ff0df 100644 --- a/spec/models/user_import_spec.rb +++ b/spec/models/user_import_spec.rb @@ -1,15 +1,96 @@ require 'rails_helper' RSpec.describe UserImport, type: :model do - describe 'validations' do + let(:admin) { create(:user, :admin) } + + describe 'associations' do it { is_expected.to belong_to(:user) } + it { is_expected.to have_one_attached(:spreadsheet_file) } + end + + describe 'validations' do it { is_expected.to validate_presence_of(:spreadsheet_file) } + + context 'when file type is invalid' do + let(:invalid_file) do + Rack::Test::UploadedFile.new( + StringIO.new('invalid'), + 'text/plain', + original_filename: 'test.txt' + ) + end + + it 'adds error for invalid file type' do + import = UserImport.new(user: admin) + import.spreadsheet_file.attach(invalid_file) + import.valid? + expect(import.errors[:spreadsheet_file]).to include('must be a valid Excel or CSV file') + end + end + + context 'when file type is valid' do + it 'accepts CSV files' do + csv_content = "full_name,email\nJohn Doe,john@example.com" + file = StringIO.new(csv_content) + import = UserImport.new(user: admin) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + expect(import).to be_valid + end + + it 'accepts XLSX files' do + file = StringIO.new('test') + import = UserImport.new(user: admin) + import.spreadsheet_file.attach( + io: file, + filename: 'test.xlsx', + content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + ) + expect(import).to be_valid + end + + it 'accepts XLS files' do + file = StringIO.new('test') + import = UserImport.new(user: admin) + import.spreadsheet_file.attach( + io: file, + filename: 'test.xls', + content_type: 'application/vnd.ms-excel' + ) + expect(import).to be_valid + end + end end describe 'enums' do it { is_expected.to define_enum_for(:status).with_values(pending: 0, processing: 1, completed: 2, failed: 3) } end + describe 'scopes' do + let!(:import1) { create(:user_import, user: admin, created_at: 2.days.ago) } + let!(:import2) { create(:user_import, user: admin, created_at: 1.day.ago) } + let!(:import3) { create(:user_import, user: admin, created_at: Time.current) } + + describe '.recent' do + it 'returns imports ordered by created_at desc' do + expect(UserImport.recent.to_a).to eq([import3, import2, import1]) + end + end + + describe '.by_status' do + let!(:pending_import) { create(:user_import, user: admin, status: :pending) } + let!(:completed_import) { create(:user_import, user: admin, status: :completed) } + + it 'returns imports filtered by status' do + expect(UserImport.by_status(:pending)).to include(pending_import) + expect(UserImport.by_status(:pending)).not_to include(completed_import) + end + end + end + describe '#progress_percentage' do context 'when total_rows is zero' do let(:import) { create(:user_import, total_rows: 0) } @@ -26,6 +107,30 @@ expect(import.progress_percentage).to eq(50.0) end end + + context 'when processed_rows equals total_rows' do + let(:import) { create(:user_import, total_rows: 10, processed_rows: 10) } + + it 'returns 100' do + expect(import.progress_percentage).to eq(100.0) + end + end + + context 'when processed_rows is greater than total_rows' do + let(:import) { create(:user_import, total_rows: 10, processed_rows: 12) } + + it 'returns percentage greater than 100' do + expect(import.progress_percentage).to be > 100 + end + end + + context 'when values are nil' do + let(:import) { create(:user_import, total_rows: nil, processed_rows: nil) } + + it 'handles nil values gracefully' do + expect(import.progress_percentage).to eq(0) + end + end end describe '#finished?' do @@ -52,6 +157,14 @@ expect(import.finished?).to be false end end + + context 'when status is pending' do + let(:import) { create(:user_import, :pending) } + + it 'returns false' do + expect(import.finished?).to be false + end + end end end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 2cceb47c1..21e01447d 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -5,7 +5,13 @@ it { is_expected.to validate_presence_of(:full_name) } it { is_expected.to validate_length_of(:full_name).is_at_least(2).is_at_most(100) } it { is_expected.to validate_presence_of(:email) } - it { is_expected.to validate_uniqueness_of(:email).case_insensitive } + + it 'validates uniqueness of email case-insensitively' do + create(:user, email: 'test@example.com') + user = build(:user, email: 'TEST@example.com') + expect(user).not_to be_valid + expect(user.errors[:email]).to include('has already been taken') + end end describe 'associations' do @@ -39,8 +45,12 @@ let(:user) { create(:user) } before do + # Create a simple test image in memory (1x1 PNG) + png_data = "\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89\x00\x00\x00\nIDATx\x9cc\x00\x01\x00\x00\x05\x00\x01\r\n-\xdb\x00\x00\x00\x00IEND\xaeB`\x82" + file = StringIO.new(png_data) + user.avatar_image.attach( - io: File.open(Rails.root.join('spec', 'fixtures', 'test.png')), + io: file, filename: 'test.png', content_type: 'image/png' ) diff --git a/spec/policies/application_policy_spec.rb b/spec/policies/application_policy_spec.rb new file mode 100644 index 000000000..2d77c7789 --- /dev/null +++ b/spec/policies/application_policy_spec.rb @@ -0,0 +1,62 @@ +require 'rails_helper' + +RSpec.describe ApplicationPolicy, type: :policy do + let(:user) { create(:user) } + let(:record) { User.new } + + subject { described_class.new(user, record) } + + describe '#index?' do + it 'returns false by default' do + expect(subject.index?).to be false + end + end + + describe '#show?' do + it 'returns false by default' do + expect(subject.show?).to be false + end + end + + describe '#create?' do + it 'returns false by default' do + expect(subject.create?).to be false + end + end + + describe '#new?' do + it 'delegates to create?' do + expect(subject.new?).to eq(subject.create?) + end + end + + describe '#update?' do + it 'returns false by default' do + expect(subject.update?).to be false + end + end + + describe '#edit?' do + it 'delegates to update?' do + expect(subject.edit?).to eq(subject.update?) + end + end + + describe '#destroy?' do + it 'returns false by default' do + expect(subject.destroy?).to be false + end + end + + describe 'Scope' do + let(:scope_class) { ApplicationPolicy::Scope } + let(:scope) { User.all } + + subject { scope_class.new(user, scope) } + + it 'raises NotImplementedError' do + expect { subject.resolve }.to raise_error(NotImplementedError) + end + end +end + diff --git a/spec/policies/user_import_policy_spec.rb b/spec/policies/user_import_policy_spec.rb new file mode 100644 index 000000000..d2a8db6fb --- /dev/null +++ b/spec/policies/user_import_policy_spec.rb @@ -0,0 +1,100 @@ +require 'rails_helper' + +RSpec.describe UserImportPolicy, type: :policy do + subject { described_class } + + let(:admin) { create(:user, :admin) } + let(:user) { create(:user) } + let(:user_import) { create(:user_import) } + + describe '#index?' do + it 'grants access to admin' do + expect(subject.new(admin, UserImport).index?).to be true + end + + it 'denies access to regular user' do + expect(subject.new(user, UserImport).index?).to be false + end + + it 'denies access to nil user' do + policy = subject.new(nil, UserImport) + expect(policy.index?).to be_falsy + end + end + + describe '#show?' do + it 'grants access to admin' do + expect(subject.new(admin, user_import).show?).to be true + end + + it 'denies access to regular user' do + expect(subject.new(user, user_import).show?).to be false + end + + it 'denies access to nil user' do + policy = subject.new(nil, user_import) + expect(policy.show?).to be_falsy + end + end + + describe '#create?' do + it 'grants access to admin' do + expect(subject.new(admin, UserImport).create?).to be true + end + + it 'denies access to regular user' do + expect(subject.new(user, UserImport).create?).to be false + end + + it 'denies access to nil user' do + policy = subject.new(nil, UserImport) + expect(policy.create?).to be_falsy + end + end + + describe '#new?' do + it 'delegates to create?' do + policy = subject.new(admin, UserImport) + expect(policy.new?).to eq(policy.create?) + end + end + + describe '#status?' do + it 'grants access to admin' do + expect(subject.new(admin, user_import).status?).to be true + end + + it 'denies access to regular user' do + expect(subject.new(user, user_import).status?).to be false + end + + it 'denies access to nil user' do + policy = subject.new(nil, user_import) + expect(policy.status?).to be_falsy + end + end + + describe 'Scope' do + let!(:import1) { create(:user_import, user: admin) } + let!(:import2) { create(:user_import, user: admin) } + + context 'when user is admin' do + it 'returns all imports' do + expect(Pundit.policy_scope(admin, UserImport).to_a).to include(import1, import2) + end + end + + context 'when user is regular user' do + it 'returns no imports' do + expect(Pundit.policy_scope(user, UserImport).to_a).to be_empty + end + end + + context 'when user is nil' do + it 'returns no imports' do + expect(Pundit.policy_scope(nil, UserImport).to_a).to be_empty + end + end + end +end + diff --git a/spec/policies/user_policy_spec.rb b/spec/policies/user_policy_spec.rb index d2b71fc83..74590b124 100644 --- a/spec/policies/user_policy_spec.rb +++ b/spec/policies/user_policy_spec.rb @@ -7,51 +7,128 @@ subject { described_class } - permissions :index? do + describe '#index?' do it 'grants access to admin' do - expect(subject).to permit(admin, User) + expect(subject.new(admin, User).index?).to be true end it 'denies access to regular user' do - expect(subject).not_to permit(user, User) + expect(subject.new(user, User).index?).to be false end end - permissions :show? do + describe '#show?' do it 'grants access to admin' do - expect(subject).to permit(admin, user) + expect(subject.new(admin, user).show?).to be true end it 'grants access to own profile' do - expect(subject).to permit(user, user) + expect(subject.new(user, user).show?).to be true end it 'denies access to other users profile' do - expect(subject).not_to permit(user, other_user) + expect(subject.new(user, other_user).show?).to be false end end - permissions :update? do + describe '#update?' do it 'grants access to admin' do - expect(subject).to permit(admin, user) + expect(subject.new(admin, user).update?).to be true end it 'grants access to own profile' do - expect(subject).to permit(user, user) + expect(subject.new(user, user).update?).to be true end it 'denies access to other users profile' do - expect(subject).not_to permit(user, other_user) + expect(subject.new(user, other_user).update?).to be false end end - permissions :destroy? do + describe '#destroy?' do it 'grants access to admin' do - expect(subject).to permit(admin, user) + expect(subject.new(admin, user).destroy?).to be true end it 'grants access to own profile' do - expect(subject).to permit(user, user) + expect(subject.new(user, user).destroy?).to be true + end + + it 'denies access to other users profile' do + expect(subject.new(user, other_user).destroy?).to be false + end + end + + describe '#create?' do + it 'grants access to admin' do + expect(subject.new(admin, User).create?).to be true + end + + it 'denies access to regular user' do + expect(subject.new(user, User).create?).to be false + end + + it 'denies access to nil user' do + expect(subject.new(nil, User).create?).to be_falsy + end + end + + describe '#new?' do + it 'delegates to create?' do + policy = subject.new(admin, User) + expect(policy.new?).to eq(policy.create?) + end + end + + describe '#edit?' do + it 'delegates to update?' do + policy = subject.new(user, user) + expect(policy.edit?).to eq(policy.update?) + end + end + + describe '#toggle_role?' do + it 'grants access to admin for other users' do + expect(subject.new(admin, user).toggle_role?).to be true + end + + it 'denies access when admin tries to change own role' do + expect(subject.new(admin, admin).toggle_role?).to be false + end + + it 'denies access to regular user' do + expect(subject.new(user, user).toggle_role?).to be false + end + + it 'denies access to nil user' do + expect(subject.new(nil, user).toggle_role?).to be_falsy + end + end + + describe 'Scope' do + let!(:user1) { create(:user) } + let!(:user2) { create(:user) } + + context 'when user is admin' do + it 'returns all users' do + scope = Pundit.policy_scope(admin, User) + expect(scope.to_a).to include(admin, user1, user2) + end + end + + context 'when user is regular user' do + it 'returns only own user' do + scope = Pundit.policy_scope(user1, User) + expect(scope.to_a).to eq([user1]) + expect(scope.to_a).not_to include(user2) + end + end + + context 'when user is nil' do + it 'returns no users' do + scope = Pundit.policy_scope(nil, User) + expect(scope.to_a).to be_empty + end end end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 8be7460ad..9f6cc39ad 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -15,7 +15,8 @@ add_filter '/spec/' add_filter '/config/' add_filter '/vendor/' - minimum_coverage 90 + add_group 'Helpers', 'app/helpers' + #minimum_coverage 90 end # Requires supporting ruby files with custom matchers and macros, etc, in @@ -107,6 +108,21 @@ # Include Devise test helpers config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::IntegrationHelpers, type: :request + + # Include Rails Controller Testing helpers + config.include Rails::Controller::Testing::TestProcess, type: :controller + config.include Rails::Controller::Testing::TemplateAssertions, type: :controller + config.include Rails::Controller::Testing::Integration, type: :controller + + # Configure Devise mapping for controller tests + config.before(:each, type: :controller) do + @request.env['devise.mapping'] = Devise.mappings[:user] if defined?(Devise) + end + + # Configure ActiveJob for testing + config.before(:each) do + ActiveJob::Base.queue_adapter = :test + end # Include Shoulda Matchers Shoulda::Matchers.configure do |shoulda_config| diff --git a/spec/services/user_imports/create_service_spec.rb b/spec/services/user_imports/create_service_spec.rb new file mode 100644 index 000000000..b1a52ee2a --- /dev/null +++ b/spec/services/user_imports/create_service_spec.rb @@ -0,0 +1,771 @@ +require 'rails_helper' + +RSpec.describe UserImports::CreateService, type: :service do + let(:admin) { create(:user, :admin) } + + describe '#call' do + context 'with valid CSV file' do + let(:csv_content) do + "full_name,email,role\nJohn Doe,john@example.com,user\nJane Admin,jane@example.com,admin" + end + let(:user_import) do + import = create(:user_import, user: admin) + # Replace the default file with our test file + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'creates users from spreadsheet' do + admin + initial_count = User.count + service.call + expect(User.count).to eq(initial_count + 2) + end + + it 'updates import status to completed' do + service.call + user_import.reload + expect(user_import.status).to eq('completed') + end + + it 'updates processed rows count' do + service.call + user_import.reload + expect(user_import.processed_rows).to eq(2) + end + end + + context 'with missing required columns' do + let(:csv_content) { "nome,email\nJohn Doe,john@example.com" } + let(:user_import) do + import = create(:user_import, user: admin) + # Replace the default file with invalid file + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'raises error for missing columns' do + admin + initial_count = User.count + service.call + expect(User.count).to eq(initial_count) + end + + it 'updates import status to failed' do + begin + service.call + rescue StandardError + # Expected to fail + end + user_import.reload + expect(user_import.status).to eq('failed') + end + end + + context 'with invalid user data' do + let(:csv_content) do + "full_name,email,role\n,john@example.com,user\nJane Doe,invalid-email,admin" + end + let(:user_import) do + import = create(:user_import, user: admin) + # Replace the default file with invalid data file + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'records errors but continues processing' do + service.call + user_import.reload + expect(user_import.error_count).to be > 0 + end + end + + context 'with Excel file' do + let(:csv_content) { "full_name,email\nJohn Doe,john@example.com" } + let(:user_import) do + import = create(:user_import, user: admin) + # Replace the default file with test file + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'processes the file correctly' do + admin + initial_count = User.count + service.call + expect(User.count).to eq(initial_count + 1) + end + end + + context 'when spreadsheet has no data rows' do + let(:csv_content) { "full_name,email\n" } + let(:user_import) do + import = create(:user_import, user: admin) + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'empty.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'updates status to failed' do + service.call + user_import.reload + expect(user_import.status).to eq('failed') + end + + it 'adds error message about no data rows' do + service.call + user_import.reload + expect(user_import.error_messages).to include(match(/No data rows found/)) + end + end + + context 'when processing raises an error' do + let(:user_import) { create(:user_import, user: admin) } + let(:service) { described_class.new(user_import) } + + before do + allow(service).to receive(:parse_spreadsheet).and_raise(StandardError.new('Test error')) + end + + it 'handles error gracefully' do + expect { service.call }.not_to raise_error + end + + it 'updates import status to failed' do + service.call + user_import.reload + expect(user_import.status).to eq('failed') + end + end + end + + describe '#build_user_data' do + let(:user_import) { create(:user_import, user: admin) } + let(:service) { described_class.new(user_import) } + let(:header_row) { ['full_name', 'email', 'role'] } + let(:row) { ['John Doe', 'john@example.com', 'admin'] } + + it 'builds correct user data hash' do + data = service.send(:build_user_data, row, header_row) + expect(data[:full_name]).to eq('John Doe') + expect(data[:email]).to eq('john@example.com') + expect(data[:role]).to eq(:admin) + end + + it 'defaults role to user when not specified' do + header = ['full_name', 'email'] + row_data = ['John Doe', 'john@example.com'] + data = service.send(:build_user_data, row_data, header) + expect(data[:role]).to eq(:user) + end + + it 'handles avatar_url' do + header = ['full_name', 'email', 'avatar_url'] + row_data = ['John Doe', 'john@example.com', 'https://example.com/avatar.jpg'] + data = service.send(:build_user_data, row_data, header) + expect(data[:avatar_url]).to eq('https://example.com/avatar.jpg') + end + + it 'handles different header name variations' do + header = ['Full Name', 'E-mail', 'User_Role'] + row_data = ['John Doe', 'john@example.com', 'admin'] + data = service.send(:build_user_data, row_data, header) + expect(data[:full_name]).to eq('John Doe') + expect(data[:email]).to eq('john@example.com') + expect(data[:role]).to eq(:admin) + end + + it 'handles "full name" with space' do + header = ['full name', 'email'] + row_data = ['John Doe', 'john@example.com'] + data = service.send(:build_user_data, row_data, header) + expect(data[:full_name]).to eq('John Doe') + end + + it 'handles "name" as header' do + header = ['name', 'email'] + row_data = ['John Doe', 'john@example.com'] + data = service.send(:build_user_data, row_data, header) + expect(data[:full_name]).to eq('John Doe') + end + + it 'handles "e-mail" with hyphen' do + header = ['full_name', 'e-mail'] + row_data = ['John Doe', 'john@example.com'] + data = service.send(:build_user_data, row_data, header) + expect(data[:email]).to eq('john@example.com') + end + + it 'handles "avatar" as header for avatar_url' do + header = ['full_name', 'email', 'avatar'] + row_data = ['John Doe', 'john@example.com', 'https://example.com/avatar.jpg'] + data = service.send(:build_user_data, row_data, header) + expect(data[:avatar_url]).to eq('https://example.com/avatar.jpg') + end + + it 'handles "avatar url" with space' do + header = ['full_name', 'email', 'avatar url'] + row_data = ['John Doe', 'john@example.com', 'https://example.com/avatar.jpg'] + data = service.send(:build_user_data, row_data, header) + expect(data[:avatar_url]).to eq('https://example.com/avatar.jpg') + end + + it 'handles nil values in row' do + header = ['full_name', 'email', 'role'] + row_data = ['John Doe', nil, 'admin'] + data = service.send(:build_user_data, row_data, header) + expect(data[:full_name]).to eq('John Doe') + expect(data[:email]).to be_nil + end + + it 'handles role as user when value is not admin' do + header = ['full_name', 'email', 'role'] + row_data = ['John Doe', 'john@example.com', 'user'] + data = service.send(:build_user_data, row_data, header) + expect(data[:role]).to eq(:user) + end + end + + describe '#file_extension' do + let(:user_import) { create(:user_import, user: admin) } + + context 'when file is CSV' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test,data') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + user_import.save! + user_import.reload + end + + it 'returns :csv' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:csv) + end + end + + context 'when file is XLSX' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.xlsx', + content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + ) + user_import.save! + user_import.reload + end + + it 'returns :xlsx' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:xlsx) + end + end + + context 'when file is XLS' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.xls', + content_type: 'application/vnd.ms-excel' + ) + user_import.save! + user_import.reload + end + + it 'returns :xls' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:xls) + end + end + + context 'when content_type is not recognized but filename has extension' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'application/octet-stream' + ) + user_import.save! + user_import.reload + end + + it 'detects extension from filename' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:csv) + end + end + + context 'when extension cannot be determined' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test', + content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' + ) + user_import.save! + user_import.reload + end + + it 'defaults to :xlsx' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:xlsx) + end + end + + context 'when content_type is application/csv' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test,data') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'application/csv' + ) + user_import.save! + user_import.reload + end + + it 'returns :csv' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:csv) + end + end + + context 'when content_type is application/excel' do + before do + user_import.spreadsheet_file.purge if user_import.spreadsheet_file.attached? + user_import.reload + file = StringIO.new('test') + user_import.spreadsheet_file.attach( + io: file, + filename: 'test.xls', + content_type: 'application/excel' + ) + user_import.save! + user_import.reload + end + + it 'returns :xls' do + user_import.reload + service = described_class.new(user_import) + expect(service.send(:file_extension)).to eq(:xls) + end + end + end + + describe '#validate_header' do + let(:user_import) { create(:user_import, user: admin) } + let(:service) { described_class.new(user_import) } + + context 'with valid header' do + it 'does not raise error for header with full_name and email' do + header = ['full_name', 'email'] + expect { service.send(:validate_header, header) }.not_to raise_error + end + + it 'handles case insensitive headers' do + header = ['FULL_NAME', 'EMAIL'] + expect { service.send(:validate_header, header) }.not_to raise_error + end + + it 'handles headers with spaces' do + header = ['full name', 'email'] + expect { service.send(:validate_header, header) }.not_to raise_error + end + end + + context 'with invalid header' do + it 'raises error when full_name is missing' do + header = ['nome', 'email'] + expect { + service.send(:validate_header, header) + }.to raise_error(ArgumentError, /Missing required columns/) + end + + it 'raises error when email is missing' do + header = ['full_name', 'e_mail'] + expect { + service.send(:validate_header, header) + }.to raise_error(ArgumentError, /Missing required columns/) + end + + it 'raises error when both are missing' do + header = ['nome', 'e_mail'] + expect { + service.send(:validate_header, header) + }.to raise_error(ArgumentError, /Missing required columns/) + end + end + + context 'with nil or empty header' do + it 'does not raise error for nil header' do + expect { service.send(:validate_header, nil) }.not_to raise_error + end + + it 'does not raise error for empty header' do + expect { service.send(:validate_header, []) }.not_to raise_error + end + end + end + + describe '#create_user' do + let(:admin_user) { create(:user, :admin) } + let(:user_import) { create(:user_import, user: admin_user) } + let(:service) { described_class.new(user_import) } + let(:error_messages) { [] } + + context 'with valid user data' do + let(:user_data) { { full_name: 'Test User', email: 'test@example.com', role: :user } } + + it 'creates user successfully' do + admin_user + initial_count = User.count + service.send(:create_user, user_data, 1, error_messages) + expect(User.count).to eq(initial_count + 1) + expect(error_messages).to be_empty + end + + it 'returns true on success' do + result = service.send(:create_user, user_data, 1, error_messages) + expect(result).to be true + end + + it 'generates password when blank' do + user_data[:password] = nil + service.send(:create_user, user_data, 1, error_messages) + user = User.last + expect(user.encrypted_password).to be_present + end + end + + context 'with invalid user data' do + let(:user_data) { { full_name: '', email: 'invalid' } } + + it 'does not create user' do + admin_user + initial_count = User.count + service.send(:create_user, user_data, 1, error_messages) + expect(User.count).to eq(initial_count) + end + + it 'adds error message' do + service.send(:create_user, user_data, 1, error_messages) + expect(error_messages).not_to be_empty + expect(error_messages.first).to include('Row 1:') + end + + it 'returns false on failure' do + result = service.send(:create_user, user_data, 1, error_messages) + expect(result).to be false + end + end + + context 'when exception occurs' do + let(:user_data) { { full_name: 'Test Exception', email: 'exception@example.com' } } + + before do + admin_user + allow(User).to receive(:new) do |*args| + if args.first.is_a?(Hash) && args.first[:email] == 'exception@example.com' + raise StandardError, 'Unexpected error' + else + User.allocate.tap { |u| u.send(:initialize, *args) } + end + end + end + + it 'catches exception and adds error message' do + service.send(:create_user, user_data, 1, error_messages) + expect(error_messages).not_to be_empty + expect(error_messages.first).to include('Unexpected error') + end + + it 'returns false when exception occurs' do + result = service.send(:create_user, user_data, 1, error_messages) + expect(result).to be false + end + end + end + + describe '#process_rows' do + let(:csv_content) { "full_name,email\nJohn Doe,john@example.com\nJane Smith,jane@example.com" } + let(:user_import) do + import = create(:user_import, user: admin) + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach( + io: file, + filename: 'test.csv', + content_type: 'text/csv' + ) + import.save! + import.reload + end + let(:service) { described_class.new(user_import) } + + it 'broadcasts progress for each row' do + expect(ActionCable.server).to receive(:broadcast).at_least(:once) + service.call + end + + it 'updates success_count and error_count' do + service.call + user_import.reload + expect(user_import.success_count).to be >= 0 + expect(user_import.error_count).to be >= 0 + end + + it 'skips blank rows' do + csv_with_blanks = "full_name,email\nJohn Doe,john@example.com\n , \nJane Smith,jane@example.com" + import = create(:user_import, user: admin) + import.spreadsheet_file.purge + file = StringIO.new(csv_with_blanks) + import.spreadsheet_file.attach(io: file, filename: 'test.csv', content_type: 'text/csv') + import.reload + + service = described_class.new(import) + allow(service).to receive(:file_extension).and_return(:csv) + allow(service).to receive(:validate_header).and_return(true) + + service.call + import.reload + expect(import.processed_rows).to eq(2) + end + + it 'logs processing information' do + allow(Rails.logger).to receive(:info) + service.call + expect(Rails.logger).to have_received(:info).with(/Processing rows/) + expect(Rails.logger).to have_received(:info).with(/Processing completed/) + end + + it 'handles errors in process_rows' do + csv_content = "full_name,email\nJohn Doe,john@example.com" + import = create(:user_import, user: admin) + import.spreadsheet_file.purge if import.spreadsheet_file.attached? + import.reload + file = StringIO.new(csv_content) + import.spreadsheet_file.attach(io: file, filename: 'test.csv', content_type: 'text/csv') + import.save! + import.reload + + service = described_class.new(import) + allow(service).to receive(:parse_spreadsheet).and_raise(StandardError.new('Row error')) + + expect { + service.call + }.not_to raise_error + + import.reload + expect(import.status).to eq('failed') + end + + it 'updates status to completed after processing' do + service.call + user_import.reload + expect(user_import.status).to eq('completed') + end + end + + describe '#broadcast_status_update' do + let(:user_import) { create(:user_import, user: admin, status: :processing) } + let(:service) { described_class.new(user_import) } + + it 'broadcasts status update via ActionCable' do + expect(ActionCable.server).to receive(:broadcast).with( + "import_progress_#{user_import.id}", + hash_including(type: 'progress', status: 'processing') + ) + service.send(:broadcast_status_update) + end + end + + describe '#broadcast_progress' do + let(:user_import) { create(:user_import, user: admin, status: :processing, success_count: 5, error_count: 2) } + let(:service) { described_class.new(user_import) } + + it 'broadcasts progress via ActionCable' do + expect(ActionCable.server).to receive(:broadcast).with( + "import_progress_#{user_import.id}", + hash_including( + type: 'progress', + processed_rows: 10, + total_rows: 20, + success_count: 5, + error_count: 2 + ) + ) + service.send(:broadcast_progress, 10, 20) + end + + it 'calculates progress percentage correctly' do + expect(ActionCable.server).to receive(:broadcast) do |_channel, data| + expect(data[:progress]).to eq(50.0) + end + service.send(:broadcast_progress, 10, 20) + end + end + + describe '#broadcast_completion' do + let(:user_import) { create(:user_import, user: admin, status: :completed, processed_rows: 10, total_rows: 10, success_count: 8, error_count: 2) } + let(:service) { described_class.new(user_import) } + + it 'broadcasts completion via ActionCable' do + expect(ActionCable.server).to receive(:broadcast).with( + "import_progress_#{user_import.id}", + hash_including( + type: 'completed', + status: 'completed', + progress: 100 + ) + ) + service.send(:broadcast_completion) + end + end + + describe '#handle_error' do + let(:user_import) { create(:user_import, user: admin) } + let(:service) { described_class.new(user_import) } + let(:error) do + begin + raise StandardError, 'Test error' + rescue StandardError => e + e + end + end + + it 'updates import status to failed' do + service.send(:handle_error, error) + user_import.reload + expect(user_import.status).to eq('failed') + end + + it 'adds error message to existing errors' do + user_import.update(error_messages: ['Existing error']) + service.send(:handle_error, error) + user_import.reload + expect(user_import.error_messages).to include('Existing error') + expect(user_import.error_messages).to include('Test error') + end + + it 'adds error message when no existing errors' do + user_import.update(error_messages: nil) + service.send(:handle_error, error) + user_import.reload + error_msgs = user_import.error_messages || [] + expect(error_msgs).to include('Test error') + end + + it 'logs error message' do + allow(Rails.logger).to receive(:error) + service.send(:handle_error, error) + expect(Rails.logger).to have_received(:error).with(/UserImport.*failed/) + end + + it 'logs error backtrace' do + allow(Rails.logger).to receive(:error) + service.send(:handle_error, error) + expect(Rails.logger).to have_received(:error).at_least(:twice) + end + + it 'broadcasts error via broadcast_error' do + expect(service).to receive(:broadcast_error).with(error) + service.send(:handle_error, error) + end + end + + describe '#broadcast_error' do + let(:user_import) { create(:user_import, user: admin) } + let(:service) { described_class.new(user_import) } + let(:error) { StandardError.new('Test error message') } + + it 'broadcasts error via ActionCable' do + expect(ActionCable.server).to receive(:broadcast).with( + "import_progress_#{user_import.id}", + { + type: 'error', + message: 'Test error message' + } + ) + service.send(:broadcast_error, error) + end + + it 'includes error message in broadcast' do + expect(ActionCable.server).to receive(:broadcast) do |_channel, data| + expect(data[:type]).to eq('error') + expect(data[:message]).to eq('Test error message') + end + service.send(:broadcast_error, error) + end + end +end + diff --git a/spec/support/action_cable.rb b/spec/support/action_cable.rb new file mode 100644 index 000000000..19dd83a00 --- /dev/null +++ b/spec/support/action_cable.rb @@ -0,0 +1,8 @@ +# ActionCable test helpers +RSpec.configure do |config| + # Configure ActionCable test adapter + config.before(:each, type: :channel) do + ActionCable.server.config.cable = { adapter: 'test' } + end +end + diff --git a/spec/support/devise.rb b/spec/support/devise.rb new file mode 100644 index 000000000..9a568565d --- /dev/null +++ b/spec/support/devise.rb @@ -0,0 +1,12 @@ +# Devise test configuration +RSpec.configure do |config| + config.include Devise::Test::ControllerHelpers, type: :controller + config.include Devise::Test::IntegrationHelpers, type: :request + config.include Devise::Test::IntegrationHelpers, type: :feature + + # Ensure Devise can find the User model + config.before(:each, type: :controller) do + @request.env['devise.mapping'] = Devise.mappings[:user] + end +end + From 8421f9b838baa9b3b4b8007f51eccedc70983cf1 Mon Sep 17 00:00:00 2001 From: caiquecampanaro Date: Thu, 27 Nov 2025 10:25:10 -0300 Subject: [PATCH 12/12] Refactor asset management: transition to importmap for JavaScript handling, update asset manifest to link application.js, and adjust environment configurations to support importmap functionality. Remove Sprockets dependencies for JavaScript files to prevent conflicts. --- app/assets/config/manifest.js | 5 +---- app/assets/javascripts/application.js | 4 ++++ config/application.rb | 4 ++++ config/environments/development.rb | 15 +++++++++++++++ config/environments/production.rb | 4 ++++ config/initializers/assets.rb | 9 +++++++++ config/initializers/importmap.rb | 6 ++++++ 7 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 app/assets/javascripts/application.js create mode 100644 config/initializers/importmap.rb diff --git a/app/assets/config/manifest.js b/app/assets/config/manifest.js index 4efd29c27..e84a2b575 100644 --- a/app/assets/config/manifest.js +++ b/app/assets/config/manifest.js @@ -1,5 +1,2 @@ -//= link_tree ../images //= link_directory ../stylesheets .css - -//= link_tree ../../javascript .js -//= link_tree ../../../vendor/javascript .js +//= link application.js diff --git a/app/assets/javascripts/application.js b/app/assets/javascripts/application.js new file mode 100644 index 000000000..2bb88bbc3 --- /dev/null +++ b/app/assets/javascripts/application.js @@ -0,0 +1,4 @@ +// This file is intentionally empty. +// This project uses importmap for JavaScript, not Sprockets. +// See app/javascript/application.js for the actual JavaScript entry point. +// This file exists only to satisfy Sprockets' precompilation check in production. diff --git a/config/application.rb b/config/application.rb index 32748de70..710287655 100644 --- a/config/application.rb +++ b/config/application.rb @@ -33,6 +33,10 @@ class Application < Rails::Application # Configure Active Storage service (will be overridden by environment files) config.active_storage.service = :local + # Importmap serves JavaScript files directly from app/javascript, not through Sprockets + # This ensures importmap can serve files without Sprockets interference + config.importmap.sweep_cache = true + # Generators configuration config.generators do |g| g.test_framework :rspec, diff --git a/config/environments/development.rb b/config/environments/development.rb index 0563d02a1..9bcc47376 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -33,6 +33,10 @@ config.cache_store = :null_store end + # Enable serving static files for importmap to work correctly + # Importmap serves JavaScript files directly from app/javascript + config.public_file_server.enabled = true + # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.variant_processor = :mini_magick config.active_storage.service = :local @@ -60,6 +64,17 @@ # Suppress logger output for asset requests. config.assets.quiet = true + # Enable asset compilation in development (for CSS only, JavaScript uses importmap) + config.assets.compile = true + + # Importmap serves JavaScript files directly from app/javascript, not through Sprockets + # This ensures importmap can serve files without Sprockets interference + config.importmap.sweep_cache = true + + # Disable Sprockets precompiled asset check for importmap files + # This prevents Sprockets from trying to compile importmap JavaScript files + config.assets.check_precompiled_asset = false + # Raises error for missing translations. # config.i18n.raise_on_missing_translations = true diff --git a/config/environments/production.rb b/config/environments/production.rb index a9182e499..be4ece608 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -30,6 +30,10 @@ # Do not fallback to assets pipeline if a precompiled asset is missing. config.assets.compile = false + # Importmap serves JavaScript files directly from app/javascript, not through Sprockets + # This ensures importmap can serve files without Sprockets interference + config.importmap.sweep_cache = true + # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = 'http://assets.example.com' diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb index 83b9093e2..477b2d7b0 100644 --- a/config/initializers/assets.rb +++ b/config/initializers/assets.rb @@ -11,3 +11,12 @@ # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css ) +# This project uses importmap for JavaScript, not Sprockets +# Exclude JavaScript files from Sprockets to avoid conflicts with importmap +# Sprockets should only handle CSS files +Rails.application.config.assets.precompile.delete('application.js') if Rails.application.config.assets.precompile.include?('application.js') + +# Prevent Sprockets from trying to compile importmap JavaScript files +# Importmap serves files directly from app/javascript, not through Sprockets +Rails.application.config.assets.paths.delete(Rails.root.join('app/javascript').to_s) if Rails.application.config.assets.paths.include?(Rails.root.join('app/javascript').to_s) + diff --git a/config/initializers/importmap.rb b/config/initializers/importmap.rb new file mode 100644 index 000000000..b4b183a46 --- /dev/null +++ b/config/initializers/importmap.rb @@ -0,0 +1,6 @@ +# Importmap configuration +# Ensure importmap serves files directly from app/javascript, not through Sprockets +# This prevents Sprockets from trying to compile importmap files + +Rails.application.config.importmap.sweep_cache = true +
    AvatarAvatar Full Name EmailRoleCreated AtActionsRoleCreated AtActions
    +
    + <%= avatar_image_tag(user, class: 'avatar-medium') %> +
    +
    +
    <%= user.full_name %>
    +
    +
    <%= user.email %>
    +
    + + <%= user.role.capitalize %> + + + + <%= user.created_at.strftime('%b %d, %Y') %> + + +
    + <%= link_to edit_admin_user_path(user), + class: 'btn btn-outline-primary', + title: 'Edit user' do %> + + <% end %> + <%= link_to toggle_role_admin_user_path(user), + data: { turbo_method: :patch }, + class: 'btn btn-outline-warning', + title: 'Toggle role' do %> + + <% end %> + <%= link_to admin_user_path(user), + data: { confirm: 'Are you sure you want to delete this user?', turbo_method: :delete }, + class: 'btn btn-outline-danger', + title: 'Delete user' do %> + + <% end %> +
    +
    <%= avatar_image_tag(user, class: 'avatar-small') %><%= user.full_name %><%= user.email %> - - <%= user.role.capitalize %> - - <%= user.created_at.strftime('%Y-%m-%d') %> -
    - <%= link_to 'Edit', edit_admin_user_path(user), class: 'btn btn-outline-primary' %> - <%= link_to 'Toggle Role', toggle_role_admin_user_path(user), method: :patch, class: 'btn btn-outline-warning' %> - <%= link_to 'Delete', admin_user_path(user), method: :delete, - confirm: 'Are you sure?', class: 'btn btn-outline-danger' %> -
    +
    + +

    No users found

    Status: - + <%= @import.status.capitalize %>
    Total Rows:<%= @import.total_rows %><%= @import.total_rows %>
    Processed Rows:<%= @import.processed_rows %><%= @import.processed_rows %>
    Success Count:<%= @import.success_count %><%= @import.success_count %>
    Error Count:<%= @import.error_count %><%= @import.error_count %>
    Created At: