From 54a82de3a0cd21bbbb7466e881def80a76380695 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:50:11 -0300 Subject: [PATCH 01/20] feat: setup project infrastructure and dependencies - Add proper .gitignore for Rails projects - Configure Docker with Dockerfile and .dockerignore - Setup Rubocop for code quality - Configure Gemfile with essential Rails gems - Add Procfile for development environment - Setup bin scripts and basic Rails structure --- .dockerignore | 51 +++ .gitignore | 59 +++ .rubocop.yml | 8 + Dockerfile | 72 ++++ Gemfile | 110 ++++++ Gemfile.lock | 538 +++++++++++++++++++++++++++ Procfile.dev | 2 + Rakefile | 6 + bin/brakeman | 7 + bin/bundle | 109 ++++++ bin/dev | 8 + bin/docker-entrypoint | 14 + bin/importmap | 4 + bin/jobs | 6 + bin/kamal | 27 ++ bin/rails | 4 + bin/rake | 4 + bin/rubocop | 8 + bin/setup | 34 ++ bin/thrust | 5 + config.ru | 6 + public/400.html | 114 ++++++ public/404.html | 114 ++++++ public/406-unsupported-browser.html | 114 ++++++ public/422.html | 114 ++++++ public/500.html | 114 ++++++ public/icon.png | Bin 0 -> 4166 bytes public/icon.svg | 3 + public/robots.txt | 1 + script/.keep | 0 test/application_system_test_case.rb | 5 + test/controllers/.keep | 0 test/fixtures/files/.keep | 0 test/helpers/.keep | 0 test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/system/.keep | 0 test/test_helper.rb | 15 + 39 files changed, 1676 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 .rubocop.yml create mode 100644 Dockerfile create mode 100644 Gemfile create mode 100644 Gemfile.lock create mode 100644 Procfile.dev create mode 100644 Rakefile create mode 100755 bin/brakeman create mode 100755 bin/bundle create mode 100755 bin/dev create mode 100755 bin/docker-entrypoint create mode 100755 bin/importmap create mode 100755 bin/jobs create mode 100755 bin/kamal create mode 100755 bin/rails create mode 100755 bin/rake create mode 100755 bin/rubocop create mode 100755 bin/setup create mode 100755 bin/thrust create mode 100644 config.ru create mode 100644 public/400.html create mode 100644 public/404.html create mode 100644 public/406-unsupported-browser.html create mode 100644 public/422.html create mode 100644 public/500.html create mode 100644 public/icon.png create mode 100644 public/icon.svg create mode 100644 public/robots.txt create mode 100644 script/.keep create mode 100644 test/application_system_test_case.rb create mode 100644 test/controllers/.keep create mode 100644 test/fixtures/files/.keep create mode 100644 test/helpers/.keep create mode 100644 test/integration/.keep create mode 100644 test/mailers/.keep create mode 100644 test/models/.keep create mode 100644 test/system/.keep create mode 100644 test/test_helper.rb diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..325bfc036 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,51 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ +/.gitignore + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep + +# Ignore assets. +/node_modules/ +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets + +# Ignore CI service files. +/.github + +# Ignore Kamal files. +/config/deploy*.yml +/.kamal + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..92bcc5328 --- /dev/null +++ b/.gitignore @@ -0,0 +1,59 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. + +# 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 storage files. +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +# Ignore uploaded files in development. +/storage/development.sqlite3 +/storage/test.sqlite3 + +# Ignore master key for decrypting credentials and more. +/config/master.key + +# Ignore bootsnap cache +/tmp/cache/ + +# Ignore node_modules +/node_modules + +# Ignore yarn files +/yarn-error.log +yarn-debug.log* +.yarn-integrity + +# Ignore coverage reports +/coverage/ + +# Ignore IDE files +.vscode/ +.idea/ +*.swp +*.swo + +# Ignore OS files +.DS_Store +Thumbs.db + +# Ignore environment variables +.env + +# Ignore Kamal secrets +/.kamal/secrets diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..f9d86d4a5 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..b2fcc5c5c --- /dev/null +++ b/Dockerfile @@ -0,0 +1,72 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t user_management_app . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name user_management_app user_management_app + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=3.4.4 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips postgresql-client && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" + +# Throw-away build stage to reduce size of final image +FROM base AS build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libpq-dev libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + bundle exec bootsnap precompile --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times +RUN bundle exec bootsnap precompile app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + + + + +# Final stage for app image +FROM base + +# Copy built artifacts: gems, application +COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --from=build /rails /rails + +# Run and own only the runtime files as a non-root user for security +RUN groupadd --system --gid 1000 rails && \ + useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ + chown -R rails:rails db log storage tmp +USER 1000:1000 + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..091e73f42 --- /dev/null +++ b/Gemfile @@ -0,0 +1,110 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.0.3" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use postgresql as the database for Active Record +gem "pg", "~> 1.1", group: :production +# Use sqlite3 as the database for Active Record in development and test +gem "sqlite3", "~> 2.0", group: [ :development, :test ] +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" +# Use Dart SASS [https://github.com/rails/dartsass-rails] +gem "dartsass-rails" +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +# gem "bcrypt", "~> 3.1.7" + +# Authentication solution for Rails [https://github.com/heartcombo/devise] +gem "devise" + +# Image processing for Active Storage [https://github.com/janko/image_processing] +gem "image_processing", "~> 1.2" + +# For CSV/Excel file handling +gem "roo", "~> 2.9" +gem "csv" + +# For background job processing +gem "sidekiq", "~> 7.0" + +# For authorization (CanCanCan) +gem "cancancan" + +# For pagination +gem "kaminari" + +# For better forms +gem "simple_form" + +# For managing environment variables +gem "dotenv-rails" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +# gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # Static analysis for security vulnerabilities [https://brakemanscanner.org/] + gem "brakeman", require: false + + # Omakase Ruby styling [https://github.com/rails/rubocop-rails-omakase/] + gem "rubocop-rails-omakase", require: false + + # RSpec for testing [https://github.com/rspec/rspec-rails] + gem "rspec-rails", "~> 7.0" + + # Factory Bot for test factories [https://github.com/thoughtbot/factory_bot_rails] + gem "factory_bot_rails" + + # Faker for generating fake data [https://github.com/faker-ruby/faker] + gem "faker" + + # Database Cleaner for test cleanup [https://github.com/DatabaseCleaner/database_cleaner] + gem "database_cleaner-active_record" + + # SimpleCov for code coverage [https://github.com/simplecov-ruby/simplecov] + gem "simplecov", require: false + + # Shoulda Matchers for easier testing [https://github.com/thoughtbot/shoulda-matchers] + gem "shoulda-matchers" +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..35320aa9c --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,538 @@ +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) + bcrypt_pbkdf (1.1.1) + benchmark (0.5.0) + bigdecimal (3.3.1) + bindex (0.8.1) + bootsnap (1.18.6) + msgpack (~> 1.2) + brakeman (7.1.1) + racc + builder (3.3.0) + cancancan (3.6.1) + 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) + concurrent-ruby (1.3.5) + connection_pool (2.5.4) + crass (1.0.6) + csv (3.3.5) + dartsass-rails (0.5.1) + railties (>= 6.0.0) + sass-embedded (~> 1.63) + 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) + debug (1.11.0) + irb (~> 1.10) + reline (>= 0.3.8) + 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) + dotenv (3.1.8) + dotenv-rails (3.1.8) + dotenv (= 3.1.8) + railties (>= 6.1) + drb (2.2.3) + ed25519 (1.4.0) + erb (5.1.3) + erubi (1.13.1) + et-orbi (1.4.0) + tzinfo + 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-x86_64-linux-gnu) + ffi (1.17.2-x86_64-linux-musl) + fugit (1.12.1) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.3.0) + activesupport (>= 6.1) + google-protobuf (4.33.0) + bigdecimal + rake (>= 13) + google-protobuf (4.33.0-aarch64-linux-gnu) + bigdecimal + rake (>= 13) + google-protobuf (4.33.0-aarch64-linux-musl) + bigdecimal + rake (>= 13) + google-protobuf (4.33.0-x86_64-linux-gnu) + bigdecimal + rake (>= 13) + google-protobuf (4.33.0-x86_64-linux-musl) + bigdecimal + rake (>= 13) + 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) + 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) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.14.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.15.2) + kamal (2.8.2) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + kaminari (1.2.2) + activesupport (>= 4.1.0) + kaminari-actionview (= 1.2.2) + kaminari-activerecord (= 1.2.2) + kaminari-core (= 1.2.2) + kaminari-actionview (1.2.2) + actionview + kaminari-core (= 1.2.2) + kaminari-activerecord (1.2.2) + activerecord + kaminari-core (= 1.2.2) + kaminari-core (1.2.2) + language_server-protocol (3.17.0.5) + lint_roller (1.1.0) + 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) + 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-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.0) + 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-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-musl) + racc (~> 1.4) + orm_adapter (0.5.0) + ostruct (0.6.3) + 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-x86_64-linux) + pg (1.6.2-x86_64-linux-musl) + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.6.0) + propshaft (1.3.1) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + psych (5.2.6) + date + stringio + public_suffix (6.0.2) + puma (7.1.0) + nio4r (~> 2.0) + raabro (1.4.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) + rdoc (6.15.1) + erb + psych (>= 4.0.0) + tsort + 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) + 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 (7.1.1) + actionpack (>= 7.0) + activesupport (>= 7.0) + railties (>= 7.0) + 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-performance (1.26.1) + lint_roller (~> 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + 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-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + ruby-vips (2.2.5) + ffi (~> 1.12) + logger + rubyzip (2.4.1) + sass-embedded (1.93.3-aarch64-linux-gnu) + google-protobuf (~> 4.31) + sass-embedded (1.93.3-aarch64-linux-musl) + google-protobuf (~> 4.31) + sass-embedded (1.93.3-arm-linux-gnueabihf) + google-protobuf (~> 4.31) + sass-embedded (1.93.3-arm-linux-musleabihf) + google-protobuf (~> 4.31) + sass-embedded (1.93.3-x86_64-linux-gnu) + google-protobuf (~> 4.31) + sass-embedded (1.93.3-x86_64-linux-musl) + google-protobuf (~> 4.31) + securerandom (0.4.1) + selenium-webdriver (4.38.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + shoulda-matchers (7.0.1) + activesupport (>= 7.1) + sidekiq (7.3.9) + base64 + connection_pool (>= 2.3.0) + logger + rack (>= 2.2.4) + redis-client (>= 0.22.2) + simple_form (5.4.0) + actionpack (>= 7.0) + activemodel (>= 7.0) + 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) + solid_cable (3.0.12) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.8) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.2.4) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sqlite3 (2.8.0-aarch64-linux-gnu) + sqlite3 (2.8.0-aarch64-linux-musl) + sqlite3 (2.8.0-arm-linux-gnu) + sqlite3 (2.8.0-arm-linux-musl) + sqlite3 (2.8.0-x86_64-linux-gnu) + sqlite3 (2.8.0-x86_64-linux-musl) + sshkit (1.24.0) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.1.7) + thor (1.4.0) + thruster (0.1.16) + thruster (0.1.16-aarch64-linux) + thruster (0.1.16-x86_64-linux) + 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.1) + useragent (0.16.11) + 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) + 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-gnueabihf + arm-linux-musl + arm-linux-musleabihf + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + cancancan + capybara + csv + dartsass-rails + database_cleaner-active_record + debug + devise + dotenv-rails + factory_bot_rails + faker + image_processing (~> 1.2) + importmap-rails + jbuilder + kamal + kaminari + pg (~> 1.1) + propshaft + puma (>= 5.0) + rails (~> 8.0.3) + roo (~> 2.9) + rspec-rails (~> 7.0) + rubocop-rails-omakase + selenium-webdriver + shoulda-matchers + sidekiq (~> 7.0) + simple_form + simplecov + solid_cable + solid_cache + solid_queue + sqlite3 (~> 2.0) + stimulus-rails + thruster + turbo-rails + tzinfo-data + web-console + +BUNDLED WITH + 2.6.9 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..852e6c710 --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,2 @@ +web: bin/rails server -p 3000 +css: bin/rails dartsass:watch diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..9a5ea7383 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# 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/bin/brakeman b/bin/brakeman new file mode 100755 index 000000000..ace1c9ba0 --- /dev/null +++ b/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/bin/bundle b/bin/bundle new file mode 100755 index 000000000..50da5fdf9 --- /dev/null +++ b/bin/bundle @@ -0,0 +1,109 @@ +#!/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" + +m = Module.new do + module_function + + def invoked_as_script? + File.expand_path($0) == File.expand_path(__FILE__) + end + + def env_var_version + ENV["BUNDLER_VERSION"] + end + + def cli_arg_version + return unless invoked_as_script? # don't want to hijack other binstubs + return unless "update".start_with?(ARGV.first || " ") # must be running `bundle update` + bundler_version = nil + update_index = nil + ARGV.each_with_index do |a, i| + if update_index && update_index.succ == i && a.match?(Gem::Version::ANCHORED_VERSION_PATTERN) + bundler_version = a + end + next unless a =~ /\A--bundler(?:[= ](#{Gem::Version::VERSION_PATTERN}))?\z/ + bundler_version = $1 + update_index = i + end + bundler_version + end + + def gemfile + gemfile = ENV["BUNDLE_GEMFILE"] + return gemfile if gemfile && !gemfile.empty? + + File.expand_path("../Gemfile", __dir__) + end + + def lockfile + lockfile = + case File.basename(gemfile) + when "gems.rb" then gemfile.sub(/\.rb$/, ".locked") + else "#{gemfile}.lock" + end + File.expand_path(lockfile) + end + + def lockfile_version + return unless File.file?(lockfile) + lockfile_contents = File.read(lockfile) + return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s{2,}(#{Gem::Version::VERSION_PATTERN})\n/ + Regexp.last_match(1) + end + + def bundler_requirement + @bundler_requirement ||= + env_var_version || + cli_arg_version || + bundler_requirement_for(lockfile_version) + end + + def bundler_requirement_for(version) + return "#{Gem::Requirement.default}.a" unless version + + bundler_gem_version = Gem::Version.new(version) + + bundler_gem_version.approximate_recommendation + end + + def load_bundler! + ENV["BUNDLE_GEMFILE"] ||= gemfile + + activate_bundler + end + + def activate_bundler + gem_error = activation_error_handling do + gem "bundler", bundler_requirement + end + return if gem_error.nil? + require_error = activation_error_handling do + require "bundler/version" + end + return if require_error.nil? && Gem::Requirement.new(bundler_requirement).satisfied_by?(Gem::Version.new(Bundler::VERSION)) + warn "Activating bundler (#{bundler_requirement}) failed:\n#{gem_error.message}\n\nTo install the version of bundler this project requires, run `gem install bundler -v '#{bundler_requirement}'`" + exit 42 + end + + def activation_error_handling + yield + nil + rescue StandardError, LoadError => e + e + end +end + +m.load_bundler! + +if m.invoked_as_script? + load Gem.bin_path("bundler", "bundle") +end diff --git a/bin/dev b/bin/dev new file mode 100755 index 000000000..74ade1664 --- /dev/null +++ b/bin/dev @@ -0,0 +1,8 @@ +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +exec foreman start -f Procfile.dev "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..57567d69b --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,14 @@ +#!/bin/bash -e + +# Enable jemalloc for reduced memory usage and latency. +if [ -z "${LD_PRELOAD+x}" ]; then + LD_PRELOAD=$(find /usr/lib -name libjemalloc.so.2 -print -quit) + export LD_PRELOAD +fi + +# If running the rails server then create or migrate existing database +if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then + ./bin/rails db:prepare +fi + +exec "${@}" 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/bin/jobs b/bin/jobs new file mode 100755 index 000000000..dcf59f309 --- /dev/null +++ b/bin/jobs @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +require_relative "../config/environment" +require "solid_queue/cli" + +SolidQueue::Cli.start(ARGV) diff --git a/bin/kamal b/bin/kamal new file mode 100755 index 000000000..cbe59b95e --- /dev/null +++ b/bin/kamal @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..efc037749 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 000000000..4fbf10b96 --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 000000000..40330c0ff --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# explicit rubocop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..be3db3c0d --- /dev/null +++ b/bin/setup @@ -0,0 +1,34 @@ +#!/usr/bin/env ruby +require "fileutils" + +APP_ROOT = File.expand_path("..", __dir__) + +def system!(*args) + system(*args, exception: true) +end + +FileUtils.chdir APP_ROOT do + # This script is a way to set up or update your development environment automatically. + # This script is idempotent, so that you can run it at any time and get an expectable outcome. + # Add necessary setup steps to this file. + + puts "== Installing dependencies ==" + system("bundle check") || system!("bundle install") + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/bin/thrust b/bin/thrust new file mode 100755 index 000000000..36bde2d83 --- /dev/null +++ b/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..4a3c09a68 --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# 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/public/400.html b/public/400.html new file mode 100644 index 000000000..282dbc8cc --- /dev/null +++ b/public/400.html @@ -0,0 +1,114 @@ + + + + + + + The server cannot process the request due to a client error (400 Bad Request) + + + + + + + + + + + + + +
+
+ +
+
+

The server cannot process the request due to a client error. Please check the request and try again. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/404.html b/public/404.html new file mode 100644 index 000000000..c0670bc87 --- /dev/null +++ b/public/404.html @@ -0,0 +1,114 @@ + + + + + + + The page you were looking for doesn’t exist (404 Not found) + + + + + + + + + + + + + +
+
+ +
+
+

The page you were looking for doesn’t exist. You may have mistyped the address or the page may have moved. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/406-unsupported-browser.html b/public/406-unsupported-browser.html new file mode 100644 index 000000000..9532a9ccd --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,114 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
+
+ +
+
+

Your browser is not supported.
Please upgrade your browser to continue.

+
+
+ + + + diff --git a/public/422.html b/public/422.html new file mode 100644 index 000000000..8bcf06014 --- /dev/null +++ b/public/422.html @@ -0,0 +1,114 @@ + + + + + + + The change you wanted was rejected (422 Unprocessable Entity) + + + + + + + + + + + + + +
+
+ +
+
+

The change you wanted was rejected. Maybe you tried to change something you didn’t have access to. If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/500.html b/public/500.html new file mode 100644 index 000000000..d77718c3a --- /dev/null +++ b/public/500.html @@ -0,0 +1,114 @@ + + + + + + + We’re sorry, but something went wrong (500 Internal Server Error) + + + + + + + + + + + + + +
+
+ +
+
+

We’re sorry, but something went wrong.
If you’re the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c4c9dbfbbd2f7c1421ffd5727188146213abbcef GIT binary patch literal 4166 zcmd6qU;WFw?|v@m)Sk^&NvB8tcujdV-r1b=i(NJxn&7{KTb zX$3(M+3TP2o^#KAo{#tIjl&t~(8D-k004kqPglzn0HFG(Q~(I*AKsD#M*g7!XK0T7 zN6P7j>HcT8rZgKl$v!xr806dyN19Bd4C0x_R*I-a?#zsTvb_89cyhuC&T**i|Rc zq5b8M;+{8KvoJ~uj9`u~d_f6`V&3+&ZX9x5pc8s)d175;@pjm(?dapmBcm0&vl9+W zx1ZD2o^nuyUHWj|^A8r>lUorO`wFF;>9XL-Jy!P}UXC{(z!FO%SH~8k`#|9;Q|eue zqWL0^Bp(fg_+Pkm!fDKRSY;+^@BF?AJE zCUWpXPst~hi_~u)SzYBDZroR+Z4xeHIlm_3Yc_9nZ(o_gg!jDgVa=E}Y8uDgem9`b zf=mfJ_@(BXSkW53B)F2s!&?_R4ptb1fYXlF++@vPhd=marQgEGRZS@B4g1Mu?euknL= z67P~tZ?*>-Hmi7GwlisNHHJDku-dSm7g@!=a}9cSL6Pa^w^2?&?$Oi8ibrr>w)xqx zOH_EMU@m05)9kuNR>>4@H%|){U$^yvVQ(YgOlh;5oU_-vivG-p4=LrN-k7D?*?u1u zsWly%tfAzKd6Fb=`eU2un_uaTXmcT#tlOL+aRS=kZZf}A7qT8lvcTx~7j` z*b>=z)mwg7%B2_!D0!1IZ?Nq{^Y$uI4Qx*6T!E2Col&2{k?ImCO=dD~A&9f9diXy^$x{6CwkBimn|1E09 zAMSezYtiL?O6hS37KpvDM?22&d{l)7h-!F)C-d3j8Z`c@($?mfd{R82)H>Qe`h{~G z!I}(2j(|49{LR?w4Jspl_i!(4T{31|dqCOpI52r5NhxYV+cDAu(xp*4iqZ2e-$YP= zoFOPmm|u*7C?S{Fp43y+V;>~@FFR76bCl@pTtyB93vNWy5yf;HKr8^0d7&GVIslYm zo3Tgt@M!`8B6IW&lK{Xk>%zp41G%`(DR&^u z5^pwD4>E6-w<8Kl2DzJ%a@~QDE$(e87lNhy?-Qgep!$b?5f7+&EM7$e>|WrX+=zCb z=!f5P>MxFyy;mIRxjc(H*}mceXw5a*IpC0PEYJ8Y3{JdoIW)@t97{wcUB@u+$FCCO z;s2Qe(d~oJC^`m$7DE-dsha`glrtu&v&93IZadvl_yjp!c89>zo;Krk+d&DEG4?x$ zufC1n+c1XD7dolX1q|7}uelR$`pT0Z)1jun<39$Sn2V5g&|(j~Z!wOddfYiZo7)A< z!dK`aBHOOk+-E_xbWCA3VR-+o$i5eO9`rMI#p_0xQ}rjEpGW;U!&&PKnivOcG(|m9 z!C8?WC6nCXw25WVa*eew)zQ=h45k8jSIPbq&?VE{oG%?4>9rwEeB4&qe#?-y_es4c|7ufw%+H5EY#oCgv!Lzv291#-oNlX~X+Jl5(riC~r z=0M|wMOP)Tt8@hNg&%V@Z9@J|Q#K*hE>sr6@oguas9&6^-=~$*2Gs%h#GF@h)i=Im z^iKk~ipWJg1VrvKS;_2lgs3n1zvNvxb27nGM=NXE!D4C!U`f*K2B@^^&ij9y}DTLB*FI zEnBL6y{jc?JqXWbkIZd7I16hA>(f9T!iwbIxJj~bKPfrO;>%*5nk&Lf?G@c2wvGrY&41$W{7HM9+b@&XY@>NZM5s|EK_Dp zQX60CBuantx>|d#DsaZ*8MW(we|#KTYZ=vNa#d*DJQe6hr~J6{_rI#?wi@s|&O}FR zG$kfPxheXh1?IZ{bDT-CWB4FTvO-k5scW^mi8?iY5Q`f8JcnnCxiy@m@D-%lO;y0pTLhh6i6l@x52j=#^$5_U^os}OFg zzdHbo(QI`%9#o*r8GCW~T3UdV`szO#~)^&X_(VW>o~umY9-ns9-V4lf~j z`QBD~pJ4a#b`*6bJ^3RS5y?RAgF7K5$ll97Y8#WZduZ`j?IEY~H(s^doZg>7-tk*t z4_QE1%%bb^p~4F5SB$t2i1>DBG1cIo;2(xTaj*Y~hlM{tSDHojL-QPg%Mo%6^7FrpB*{ z4G0@T{-77Por4DCMF zB_5Y~Phv%EQ64W8^GS6h?x6xh;w2{z3$rhC;m+;uD&pR74j+i22P5DS-tE8ABvH(U~indEbBUTAAAXfHZg5QpB@TgV9eI<)JrAkOI z8!TSOgfAJiWAXeM&vR4Glh;VxH}WG&V$bVb`a`g}GSpwggti*&)taV1@Ak|{WrV|5 zmNYx)Ans=S{c52qv@+jmGQ&vd6>6yX6IKq9O$3r&0xUTdZ!m1!irzn`SY+F23Rl6# zFRxws&gV-kM1NX(3(gnKpGi0Q)Dxi~#?nyzOR9!en;Ij>YJZVFAL*=R%7y%Mz9hU% zs>+ZB?qRmZ)nISx7wxY)y#cd$iaC~{k0avD>BjyF1q^mNQ1QcwsxiTySe<6C&cC6P zE`vwO9^k-d`9hZ!+r@Jnr+MF*2;2l8WjZ}DrwDUHzSF{WoG zucbSWguA!3KgB3MU%HH`R;XqVv0CcaGq?+;v_A5A2kpmk5V%qZE3yzQ7R5XWhq=eR zyUezH=@V)y>L9T-M-?tW(PQYTRBKZSVb_!$^H-Pn%ea;!vS_?M<~Tm>_rWIW43sPW z=!lY&fWc1g7+r?R)0p8(%zp&vl+FK4HRkns%BW+Up&wK8!lQ2~bja|9bD12WrKn#M zK)Yl9*8$SI7MAwSK$%)dMd>o+1UD<2&aQMhyjS5R{-vV+M;Q4bzl~Z~=4HFj_#2V9 zB)Gfzx3ncy@uzx?yzi}6>d%-?WE}h7v*w)Jr_gBl!2P&F3DX>j_1#--yjpL%<;JMR z*b70Gr)MMIBWDo~#<5F^Q0$VKI;SBIRneuR7)yVsN~A9I@gZTXe)E?iVII+X5h0~H zx^c(fP&4>!*q>fb6dAOC?MI>Cz3kld#J*;uik+Ps49cwm1B4 zZc1|ZxYyTv;{Z!?qS=D)sgRKx^1AYf%;y_V&VgZglfU>d+Ufk5&LV$sKv}Hoj+s; xK3FZRYdhbXT_@RW*ff3@`D1#ps#~H)p+y&j#(J|vk^lW{fF9OJt5(B-_&*Xgn9~3N literal 0 HcmV?d00001 diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 000000000..04b34bf83 --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/script/.keep b/script/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 000000000..cee29fd21 --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/system/.keep b/test/system/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 000000000..0c22470ec --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end From ddcc6d13f072037257920975d64840470aac398a Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:50:40 -0300 Subject: [PATCH 02/20] feat: setup database configuration and migrations - Configure database settings for development/test/production - Add Devise User migration with authentication fields - Create Import model migration for CSV functionality - Add trackable fields to User model for login tracking - Setup database schema and seed data - Configure Rails application environments --- config/application.rb | 27 ++++ config/boot.rb | 4 + config/database.yml | 65 +++++++++ config/environment.rb | 5 + config/environments/development.rb | 72 ++++++++++ config/environments/production.rb | 90 ++++++++++++ config/environments/test.rb | 53 +++++++ db/cable_schema.rb | 11 ++ db/cache_schema.rb | 14 ++ .../20251106182316_devise_create_users.rb | 48 +++++++ ...te_active_storage_tables.active_storage.rb | 57 ++++++++ db/migrate/20251106184110_create_imports.rb | 15 ++ .../20251106192110_add_trackable_to_users.rb | 9 ++ db/queue_schema.rb | 129 ++++++++++++++++++ db/schema.rb | 82 +++++++++++ db/seeds.rb | 90 ++++++++++++ storage/.keep | 0 17 files changed, 771 insertions(+) create mode 100644 config/application.rb create mode 100644 config/boot.rb 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 db/cable_schema.rb create mode 100644 db/cache_schema.rb create mode 100644 db/migrate/20251106182316_devise_create_users.rb create mode 100644 db/migrate/20251106183627_create_active_storage_tables.active_storage.rb create mode 100644 db/migrate/20251106184110_create_imports.rb create mode 100644 db/migrate/20251106192110_add_trackable_to_users.rb create mode 100644 db/queue_schema.rb create mode 100644 db/schema.rb create mode 100644 db/seeds.rb create mode 100644 storage/.keep diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..fc06223b9 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,27 @@ +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 UserManagementApp + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + 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") + end +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..988a5ddc4 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +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/database.yml b/config/database.yml new file mode 100644 index 000000000..0cda04b89 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,65 @@ +# PostgreSQL. Versions 9.3 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/usr/local/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem "pg" +# +default: &default + adapter: sqlite3 + pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +test: + <<: *default + database: storage/test.sqlite3 + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV["MY_APP_DATABASE_URL"] %> +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + primary: &primary_production + <<: *default + database: user_management_app_production + username: user_management_app + password: <%= ENV["USER_MANAGEMENT_APP_DATABASE_PASSWORD"] %> + cache: + <<: *primary_production + database: user_management_app_production_cache + migrations_paths: db/cache_migrate + queue: + <<: *primary_production + database: user_management_app_production_queue + migrations_paths: db/queue_migrate + cable: + <<: *primary_production + database: user_management_app_production_cable + migrations_paths: db/cable_migrate diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..cac531577 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# 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..4cc21c4eb --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,72 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # 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 Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller 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.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Make template changes take effect immediately. + config.action_mailer.perform_caching = false + + # Set localhost to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # 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 + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = 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 + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true + + # Apply autocorrection by RuboCop to files generated by `bin/rails generate`. + # config.generators.apply_rubocop_autocorrect_after_generate! +end diff --git a/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..bdcd01d1b --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,90 @@ +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.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!) + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # 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 + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via rails credentials:edit. + # config.action_mailer.smtp_settings = { + # user_name: Rails.application.credentials.dig(:smtp, :user_name), + # password: Rails.application.credentials.dig(:smtp, :password), + # address: "smtp.example.com", + # port: 587, + # authentication: :plain + # } + + # 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.fallbacks = true + + # Do not dump schema after migrations. + config.active_record.dump_schema_after_migration = false + + # Only use :id for inspections in production. + config.active_record.attributes_for_inspect = [ :id ] + + # Enable DNS rebinding protection and other `Host` header attacks. + # config.hosts = [ + # "example.com", # Allow requests from example.com + # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` + # ] + # + # Skip DNS rebinding protection for the default health check endpoint. + # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..c2095b117 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,53 @@ +# 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. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + 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.service = :test + + # 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 + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # 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 +end diff --git a/db/cable_schema.rb b/db/cable_schema.rb new file mode 100644 index 000000000..23666604a --- /dev/null +++ b/db/cable_schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_cable_messages", force: :cascade do |t| + t.binary "channel", limit: 1024, null: false + t.binary "payload", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "channel_hash", limit: 8, null: false + t.index ["channel"], name: "index_solid_cable_messages_on_channel" + t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" + t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" + end +end diff --git a/db/cache_schema.rb b/db/cache_schema.rb new file mode 100644 index 000000000..6005a2972 --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +ActiveRecord::Schema[7.2].define(version: 1) do + create_table "solid_cache_entries", force: :cascade do |t| + t.binary "key", limit: 1024, null: false + t.binary "value", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "key_hash", limit: 8, null: false + t.integer "byte_size", limit: 4, null: false + t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" + t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" + t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true + end +end diff --git a/db/migrate/20251106182316_devise_create_users.rb b/db/migrate/20251106182316_devise_create_users.rb new file mode 100644 index 000000000..5d9d0c06f --- /dev/null +++ b/db/migrate/20251106182316_devise_create_users.rb @@ -0,0 +1,48 @@ +# 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 + + ## Trackable + # t.integer :sign_in_count, default: 0, null: false + # t.datetime :current_sign_in_at + # t.datetime :last_sign_in_at + # t.string :current_sign_in_ip + # t.string :last_sign_in_ip + + ## Confirmable + # t.string :confirmation_token + # t.datetime :confirmed_at + # t.datetime :confirmation_sent_at + # t.string :unconfirmed_email # Only if using reconfirmable + + ## Lockable + # t.integer :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts + # t.string :unlock_token # Only if unlock strategy is :email or :both + # t.datetime :locked_at + + ## Custom fields + t.string :full_name, null: false + t.string :role, null: false, default: "user" + 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, :confirmation_token, unique: true + # add_index :users, :unlock_token, unique: true + end +end diff --git a/db/migrate/20251106183627_create_active_storage_tables.active_storage.rb b/db/migrate/20251106183627_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..6bd8bd082 --- /dev/null +++ b/db/migrate/20251106183627_create_active_storage_tables.active_storage.rb @@ -0,0 +1,57 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[7.0] + def change + # Use Active Record's configured type for primary and foreign keys + primary_key_type, foreign_key_type = primary_and_foreign_key_types + + create_table :active_storage_blobs, id: primary_key_type 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 + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments, id: primary_key_type do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type + t.references :blob, null: false, type: foreign_key_type + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + 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, id: primary_key_type do |t| + t.belongs_to :blob, null: false, index: false, type: foreign_key_type + 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 + + private + def primary_and_foreign_key_types + config = Rails.configuration.generators + setting = config.options[config.orm][:primary_key_type] + primary_key_type = setting || :primary_key + foreign_key_type = setting || :bigint + [ primary_key_type, foreign_key_type ] + end +end diff --git a/db/migrate/20251106184110_create_imports.rb b/db/migrate/20251106184110_create_imports.rb new file mode 100644 index 000000000..5af7d0855 --- /dev/null +++ b/db/migrate/20251106184110_create_imports.rb @@ -0,0 +1,15 @@ +class CreateImports < ActiveRecord::Migration[8.0] + def change + create_table :imports do |t| + t.string :file_name + t.string :status + t.integer :progress + t.integer :total_rows + t.integer :processed_rows + t.text :error_details + t.references :user, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/db/migrate/20251106192110_add_trackable_to_users.rb b/db/migrate/20251106192110_add_trackable_to_users.rb new file mode 100644 index 000000000..3ee2ca547 --- /dev/null +++ b/db/migrate/20251106192110_add_trackable_to_users.rb @@ -0,0 +1,9 @@ +class AddTrackableToUsers < ActiveRecord::Migration[8.0] + def change + add_column :users, :sign_in_count, :integer, default: 0, null: false + add_column :users, :current_sign_in_at, :datetime + add_column :users, :last_sign_in_at, :datetime + add_column :users, :current_sign_in_ip, :string + add_column :users, :last_sign_in_ip, :string + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 000000000..85194b6a8 --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,129 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..11202f070 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,82 @@ +# 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: 2025_11_06_192110) do + 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 + end + + create_table "imports", force: :cascade do |t| + t.string "file_name", null: false + t.string "status", default: "pending", null: false + t.integer "progress", default: 0 + t.integer "total_rows", default: 0 + t.integer "processed_rows", default: 0 + t.integer "successful_rows", default: 0 + t.integer "failed_rows", default: 0 + t.text "error_details" + t.integer "user_id", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index ["created_at"], name: "index_imports_on_created_at" + t.index ["status"], name: "index_imports_on_status" + t.index ["user_id"], name: "index_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.string "role", default: "user", null: false + t.string "avatar_url" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.integer "sign_in_count", default: 0, null: false + t.datetime "current_sign_in_at" + t.datetime "last_sign_in_at" + t.string "current_sign_in_ip" + t.string "last_sign_in_ip" + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true + 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 "imports", "users" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..468447a0b --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,90 @@ +# 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). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end + +puts "🌱 Seeding database..." + +# Create admin user +admin_email = "admin@example.com" +admin_user = User.find_or_initialize_by(email: admin_email) + +if admin_user.new_record? + admin_user.assign_attributes( + full_name: "Administrator", + role: "admin", + password: "password123", + password_confirmation: "password123" + ) + + if admin_user.save + puts "✅ Admin user created successfully!" + puts " Email: #{admin_user.email}" + puts " Password: password123" + puts " Role: #{admin_user.role}" + else + puts "❌ Failed to create admin user:" + admin_user.errors.full_messages.each do |error| + puts " - #{error}" + end + end +else + puts "ℹ️ Admin user already exists (#{admin_email})" +end + +# Create some sample regular users for testing +sample_users = [ + { + full_name: "João Silva", + email: "joao@example.com", + role: "user" + }, + { + full_name: "Maria Santos", + email: "maria@example.com", + role: "user" + }, + { + full_name: "Pedro Oliveira", + email: "pedro@example.com", + role: "user" + } +] + +puts "\n👥 Creating sample users..." + +sample_users.each do |user_data| + user = User.find_or_initialize_by(email: user_data[:email]) + + if user.new_record? + user.assign_attributes( + full_name: user_data[:full_name], + role: user_data[:role], + password: "password123", + password_confirmation: "password123" + ) + + if user.save + puts "✅ Created user: #{user.full_name} (#{user.email})" + else + puts "❌ Failed to create user #{user_data[:email]}:" + user.errors.full_messages.each do |error| + puts " - #{error}" + end + end + else + puts "ℹ️ User already exists: #{user_data[:email]}" + end +end + +puts "\n📊 Database summary:" +puts " Total users: #{User.count}" +puts " Admin users: #{User.admin.count}" +puts " Regular users: #{User.user.count}" + +puts "\n🎉 Seeding completed!" diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb From f59bc8ac0075b7b87efde48a3bb300bcb9aa5efc Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:51:07 -0300 Subject: [PATCH 03/20] feat: create User and Import models with business logic - User model with role management (admin, manager, user) - Email validation and full name presentation methods - Import model with status tracking and file attachment - Dashboard broadcaster concern for real-time updates - Application record base class and model associations - Application mailer for email functionality --- app/mailers/application_mailer.rb | 4 ++ app/models/application_record.rb | 3 + app/models/concerns/.keep | 0 app/models/concerns/dashboard_broadcaster.rb | 25 +++++++ app/models/import.rb | 68 ++++++++++++++++++++ app/models/user.rb | 65 +++++++++++++++++++ 6 files changed, 165 insertions(+) create mode 100644 app/mailers/application_mailer.rb create mode 100644 app/models/application_record.rb create mode 100644 app/models/concerns/.keep create mode 100644 app/models/concerns/dashboard_broadcaster.rb create mode 100644 app/models/import.rb create mode 100644 app/models/user.rb diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..3c34c8148 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +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..b63caeb8a --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/concerns/dashboard_broadcaster.rb b/app/models/concerns/dashboard_broadcaster.rb new file mode 100644 index 000000000..631f18b7c --- /dev/null +++ b/app/models/concerns/dashboard_broadcaster.rb @@ -0,0 +1,25 @@ +module DashboardBroadcaster + extend ActiveSupport::Concern + + included do + after_commit :broadcast_dashboard_update, on: [ :create, :update, :destroy ] + end + + private + + def broadcast_dashboard_update + # Broadcast updated statistics to admin dashboard + ActionCable.server.broadcast( + "dashboard_updates", + { + type: "stats_update", + stats: { + total_users: User.total_count, + admin_users: User.admin_count, + regular_users: User.user_count + }, + timestamp: Time.current.iso8601 + } + ) + end +end diff --git a/app/models/import.rb b/app/models/import.rb new file mode 100644 index 000000000..f6ba9b40e --- /dev/null +++ b/app/models/import.rb @@ -0,0 +1,68 @@ +class Import < ApplicationRecord + belongs_to :user + has_one_attached :file + + # Status enum + STATUSES = %w[pending processing completed failed].freeze + + validates :file_name, presence: true + validates :status, inclusion: { in: STATUSES } + validates :progress, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } + + scope :recent, -> { order(created_at: :desc) } + scope :by_status, ->(status) { where(status: status) if status.present? } + + # Status helpers + def pending? + status == 'pending' + end + + def processing? + status == 'processing' + end + + def completed? + status == 'completed' + end + + def failed? + status == 'failed' + end + + # Progress calculation + def calculate_progress + return 0 if total_rows.zero? + ((processed_rows.to_f / total_rows) * 100).round(2) + end + + def update_progress! + self.progress = calculate_progress + save! + end + + # Error handling + def add_error(error_message) + self.error_details = error_details.to_s + "\n#{Time.current}: #{error_message}" + save! + end + + def success_rate + return 0 if processed_rows.zero? + ((successful_rows.to_f / processed_rows) * 100).round(2) + end + + # Display helpers + def display_status + status.humanize + end + + def estimated_time_remaining + return nil unless processing? && processed_rows > 0 + + elapsed_time = Time.current - updated_at + avg_time_per_row = elapsed_time / processed_rows + remaining_rows = total_rows - processed_rows + + (remaining_rows * avg_time_per_row).seconds + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..204a914f3 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,65 @@ +class User < ApplicationRecord + include DashboardBroadcaster + + # Include default devise modules. Others available are: + # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable + devise :database_authenticatable, :registerable, + :recoverable, :rememberable, :validatable, :trackable + + # Active Storage for avatar image + has_one_attached :avatar_image + + # Validations + validates :full_name, presence: true, length: { minimum: 2, maximum: 100 } + validates :role, presence: true, inclusion: { in: %w[user admin] } + validates :avatar_url, format: { with: URI::DEFAULT_PARSER.make_regexp([ "http", "https" ]) }, allow_blank: true + + # Enums + enum :role, { user: "user", admin: "admin" } + + # Scopes + scope :admins, -> { where(role: "admin") } + scope :regular_users, -> { where(role: "user") } + + # Methods + def admin? + role == "admin" + end + + def display_name + full_name.presence || email + end + + def initials + return "??" if full_name.blank? + + full_name.split(" ") + .map { |word| word[0]&.upcase } + .compact + .first(2) + .join + end + + def avatar + if avatar_image.attached? + avatar_image + elsif avatar_url.present? + avatar_url + else + nil + end + end + + # Class methods + def self.total_count + count + end + + def self.admin_count + admins.count + end + + def self.user_count + regular_users.count + end +end From aa6ea34850f74ded387a0de85a07b4a3d99363f6 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:51:36 -0300 Subject: [PATCH 04/20] feat: configure Devise authentication system - Setup Devise initializer with security configurations - Configure authentication routes for users and admin - Add Devise localization files - Setup credentials encryption for secure configuration - Configure role-based route access control --- config/credentials.yml.enc | 1 + config/initializers/devise.rb | 313 ++++++++++++++++++++++++++++++++++ config/locales/devise.en.yml | 65 +++++++ config/routes.rb | 33 ++++ 4 files changed, 412 insertions(+) create mode 100644 config/credentials.yml.enc create mode 100644 config/initializers/devise.rb create mode 100644 config/locales/devise.en.yml create mode 100644 config/routes.rb diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 000000000..ef7fbf3ab --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +ifgLmHlLsUsIuLqz3B0fCAHN76bFRQmGX3WyGsIGp1DbwqjAmCkUAcSDynvD1bSPpygx4O0tKMHfczGCEBup0JNNv/H35scZQCPEVDyRFBHiOppTWoqf/Hp/kU/vycHFFn+p1c8GrG0bf6dht14cGGHiWyOSfMliTUVWeTwqmuUjKPFbynwpap8JukFC49DDjJ/mu0UM0v3/HES4MxLejR3FNr8Hc6q3DuxFbwJRlTnmjAT5c4BXOdsOl63HpVH24Z+V8ZlK7U3cccpgsC9kmKSQ2FA7PcZiRdl6H39hCnYYln98QawqyXDnPLThIwlm2qJvvIXJdwXBr9xKM5yPX9vvPUYHbdmpyNLiE36c6II9uKmJVtqxR5TdPCDpDTpfm3+doYP6mb/+pN7LojC2MbUTISgm3VxlvzwBhVbw2KdXDBLXT0h02+L6TEgNzXofkj3V3pRDvZFT2GarumOdD1l0WYPp1eqpG+haKEN7eM1dwCB+hSvJnu5f--KlJV7eGP5KbD/Rww--R2gvaFIVw5yJ+7AOOJ2d9Q== \ No newline at end of file diff --git a/config/initializers/devise.rb b/config/initializers/devise.rb new file mode 100644 index 000000000..14de78390 --- /dev/null +++ b/config/initializers/devise.rb @@ -0,0 +1,313 @@ +# 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 = '87e07ca0cbe93c05724a7ae1631036f08e677e7c8af060bb28630ec7d00dee6d815dcbf77ac6271c9472b16308782cf60f27441dd8b880b01a5717c6b04c2933' + + # ==> 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 = 'ActionMailer::Base' + + # ==> ORM configuration + # Load and configure the ORM. Supports :active_record (default) and + # :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 + # 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 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. + # 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 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 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 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 + + # 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 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 + # 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 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 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 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 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 = '4bcfa3e072bddad20362a22f0a8074b21dc080efb208b638d1acfc17d6fd6e226cc92eb86b99f2aed673780bcafe35c5fe6b786bab6541407d7ebeee76f579e5' + + # Send a notification to the original email when the user's email is changed. + # config.send_email_changed_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 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 = 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'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 + + # 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 column, and copied to email column 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 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 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. + # :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.reset_password_keys = [:email] + + # 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). + # 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 :iphone or :mobile, you + # should add them to the navigational formats lists. + # + # 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. 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.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 + # 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 + + # ==> 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 + # 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/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..aac062748 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,33 @@ +Rails.application.routes.draw do + devise_for :users + + # Root routes + root to: "home#index" + + # Admin routes + namespace :admin do + get "dashboard", to: "dashboard#index" + + resources :users do + member do + patch :toggle_role + end + end + + resources :imports, only: [ :index, :create, :show ] + end + + # User profile routes + get "profile", to: "users#show" + get "profile/edit", to: "users#edit" + patch "profile", to: "users#update" + delete "profile", to: "users#destroy" + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) + # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker +end From ecb54f7c593b1ab17c25d554e3e85aaa2ab103f0 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:52:00 -0300 Subject: [PATCH 05/20] feat: create controllers with authentication and authorization - Application controller with authentication and role-based access - Home controller for landing page and navigation - Users controller for profile management - Admin controllers for dashboard and user management - Admin imports controller for CSV functionality - Helper modules for view assistance and utilities --- app/controllers/admin/dashboard_controller.rb | 18 +++++ app/controllers/admin/imports_controller.rb | 64 ++++++++++++++++ app/controllers/admin/users_controller.rb | 76 +++++++++++++++++++ app/controllers/application_controller.rb | 38 ++++++++++ app/controllers/concerns/.keep | 0 app/controllers/home_controller.rb | 13 ++++ app/controllers/users_controller.rb | 44 +++++++++++ app/helpers/admin/dashboard_helper.rb | 2 + app/helpers/admin/imports_helper.rb | 2 + app/helpers/admin/users_helper.rb | 2 + app/helpers/application_helper.rb | 2 + app/helpers/home_helper.rb | 2 + app/helpers/users_helper.rb | 2 + 13 files changed, 265 insertions(+) create mode 100644 app/controllers/admin/dashboard_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/concerns/.keep create mode 100644 app/controllers/home_controller.rb create mode 100644 app/controllers/users_controller.rb create mode 100644 app/helpers/admin/dashboard_helper.rb create mode 100644 app/helpers/admin/imports_helper.rb create mode 100644 app/helpers/admin/users_helper.rb create mode 100644 app/helpers/application_helper.rb create mode 100644 app/helpers/home_helper.rb create mode 100644 app/helpers/users_helper.rb diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb new file mode 100644 index 000000000..352a3de86 --- /dev/null +++ b/app/controllers/admin/dashboard_controller.rb @@ -0,0 +1,18 @@ +class Admin::DashboardController < ApplicationController + before_action :ensure_admin! + + def index + result = DashboardStatsService.call(current_user) + + if result.success? + stats = result.data + @user_stats = stats[:users] + @import_stats = stats[:imports] + @activity_stats = stats[:activity] + @growth_stats = stats[:growth] + @recent_users = stats[:users][:recent] + else + redirect_to root_path, alert: result.error_messages.join(", ") + end + end +end diff --git a/app/controllers/admin/imports_controller.rb b/app/controllers/admin/imports_controller.rb new file mode 100644 index 000000000..99fb61274 --- /dev/null +++ b/app/controllers/admin/imports_controller.rb @@ -0,0 +1,64 @@ +class Admin::ImportsController < ApplicationController + before_action :ensure_admin! + before_action :set_import, only: [ :show ] + + def index + @imports = Import.includes(:user) + .recent + .page(params[:page]) + .per(10) + @pending_imports = Import.where(status: "pending").count + @processing_imports = Import.where(status: "processing").count + end + + def show + respond_to do |format| + format.html + format.json { render json: import_json } + end + end + + def create + @import = current_user.imports.build + + if params[:file].present? + @import.file.attach(params[:file]) + @import.file_name = params[:file].original_filename + + if @import.save + # Enqueue background job to process the import + UserImportJob.perform_later(@import) + + redirect_to admin_import_path(@import), + notice: "Import started successfully. Processing will begin shortly." + else + redirect_to admin_imports_path, + alert: "Import failed: #{@import.errors.full_messages.join(', ')}" + end + else + redirect_to admin_imports_path, alert: "Please select a file to import." + end + end + + private + + def set_import + @import = Import.find(params[:id]) + end + + def import_json + { + id: @import.id, + status: @import.status, + progress: @import.progress, + total_rows: @import.total_rows, + processed_rows: @import.processed_rows, + successful_rows: @import.successful_rows, + failed_rows: @import.failed_rows, + success_rate: @import.success_rate, + estimated_time_remaining: @import.estimated_time_remaining, + created_at: @import.created_at, + updated_at: @import.updated_at + } + end +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..c6592f063 --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,76 @@ +class Admin::UsersController < ApplicationController + before_action :ensure_admin! + before_action :set_user, only: [ :show, :edit, :update, :destroy, :toggle_role ] + + def index + @users = User.with_attached_avatar_image.order(:created_at) + @users = @users.where(role: params[:role]) if params[:role].present? + @users = @users.where("full_name ILIKE ? OR email ILIKE ?", "%#{params[:search]}%", "%#{params[:search]}%") if params[:search].present? + @users = @users.page(params[:page]).per(10) + end + + def show + end + + def new + @user = User.new + end + + def create + @user = User.new(user_params) + @user.password = SecureRandom.hex(8) if @user.password.blank? + + if @user.save + UserMailer.welcome_email(@user, @user.password).deliver_later if Rails.env.production? + redirect_to admin_user_path(@user), notice: "User was successfully created." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + user_update_params = user_params + user_update_params.delete(:password) if user_update_params[:password].blank? + + if @user.update(user_update_params) + redirect_to admin_user_path(@user), notice: "User was successfully updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + if @user == current_user + redirect_to admin_users_path, alert: "You cannot delete your own account." + return + end + + @user.destroy + redirect_to admin_users_path, notice: "User was successfully deleted." + end + + def toggle_role + new_role = @user.admin? ? "user" : "admin" + + if @user == current_user && new_role == "user" + redirect_to admin_users_path, alert: "You cannot remove admin access from your own account." + return + end + + @user.update(role: new_role) + redirect_to admin_users_path, notice: "User role updated to #{new_role.humanize}." + 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..3dffa2c39 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,38 @@ +class ApplicationController < ActionController::Base + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern + + # Devise configuration + before_action :authenticate_user! + before_action :configure_permitted_parameters, if: :devise_controller? + + # Redirect after sign in + def after_sign_in_path_for(resource) + if resource.admin? + admin_dashboard_path + else + profile_path + end + end + + # Redirect after sign out + def after_sign_out_path_for(resource_or_scope) + new_user_session_path + end + + protected + + def configure_permitted_parameters + devise_parameter_sanitizer.permit(:sign_up, keys: [ :full_name, :avatar_url ]) + devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_url, :avatar_image ]) + end + + # Authorization helpers + def ensure_admin! + redirect_to root_path, alert: "Access denied." unless current_user&.admin? + end + + def ensure_user_or_admin!(user) + redirect_to root_path, alert: "Access denied." unless current_user == user || current_user&.admin? + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 000000000..c2030bbac --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,13 @@ +class HomeController < ApplicationController + skip_before_action :authenticate_user!, only: [ :index ] + + def index + if user_signed_in? + if current_user.admin? + redirect_to admin_dashboard_path + else + redirect_to profile_path + end + end + end +end diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rb new file mode 100644 index 000000000..1ed12bb84 --- /dev/null +++ b/app/controllers/users_controller.rb @@ -0,0 +1,44 @@ +class UsersController < ApplicationController + before_action :set_user + before_action :ensure_user_or_admin! + + def show + end + + def edit + end + + def update + user_update_params = user_params + user_update_params.delete(:password) if user_update_params[:password].blank? + + if @user.update(user_update_params) + redirect_to profile_path, notice: "Profile was successfully updated." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + if @user == current_user + @user.destroy + redirect_to root_path, notice: "Your account has been successfully deleted." + else + redirect_to profile_path, alert: "You can only delete your own account." + end + end + + private + + def set_user + @user = current_user + end + + def ensure_user_or_admin! + redirect_to root_path, alert: "Access denied." unless current_user == @user || current_user&.admin? + end + + def user_params + params.require(:user).permit(:full_name, :email, :password, :password_confirmation, :avatar_url, :avatar_image) + end +end diff --git a/app/helpers/admin/dashboard_helper.rb b/app/helpers/admin/dashboard_helper.rb new file mode 100644 index 000000000..4052b7c4b --- /dev/null +++ b/app/helpers/admin/dashboard_helper.rb @@ -0,0 +1,2 @@ +module Admin::DashboardHelper +end diff --git a/app/helpers/admin/imports_helper.rb b/app/helpers/admin/imports_helper.rb new file mode 100644 index 000000000..29ba6a260 --- /dev/null +++ b/app/helpers/admin/imports_helper.rb @@ -0,0 +1,2 @@ +module Admin::ImportsHelper +end diff --git a/app/helpers/admin/users_helper.rb b/app/helpers/admin/users_helper.rb new file mode 100644 index 000000000..5995c2aa8 --- /dev/null +++ b/app/helpers/admin/users_helper.rb @@ -0,0 +1,2 @@ +module Admin::UsersHelper +end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 000000000..de6be7945 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/helpers/home_helper.rb b/app/helpers/home_helper.rb new file mode 100644 index 000000000..23de56ac6 --- /dev/null +++ b/app/helpers/home_helper.rb @@ -0,0 +1,2 @@ +module HomeHelper +end diff --git a/app/helpers/users_helper.rb b/app/helpers/users_helper.rb new file mode 100644 index 000000000..2310a240d --- /dev/null +++ b/app/helpers/users_helper.rb @@ -0,0 +1,2 @@ +module UsersHelper +end From 55b287c13c216d186e1e6de1869f8fb417243c02 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:52:26 -0300 Subject: [PATCH 06/20] feat: implement service layer for business logic - Application service base class with error handling - Dashboard stats service for real-time metrics calculation - User management service for CRUD operations - User search service with filtering and pagination - Separation of concerns between controllers and business logic --- app/services/application_service.rb | 60 ++++++++++++++++ app/services/dashboard_stats_service.rb | 80 ++++++++++++++++++++++ app/services/user_management_service.rb | 68 ++++++++++++++++++ app/services/user_search_service.rb | 91 +++++++++++++++++++++++++ 4 files changed, 299 insertions(+) create mode 100644 app/services/application_service.rb create mode 100644 app/services/dashboard_stats_service.rb create mode 100644 app/services/user_management_service.rb create mode 100644 app/services/user_search_service.rb diff --git a/app/services/application_service.rb b/app/services/application_service.rb new file mode 100644 index 000000000..4a606b192 --- /dev/null +++ b/app/services/application_service.rb @@ -0,0 +1,60 @@ +# Base service class following Command pattern +class ApplicationService + class << self + # Call the service with given arguments + def call(*args, **kwargs) + new(*args, **kwargs).call + end + end + + # Override in subclasses + def call + raise NotImplementedError, "Subclasses must implement the call method" + end + + private + + # Success result + def success(data = nil) + ServiceResult.new(success: true, data: data) + end + + # Error result + def failure(errors) + ServiceResult.new(success: false, errors: errors) + end +end + +# Service result object +class ServiceResult + attr_reader :data, :errors + + def initialize(success:, data: nil, errors: nil) + @success = success + @data = data + @errors = errors || [] + end + + def success? + @success + end + + def failure? + !@success + end + + def error_messages + return [] if errors.blank? + + case errors + when String + [ errors ] + when Array + errors + when ActiveModel::Errors + errors.full_messages + else + [ errors.to_s ] + end + end +end diff --git a/app/services/dashboard_stats_service.rb b/app/services/dashboard_stats_service.rb new file mode 100644 index 000000000..19ce4f08c --- /dev/null +++ b/app/services/dashboard_stats_service.rb @@ -0,0 +1,80 @@ +class DashboardStatsService < ApplicationService + def initialize(current_user) + @current_user = current_user + end + + def call + return failure("Unauthorized access") unless can_access_dashboard? + + stats = calculate_dashboard_stats + success(stats) + end + + private + + attr_reader :current_user + + def can_access_dashboard? + current_user&.admin? + end + + def calculate_dashboard_stats + { + users: user_statistics, + imports: import_statistics, + activity: activity_statistics, + growth: growth_statistics + } + end + + def user_statistics + { + total: User.count, + admins: User.where(role: "admin").count, + regular_users: User.where(role: "user").count, + recent: User.with_attached_avatar_image.order(created_at: :desc).limit(5), + created_today: User.where(created_at: Date.current.beginning_of_day..Date.current.end_of_day).count, + created_this_week: User.where(created_at: 1.week.ago..Time.current).count, + created_this_month: User.where(created_at: 1.month.ago..Time.current).count + } + end + + def import_statistics + { + total: Import.count, + pending: Import.where(status: "pending").count, + processing: Import.where(status: "processing").count, + completed: Import.where(status: "completed").count, + failed: Import.where(status: "failed").count, + recent: Import.order(created_at: :desc).limit(5) + } + end + + def activity_statistics + { + users_created_today: User.where(created_at: Date.current.beginning_of_day..Date.current.end_of_day).count, + imports_started_today: Import.where(created_at: Date.current.beginning_of_day..Date.current.end_of_day).count, + last_activity: [ + User.maximum(:updated_at), + Import.maximum(:updated_at) + ].compact.max + } + end + + def growth_statistics + # Calculate user growth over the last 30 days + growth_data = (0..29).map do |days_ago| + date = days_ago.days.ago.to_date + { + date: date, + users_created: User.where(created_at: date.beginning_of_day..date.end_of_day).count + } + end.reverse + + { + daily_growth: growth_data, + total_growth_30_days: User.where(created_at: 30.days.ago..Time.current).count, + average_daily_growth: growth_data.sum { |d| d[:users_created] } / 30.0 + } + end +end diff --git a/app/services/user_management_service.rb b/app/services/user_management_service.rb new file mode 100644 index 000000000..e9cce4518 --- /dev/null +++ b/app/services/user_management_service.rb @@ -0,0 +1,68 @@ +class UserManagementService < ApplicationService + def initialize(user_params, current_user) + @user_params = user_params + @current_user = current_user + end + + def call + if can_perform_action? + create_or_update_user + else + failure("You do not have permission to perform this action") + end + end + + private + + attr_reader :user_params, :current_user + + def can_perform_action? + current_user&.admin? + end + + def create_or_update_user + if user_params[:id].present? + update_existing_user + else + create_new_user + end + end + + def update_existing_user + user = User.find(user_params[:id]) + + if user.update(filtered_params) + success(user) + else + failure(user.errors) + end + rescue ActiveRecord::RecordNotFound + failure("User not found") + end + + def create_new_user + # Generate random password for new users + params_with_password = filtered_params.merge( + password: generate_secure_password, + password_confirmation: nil + ) + + user = User.new(params_with_password) + + if user.save + # Send welcome email with password + UserMailer.welcome_email(user, params_with_password[:password]).deliver_later + success(user) + else + failure(user.errors) + end + end + + def filtered_params + user_params.permit(:full_name, :email, :role, :avatar_url, :avatar_image) + end + + def generate_secure_password + SecureRandom.alphanumeric(12) + end +end diff --git a/app/services/user_search_service.rb b/app/services/user_search_service.rb new file mode 100644 index 000000000..be0c362dd --- /dev/null +++ b/app/services/user_search_service.rb @@ -0,0 +1,91 @@ +class UserSearchService < ApplicationService + def initialize(search_params, current_user) + @search_params = search_params + @current_user = current_user + end + + def call + return failure("Unauthorized access") unless can_search? + + users = build_search_query + success({ + users: users, + total_count: users.count, + filters_applied: filters_applied? + }) + end + + private + + attr_reader :search_params, :current_user + + def can_search? + current_user&.admin? + end + + def build_search_query + query = User.all + query = apply_search_filter(query) + query = apply_role_filter(query) + query = apply_date_filter(query) + query = apply_sorting(query) + query + end + + def apply_search_filter(query) + return query if search_params[:search].blank? + + search_term = "%#{search_params[:search].strip}%" + query.where( + "full_name ILIKE ? OR email ILIKE ?", + search_term, search_term + ) + end + + def apply_role_filter(query) + return query if search_params[:role].blank? + + query.where(role: search_params[:role]) + end + + def apply_date_filter(query) + return query unless search_params[:date_from].present? || search_params[:date_to].present? + + if search_params[:date_from].present? + query = query.where("created_at >= ?", Date.parse(search_params[:date_from])) + end + + if search_params[:date_to].present? + query = query.where("created_at <= ?", Date.parse(search_params[:date_to]).end_of_day) + end + + query + rescue Date::Error + query + end + + def apply_sorting(query) + sort_by = search_params[:sort_by]&.to_s + sort_direction = search_params[:sort_direction]&.to_s + + case sort_by + when "name" + query.order("full_name #{sort_direction == 'desc' ? 'DESC' : 'ASC'}") + when "email" + query.order("email #{sort_direction == 'desc' ? 'DESC' : 'ASC'}") + when "role" + query.order("role #{sort_direction == 'desc' ? 'DESC' : 'ASC'}") + when "created_at" + query.order("created_at #{sort_direction == 'desc' ? 'DESC' : 'ASC'}") + else + query.order(created_at: :desc) + end + end + + def filters_applied? + search_params[:search].present? || + search_params[:role].present? || + search_params[:date_from].present? || + search_params[:date_to].present? + end +end From f0278d2202c3e91e673a5c01f4755cafaf56c69c Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:53:15 -0300 Subject: [PATCH 07/20] feat: implement CSV user import with real-time progress - Background job for processing CSV imports asynchronously - Real-time progress tracking via Action Cable channels - Dashboard channel for live metrics updates - Import progress channel for upload status - Queue and cable configuration for background processing --- app/channels/application_cable/channel.rb | 4 + app/channels/application_cable/connection.rb | 20 +++ app/channels/dashboard_channel.rb | 15 ++ app/channels/import_progress_channel.rb | 16 ++ app/jobs/application_job.rb | 7 + app/jobs/user_import_job.rb | 155 +++++++++++++++++++ config/cable.yml | 17 ++ config/queue.yml | 18 +++ config/recurring.yml | 15 ++ 9 files changed, 267 insertions(+) create mode 100644 app/channels/application_cable/channel.rb create mode 100644 app/channels/application_cable/connection.rb create mode 100644 app/channels/dashboard_channel.rb create mode 100644 app/channels/import_progress_channel.rb create mode 100644 app/jobs/application_job.rb create mode 100644 app/jobs/user_import_job.rb create mode 100644 config/cable.yml create mode 100644 config/queue.yml create mode 100644 config/recurring.yml diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..d67269728 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +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..db248fcfc --- /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 + # Try to find user from session + if verified_user = env["warden"]&.user + verified_user + else + reject_unauthorized_connection + end + end + end +end diff --git a/app/channels/dashboard_channel.rb b/app/channels/dashboard_channel.rb new file mode 100644 index 000000000..fa94045dc --- /dev/null +++ b/app/channels/dashboard_channel.rb @@ -0,0 +1,15 @@ +class DashboardChannel < ApplicationCable::Channel + def subscribed + # Only allow admin users to subscribe to dashboard updates + if current_user&.admin? + stream_from "dashboard_updates" + else + reject + end + end + + def unsubscribed + # Any cleanup needed when channel is unsubscribed + stop_all_streams + end +end diff --git a/app/channels/import_progress_channel.rb b/app/channels/import_progress_channel.rb new file mode 100644 index 000000000..1a7d59a5f --- /dev/null +++ b/app/channels/import_progress_channel.rb @@ -0,0 +1,16 @@ +class ImportProgressChannel < ApplicationCable::Channel + def subscribed + return reject unless current_user&.admin? + return reject unless params[:import_id].present? + + import = Import.find_by(id: params[:import_id]) + return reject unless import + + stream_from "import_#{import.id}" + end + + def unsubscribed + # Any cleanup needed when channel is unsubscribed + stop_all_streams + end +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..d394c3d10 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +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..35a231cec --- /dev/null +++ b/app/jobs/user_import_job.rb @@ -0,0 +1,155 @@ +class UserImportJob < ApplicationJob + queue_as :default + + def perform(import) + import.update!(status: "processing", processed_rows: 0, successful_rows: 0, failed_rows: 0) + + begin + process_import(import) + import.update!(status: "completed") + rescue StandardError => e + import.update!(status: "failed") + import.add_error("Import failed: #{e.message}") + raise e + end + end + + private + + def process_import(import) + file_path = download_file(import) + + # Use Roo to parse the spreadsheet + spreadsheet = open_spreadsheet(file_path, import.file_name) + headers = spreadsheet.row(1) + + validate_headers(headers, import) + + total_rows = spreadsheet.last_row - 1 # Exclude header row + import.update!(total_rows: total_rows) + + (2..spreadsheet.last_row).each_with_index do |row_num, index| + row = spreadsheet.row(row_num) + process_row(row, headers, import) + + # Update progress every 10 rows or on last row + if (index + 1) % 10 == 0 || (index + 1) == total_rows + import.update_progress! + # Broadcast progress via ActionCable + broadcast_progress(import) + end + end + + # Clean up temporary file + File.delete(file_path) if File.exist?(file_path) + end + + def download_file(import) + temp_file = Tempfile.new([ import.file_name, File.extname(import.file_name) ]) + temp_file.binmode + temp_file.write(import.file.download) + temp_file.close + temp_file.path + end + + def open_spreadsheet(file_path, filename) + case File.extname(filename).downcase + when ".csv" + Roo::CSV.new(file_path) + when ".xls" + Roo::Excel.new(file_path) + when ".xlsx" + Roo::Excelx.new(file_path) + else + raise "Unknown file type: #{filename}" + end + end + + def validate_headers(headers, import) + required_headers = [ "full_name", "email" ] + optional_headers = [ "role", "avatar_url" ] + + missing_headers = required_headers - headers.map(&:to_s).map(&:downcase) + + if missing_headers.any? + raise "Missing required headers: #{missing_headers.join(', ')}" + end + end + + def process_row(row, headers, import) + begin + user_data = build_user_data(row, headers) + + user = User.find_by(email: user_data[:email]) + + if user + # Update existing user + user.update!(user_data.except(:email)) + import.increment!(:successful_rows) + else + # Create new user + user = User.create!(user_data.merge(password: generate_password)) + import.increment!(:successful_rows) + end + + import.increment!(:processed_rows) + + rescue StandardError => e + import.increment!(:failed_rows) + import.increment!(:processed_rows) + import.add_error("Row #{import.processed_rows}: #{e.message}") + end + end + + def build_user_data(row, headers) + data = {} + + headers.each_with_index do |header, index| + value = row[index] + next if value.blank? + + case header.to_s.downcase + when "full_name" + data[:full_name] = value.to_s.strip + when "email" + data[:email] = value.to_s.strip.downcase + when "role" + role = value.to_s.strip.downcase + data[:role] = %w[admin user].include?(role) ? role : "user" + when "avatar_url" + data[:avatar_url] = value.to_s.strip if valid_url?(value.to_s.strip) + end + end + + data + end + + def generate_password + SecureRandom.alphanumeric(12) + end + + def valid_url?(url) + uri = URI.parse(url) + %w[http https].include?(uri.scheme) + rescue URI::InvalidURIError + false + end + + def broadcast_progress(import) + ActionCable.server.broadcast( + "import_#{import.id}", + { + type: "progress_update", + import: { + id: import.id, + progress: import.progress, + processed_rows: import.processed_rows, + total_rows: import.total_rows, + successful_rows: import.successful_rows, + failed_rows: import.failed_rows, + status: import.status + } + } + ) + end +end diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..b9adc5aa3 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,17 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/queue.yml b/config/queue.yml new file mode 100644 index 000000000..9eace59c4 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 0.1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 000000000..b4207f9b0 --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,15 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 From 04cc1d68f29e1487581eaca10deed6df727a13a3 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:53:50 -0300 Subject: [PATCH 08/20] feat: create admin dashboard and management views - Admin dashboard with real-time metrics and statistics - User management views with CRUD operations - Import management views with progress tracking - Responsive layout with Bootstrap navigation - Shared components for flash messages and navbar --- app/views/admin/dashboard/index.html.erb | 249 +++++++++++++ app/views/admin/imports/create.html.erb | 336 +++++++++++++++++ app/views/admin/imports/index.html.erb | 219 +++++++++++ app/views/admin/imports/show.html.erb | 261 +++++++++++++ app/views/admin/users/edit.html.erb | 334 +++++++++++++++++ app/views/admin/users/index.html.erb | 208 +++++++++++ app/views/admin/users/new.html.erb | 435 ++++++++++++++++++++++ app/views/admin/users/show.html.erb | 224 +++++++++++ app/views/layouts/application.html.erb | 44 +++ app/views/layouts/mailer.html.erb | 13 + app/views/layouts/mailer.text.erb | 1 + app/views/shared/_flash_messages.html.erb | 31 ++ app/views/shared/_footer.html.erb | 20 + app/views/shared/_navbar.html.erb | 63 ++++ 14 files changed, 2438 insertions(+) create mode 100644 app/views/admin/dashboard/index.html.erb create mode 100644 app/views/admin/imports/create.html.erb create mode 100644 app/views/admin/imports/index.html.erb create mode 100644 app/views/admin/imports/show.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/admin/users/show.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/shared/_flash_messages.html.erb create mode 100644 app/views/shared/_footer.html.erb create mode 100644 app/views/shared/_navbar.html.erb diff --git a/app/views/admin/dashboard/index.html.erb b/app/views/admin/dashboard/index.html.erb new file mode 100644 index 000000000..91df88931 --- /dev/null +++ b/app/views/admin/dashboard/index.html.erb @@ -0,0 +1,249 @@ +<% content_for :title, "Admin Dashboard" %> + +
+
+
+
+
+

Admin Dashboard

+

+ Welcome back, <%= current_user.display_name %>! + Live +

+
+
+ <%= link_to admin_users_path, class: "btn btn-primary" do %> + Manage Users + <% end %> + <%= link_to admin_imports_path, class: "btn btn-outline-primary ms-2" do %> + Import Users + <% end %> +
+
+
+
+ +
+ +
+
+
+
+
+
+ +
+
+

<%= @user_stats[:total] %>

+

Total Users

+
+
+
+
+ +
+
+
+
+ +
+
+

<%= @user_stats[:admins] %>

+

Admin Users

+
+
+
+
+ +
+
+
+
+ +
+
+

<%= @user_stats[:regular_users] %>

+

Regular Users

+
+
+
+
+
+
+ + +
+
+ +
+
+
+
+ Recent Users +
+
+
+ <% if @recent_users.any? %> +
+ + + + + + + + + + + + <% @recent_users.each do |user| %> + + + + + + + + <% end %> + +
AvatarUserRoleJoinedActions
+ <% if user.avatar %> + <%= image_tag user.avatar, class: "user-avatar", alt: user.display_name %> + <% else %> +
+ +
+ <% end %> +
+ + <%= user.role.humanize %> + + + + <%= time_ago_in_words(user.created_at) %> ago + + + <%= link_to admin_user_path(user), class: "btn btn-sm btn-outline-primary" do %> + + <% end %> + <%= link_to edit_admin_user_path(user), class: "btn btn-sm btn-outline-secondary" do %> + + <% end %> +
+
+
+ <%= link_to "View All Users", admin_users_path, class: "btn btn-primary" %> +
+ <% else %> +
+ +

No users yet

+

Users will appear here once they register.

+
+ <% end %> +
+
+
+ + +
+
+
+
+ Quick Actions +
+
+
+
+ <%= link_to admin_users_path, class: "btn btn-outline-primary" do %> + View All Users + <% end %> + + <%= link_to new_admin_user_path, class: "btn btn-outline-success" do %> + Add New User + <% end %> + + <%= link_to admin_imports_path, class: "btn btn-outline-info" do %> + Import Users + <% end %> + + <%= link_to admin_users_path(role: 'admin'), class: "btn btn-outline-warning" do %> + View Admins + <% end %> +
+
+
+ + +
+
+
+ System Information +
+
+
+
+
+
+ +
+
Rails
+ <%= Rails.version %> +
+
+
+ +
+
Ruby
+ <%= RUBY_VERSION %> +
+
+
+
+
+
+
+
+
+ + diff --git a/app/views/admin/imports/create.html.erb b/app/views/admin/imports/create.html.erb new file mode 100644 index 000000000..20177bcd6 --- /dev/null +++ b/app/views/admin/imports/create.html.erb @@ -0,0 +1,336 @@ +<% content_for :title, "Import Started" %> + +
+
+
+ <% if @import&.persisted? %> + +
+
+
+ +
+ +

Import Started Successfully

+

+ Your file "<%= @import.file_name %>" has been uploaded and is now being processed. +

+ +
+
+
+
+
+
<%= @import.total_rows %>
+ Total Rows +
+
+
+ <%= @import.status.humanize %> +
+ Current Status +
+
+
+ <%= time_ago_in_words(@import.created_at) %> ago +
+ Started +
+
+
+
+
+ +
+ <%= link_to admin_import_path(@import), class: "btn btn-primary" do %> + View Progress + <% end %> + + <%= link_to admin_imports_path, class: "btn btn-outline-secondary" do %> + All Imports + <% end %> + + <%= link_to admin_users_path, class: "btn btn-outline-success" do %> + Manage Users + <% end %> +
+
+
+ + +
+
+
+ What Happens Next? +
+
+
+
+
+
+ +
+
+
File Uploaded
+

Your file has been successfully uploaded and validated.

+
+
+ +
+
+ +
+
+
Processing Rows
+

Each row is being processed and new users are being created.

+
+
+ +
+
+ +
+
+
Notifications Sent
+

Welcome emails will be sent to newly created users.

+
+
+ +
+
+ +
+
+
Import Complete
+

You'll receive a summary of the import results.

+
+
+
+
+
+ + +
+
+
+ Live Progress Updates +
+
+
+
+ + Real-time Updates: This page will automatically update as your import progresses. +
+ +
+
+ Current Progress + + <%= @import.processed_rows %> / <%= @import.total_rows %> rows + +
+ +
+
+ <%= @import.progress.round(1) %>% +
+
+ +
+ + Status: <%= @import.status.humanize %> + + + <%= @import.success_rate.round(1) %>% success rate + +
+
+
+
+ + <% else %> + +
+
+
+ +
+ +

Import Failed to Start

+

+ There was an error processing your file. Please check the requirements and try again. +

+ + <% if @import&.errors&.any? %> +
+
Errors:
+
    + <% @import.errors.full_messages.each do |error| %> +
  • <%= error %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= link_to admin_imports_path, class: "btn btn-primary" do %> + Try Again + <% end %> + + <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + Manage Users + <% end %> +
+
+
+ + +
+
+
+ Troubleshooting +
+
+
+
Common Issues:
+
    +
  • File Format: Make sure your file is in CSV, XLS, or XLSX format
  • +
  • File Size: Files must be under 10MB in size
  • +
  • Required Columns: Ensure your file has 'full_name' and 'email' columns
  • +
  • Email Format: All email addresses must be valid
  • +
  • Unique Emails: Email addresses must be unique in your file
  • +
+ +
+ + Need Help? Check our documentation or contact support for assistance with file formatting. +
+
+
+ <% end %> +
+
+
+ +<% if @import&.persisted? %> + +<% 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..d80a3cac9 --- /dev/null +++ b/app/views/admin/imports/index.html.erb @@ -0,0 +1,219 @@ +<% content_for :title, "User Imports" %> + +
+
+
+

User Imports

+

Manage user data imports from spreadsheets

+
+ +
+ + +
+
+
+
+
+ +
+
+

<%= @pending_imports %>

+

Pending Imports

+
+
+
+
+
+
+
+
+ +
+
+

<%= @processing_imports %>

+

Processing

+
+
+
+
+
+
+
+
+ +
+
+

<%= @imports.total_count %>

+

Total Imports

+
+
+
+
+
+ + +
+
+
+ Import History +
+
+
+ <% if @imports.any? %> +
+ + + + + + + + + + + + + + + <% @imports.each do |import| %> + + + + + + + + + + + <% end %> + +
File NameStatusProgressRowsSuccess RateStarted ByCreatedActions
+ + <%= import.file_name %> + + <% case import.status %> + <% when 'pending' %> + + Pending + + <% when 'processing' %> + + Processing + + <% when 'completed' %> + + Completed + + <% when 'failed' %> + + Failed + + <% end %> + + <% if import.processing? %> +
+
+ <%= import.progress.round(1) %>% +
+
+ <% else %> + <%= import.progress.round(1) %>% + <% end %> +
+ + <%= import.processed_rows %>/<%= import.total_rows %> + + + <% if import.processed_rows > 0 %> + + <%= import.success_rate.round(1) %>% + + <% else %> + - + <% end %> + + + <%= import.user.display_name %> + + + + <%= time_ago_in_words(import.created_at) %> ago + + + <%= link_to admin_import_path(import), + class: "btn btn-sm btn-outline-primary", + title: "View Details" do %> + + <% end %> +
+
+ + <%= paginate @imports if respond_to?(:paginate) %> + <% else %> +
+ +

No imports yet

+

Upload a CSV or Excel file to start importing users.

+ +
+ <% 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..f45b8279a --- /dev/null +++ b/app/views/admin/imports/show.html.erb @@ -0,0 +1,261 @@ +<% content_for :title, "Import Details - #{@import.file_name}" %> + +
+
+
+

Import Details

+

+ + <%= @import.file_name %> +

+
+ <%= link_to admin_imports_path, class: "btn btn-outline-secondary" do %> + Back to Imports + <% end %> +
+ +
+ +
+
+
+
+
+ Import Progress +
+ <% if @import.processing? %> + Live Updates + <% end %> +
+
+
+ +
+ <% case @import.status %> + <% when 'pending' %> + + Waiting to Start + + <% when 'processing' %> + + Processing + + <% when 'completed' %> + + Completed Successfully + + <% when 'failed' %> + + Failed + + <% end %> +
+ + +
+
+ + <%= @import.processed_rows %> of <%= @import.total_rows %> rows processed + + + <%= @import.progress.round(1) %>% + +
+
+
+ <%= @import.progress.round(1) %>% +
+
+
+ + +
+
+
+

<%= @import.total_rows %>

+ Total Rows +
+
+
+
+

<%= @import.successful_rows %>

+ Successful +
+
+
+
+

<%= @import.failed_rows %>

+ Failed +
+
+
+
+

+ <%= @import.success_rate.round(1) %>% +

+ Success Rate +
+
+
+ + + <% if @import.processing? && @import.estimated_time_remaining %> +
+ + + Estimated time remaining: + + <%= distance_of_time_in_words(@import.estimated_time_remaining) %> + + +
+ <% end %> +
+
+
+ + +
+
+
+
+ Import Details +
+
+
+
+ +

<%= @import.file_name %>

+
+ +
+ +

<%= @import.user.display_name %>

+
+ +
+ +

+ <%= @import.created_at.strftime("%B %d, %Y at %I:%M %p") %> +

+
+ + <% if @import.completed? || @import.failed? %> +
+ +

+ <%= @import.updated_at.strftime("%B %d, %Y at %I:%M %p") %> +

+
+ +
+ +

+ <%= distance_of_time_in_words(@import.created_at, @import.updated_at) %> +

+
+ <% end %> +
+
+ + +
+
+
+ Actions +
+
+
+
+ <% if @import.file.attached? %> + <%= link_to @import.file, + class: "btn btn-outline-primary", + download: @import.file_name do %> + Download Original File + <% end %> + <% end %> + + <%= link_to admin_users_path, class: "btn btn-outline-success" do %> + View Users + <% end %> + + <%= link_to admin_imports_path, class: "btn btn-outline-info" do %> + All Imports + <% end %> +
+
+
+
+
+ + + <% if @import.error_details.present? %> +
+
+
+ Error Details +
+
+
+
<%= @import.error_details %>
+
+
+ <% end %> +
+ +<% if @import.processing? %> + +<% 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..c60924952 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,334 @@ +<% content_for :title, "Edit User - #{@user.display_name}" %> + +
+ +
+
+

Edit User

+

Update user information and settings

+
+
+ <%= link_to admin_user_path(@user), class: "btn btn-outline-primary" do %> + View User + <% end %> + <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + Back to Users + <% end %> +
+
+ +
+ +
+
+
+
+ Current Profile +
+
+
+ <% if @user.avatar %> + <%= image_tag @user.avatar, class: "user-avatar mx-auto d-block mb-3", alt: @user.display_name %> + <% else %> +
+ <%= @user.initials %> +
+ <% end %> + + +
+
+ + +
+
+
+ Account Information +
+
+
+
+ Member since:
+ <%= @user.created_at.strftime("%B %d, %Y") %> +
+
+ Last sign in:
+ + <% if @user.current_sign_in_at %> + <%= time_ago_in_words(@user.current_sign_in_at) %> ago + <% else %> + Never signed in + <% end %> + +
+
+ Sign in count:
+ <%= @user.sign_in_count || 0 %> times +
+
+
+
+ + +
+ <%= form_with model: [:admin, @user], local: true, html: { + multipart: true, + class: "needs-validation", + novalidate: true, + id: "edit-user-form" + } do |form| %> + + +
+
+
+ Personal Information +
+
+
+
+
+ <%= form.label :full_name, class: "form-label required" %> + <%= form.text_field :full_name, + class: "form-control #{'is-invalid' if @user.errors[:full_name].present?}", + placeholder: "Enter full name", + required: true %> + <% if @user.errors[:full_name].present? %> +
+ <%= @user.errors[:full_name].first %> +
+ <% else %> +
User's full name as it will appear throughout the system.
+ <% end %> +
+ +
+ <%= form.label :email, class: "form-label required" %> + <%= form.email_field :email, + class: "form-control #{'is-invalid' if @user.errors[:email].present?}", + placeholder: "Enter email address", + required: true %> + <% if @user.errors[:email].present? %> +
+ <%= @user.errors[:email].first %> +
+ <% else %> +
Must be a valid email address.
+ <% end %> +
+
+ +
+
+ <%= form.label :role, class: "form-label required" %> + <%= form.select :role, + options_for_select([ + ['Regular User', 'user', { 'data-description': 'Standard user with basic permissions' }], + ['Administrator', 'admin', { 'data-description': 'Full system access and user management' }] + ], @user.role), + {}, + { + class: "form-select #{'is-invalid' if @user.errors[:role].present?}", + id: "user_role" + } %> + <% if @user.errors[:role].present? %> +
+ <%= @user.errors[:role].first %> +
+ <% else %> +
+ Select the appropriate access level for this user. +
+ <% end %> +
+ +
+ <%= form.label :avatar, "Profile Picture", class: "form-label" %> + <%= form.file_field :avatar, + class: "form-control #{'is-invalid' if @user.errors[:avatar].present?}", + accept: "image/*", + id: "avatar-upload" %> + <% if @user.errors[:avatar].present? %> +
+ <%= @user.errors[:avatar].first %> +
+ <% else %> +
+ Upload a new profile picture (JPG, PNG, or GIF). Max size: 5MB. +
+ <% end %> +
+
+
+
+ + +
+
+
+ Password Settings +
+
+
+ + +
+
+ <%= form.label :password, "New Password", class: "form-label" %> + <%= form.password_field :password, + class: "form-control #{'is-invalid' if @user.errors[:password].present?}", + placeholder: "Enter new password", + autocomplete: "new-password", + id: "password-field" %> + <% if @user.errors[:password].present? %> +
+ <%= @user.errors[:password].first %> +
+ <% else %> +
+ Password must be at least 6 characters long. +
+ <% end %> +
+ +
+ <%= form.label :password_confirmation, "Confirm Password", class: "form-label" %> + <%= form.password_field :password_confirmation, + class: "form-control #{'is-invalid' if @user.errors[:password_confirmation].present?}", + placeholder: "Confirm new password", + autocomplete: "new-password", + id: "password-confirmation-field" %> + <% if @user.errors[:password_confirmation].present? %> +
+ <%= @user.errors[:password_confirmation].first %> +
+ <% else %> +
+ Re-enter the password to confirm. +
+ <% end %> +
+
+
+
+ + + <% if @user == current_user %> + + <% end %> + + +
+
+
+
+ + Last updated: <%= time_ago_in_words(@user.updated_at) %> ago +
+ +
+ <%= link_to admin_user_path(@user), class: "btn btn-outline-secondary" do %> + Cancel + <% end %> + + <%= form.submit "Update User", + class: "btn btn-primary", + data: { + confirm: (@user == current_user ? "Are you sure you want to update your own profile?" : nil) + } do %> + Update User + <% end %> +
+
+
+
+ <% end %> +
+
+
+ + + diff --git a/app/views/admin/users/index.html.erb b/app/views/admin/users/index.html.erb new file mode 100644 index 000000000..7a198456d --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,208 @@ +<% content_for :title, "User Management" %> + +
+ +
+
+

User Management

+

Manage all users in the system

+
+ <%= link_to new_admin_user_path, class: "btn btn-primary" do %> + Add New User + <% end %> +
+ + +
+
+ <%= form_with url: admin_users_path, method: :get, local: true, class: "row g-3" do |f| %> +
+ <%= f.text_field :search, + placeholder: "Search by name or email...", + value: params[:search], + class: "form-control" %> +
+
+ <%= f.select :role, + options_for_select([ + ['All Roles', ''], + ['Admin Users', 'admin'], + ['Regular Users', 'user'] + ], params[:role]), + {}, + { class: "form-select" } %> +
+
+ <%= f.select :sort_by, + options_for_select([ + ['Sort by...', ''], + ['Name', 'name'], + ['Email', 'email'], + ['Role', 'role'], + ['Created Date', 'created_at'] + ], params[:sort_by]), + {}, + { class: "form-select" } %> +
+
+
+ <%= f.submit "Search", class: "btn btn-outline-primary" %> + <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + + <% end %> +
+
+ <% end %> +
+
+ + +
+
+
+
+ + Users (<%= @users.total_count %>) +
+
+ <%= link_to admin_imports_path, class: "btn btn-sm btn-outline-info" do %> + Import + <% end %> + <%= link_to admin_users_path(format: :csv), class: "btn btn-sm btn-outline-success" do %> + Export + <% end %> +
+
+
+
+ <% if @users.any? %> +
+ + + + + + + + + + + + + <% @users.each do |user| %> + + + + + + + + + <% end %> + +
AvatarUserRoleStatusJoinedActions
+ <% if user.avatar %> + <%= image_tag user.avatar, class: "user-avatar", alt: user.display_name %> + <% else %> +
+ <%= user.initials %> +
+ <% end %> +
+ <% if user.admin? %> + + Admin + + <% else %> + + User + + <% end %> + + <% if user.current_sign_in_at.present? %> + <% if user.current_sign_in_at > 30.days.ago %> + Active + <% else %> + Inactive + <% end %> + <% else %> + Never logged in + <% end %> + + + <%= time_ago_in_words(user.created_at) %> ago + + + +
+
+ + + + <% else %> +
+ +

No users found

+ <% if params[:search].present? || params[:role].present? %> +

Try adjusting your search criteria

+ <%= link_to "Clear filters", admin_users_path, class: "btn btn-outline-primary" %> + <% else %> +

Start by adding your first user

+ <%= link_to "Add New User", new_admin_user_path, class: "btn btn-primary" %> + <% end %> +
+ <% end %> +
+
+ + +
+ + + Tip: Click on user names to view detailed profiles, or use the Actions dropdown for quick operations. + +
+
diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..3d6b2f66e --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,435 @@ +<% content_for :title, "Create New User" %> + +
+ +
+
+

Create New User

+

Add a new user to the system

+
+
+ <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + Back to Users + <% end %> +
+
+ +
+ +
+
+
+
+ Instructions +
+
+
+
+
Required Information
+
    +
  • Full name
  • +
  • Valid email address
  • +
  • Secure password (min. 6 characters)
  • +
  • User role (User or Admin)
  • +
+
+ +
+
User Roles
+
+
+ User + Standard access with basic permissions +
+
+ Admin + Full system access and user management +
+
+
+ + +
+
+ + +
+
+
+ Current Stats +
+
+
+
+
+

<%= User.count %>

+ Total Users +
+
+

<%= User.admin.count %>

+ Administrators +
+
+
+
+
+ + +
+ <%= form_with model: [:admin, @user], local: true, html: { + multipart: true, + class: "needs-validation", + novalidate: true, + id: "new-user-form" + } do |form| %> + + +
+
+
+ Personal Information +
+
+
+
+
+ <%= form.label :full_name, class: "form-label required" %> + <%= form.text_field :full_name, + class: "form-control #{'is-invalid' if @user.errors[:full_name].present?}", + placeholder: "Enter full name", + required: true, + autofocus: true %> + <% if @user.errors[:full_name].present? %> +
+ <%= @user.errors[:full_name].first %> +
+ <% else %> +
User's full name as it will appear throughout the system.
+ <% end %> +
+ +
+ <%= form.label :email, class: "form-label required" %> + <%= form.email_field :email, + class: "form-control #{'is-invalid' if @user.errors[:email].present?}", + placeholder: "Enter email address", + required: true %> + <% if @user.errors[:email].present? %> +
+ <%= @user.errors[:email].first %> +
+ <% else %> +
Must be a valid email address.
+ <% end %> +
+
+ +
+
+ <%= form.label :role, class: "form-label required" %> + <%= form.select :role, + options_for_select([ + ['Regular User', 'user', { 'data-description': 'Standard user with basic permissions' }], + ['Administrator', 'admin', { 'data-description': 'Full system access and user management' }] + ], @user.role || 'user'), + {}, + { + class: "form-select #{'is-invalid' if @user.errors[:role].present?}", + id: "user_role" + } %> + <% if @user.errors[:role].present? %> +
+ <%= @user.errors[:role].first %> +
+ <% else %> +
+ Standard user with basic permissions +
+ <% end %> +
+ +
+ <%= form.label :avatar, "Profile Picture", class: "form-label" %> + <%= form.file_field :avatar, + class: "form-control #{'is-invalid' if @user.errors[:avatar].present?}", + accept: "image/*", + id: "avatar-upload" %> + <% if @user.errors[:avatar].present? %> +
+ <%= @user.errors[:avatar].first %> +
+ <% else %> +
+ Optional: Upload a profile picture (JPG, PNG, or GIF). Max size: 5MB. +
+ <% end %> +
+
+
+
+ + +
+
+
+ Password Setup +
+
+
+ + +
+
+ <%= form.label :password, class: "form-label required" %> + <%= form.password_field :password, + class: "form-control #{'is-invalid' if @user.errors[:password].present?}", + placeholder: "Enter password", + required: true, + autocomplete: "new-password", + id: "password-field" %> + <% if @user.errors[:password].present? %> +
+ <%= @user.errors[:password].first %> +
+ <% else %> +
+ Password must be at least 6 characters long. +
+ <% end %> +
+ +
+ <%= form.label :password_confirmation, class: "form-label required" %> + <%= form.password_field :password_confirmation, + class: "form-control #{'is-invalid' if @user.errors[:password_confirmation].present?}", + placeholder: "Confirm password", + required: true, + autocomplete: "new-password", + id: "password-confirmation-field" %> + <% if @user.errors[:password_confirmation].present? %> +
+ <%= @user.errors[:password_confirmation].first %> +
+ <% else %> +
+ Re-enter the password to confirm. +
+ <% end %> +
+
+ + +
+ +
+
+
+ Enter a password to see strength +
+
+
+ + +
+
+
+ User Preview +
+
+
+
+
+
+ ?? +
+
+
+
User Name
+

user@example.com

+ user +
+
+
+
+ + +
+
+
+
+ + +
+ +
+ <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + Cancel + <% end %> + + <%= form.submit "Create User", + class: "btn btn-primary", + id: "submit-btn" do %> + Create User + <% end %> +
+
+
+
+ <% end %> +
+
+
+ + + diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb new file mode 100644 index 000000000..99d85fb6e --- /dev/null +++ b/app/views/admin/users/show.html.erb @@ -0,0 +1,224 @@ +<% content_for :title, "User Details - #{@user.display_name}" %> + +
+ +
+
+

User Details

+

View and manage user information

+
+
+ <%= link_to edit_admin_user_path(@user), class: "btn btn-primary" do %> + Edit User + <% end %> + <%= link_to admin_users_path, class: "btn btn-outline-secondary" do %> + Back to Users + <% end %> +
+
+ +
+ +
+
+
+ <% if @user.avatar %> + <%= image_tag @user.avatar, class: "user-avatar mx-auto d-block mb-3", alt: @user.display_name %> + <% else %> +
+ <%= @user.initials %> +
+ <% end %> + + +
+
+ + +
+
+
+ Quick Actions +
+
+
+
+ <%= link_to edit_admin_user_path(@user), class: "btn btn-outline-primary" do %> + Edit Profile + <% end %> + + <%= link_to toggle_role_admin_user_path(@user), + method: :patch, + class: "btn btn-outline-warning #{'disabled' if @user == current_user}", + data: { confirm: "Are you sure you want to change this user's role?" } do %> + + Toggle Role (<%= @user.admin? ? 'Make User' : 'Make Admin' %>) + <% end %> + + <%= mail_to @user.email, class: "btn btn-outline-info" do %> + Send Email + <% end %> + + <% unless @user == current_user %> + <%= link_to admin_user_path(@user), + method: :delete, + class: "btn btn-outline-danger", + data: { confirm: "Are you sure you want to delete this user? This action cannot be undone." } do %> + Delete User + <% end %> + <% end %> +
+
+
+
+ + +
+ +
+
+
+ Personal Information +
+
+
+
+
+
+ +

<%= @user.full_name %>

+
+
+
+
+ +

+ <%= mail_to @user.email, @user.email, class: "text-decoration-none" %> +

+
+
+
+
+ +

+ + <%= @user.role.humanize %> + +

+
+
+
+
+ +

+ <%= @user.created_at.strftime("%B %d, %Y") %> + (<%= time_ago_in_words(@user.created_at) %> ago) +

+
+
+
+
+
+ + +
+
+
+ Account Information +
+
+
+
+
+
+ +

+ <% if @user.current_sign_in_at %> + <%= @user.current_sign_in_at.strftime("%B %d, %Y at %I:%M %p") %> +
<%= time_ago_in_words(@user.current_sign_in_at) %> ago + <% else %> + Never signed in + <% end %> +

+
+
+
+
+ +

+ <%= @user.sign_in_count || 0 %> times +

+
+
+
+
+ +

+ <% if @user.current_sign_in_at.present? && @user.current_sign_in_at > 30.days.ago %> + Active + <% elsif @user.current_sign_in_at.present? %> + Inactive + <% else %> + Never logged in + <% end %> +

+
+
+
+
+ +

+ <%= @user.updated_at.strftime("%B %d, %Y") %> + (<%= time_ago_in_words(@user.updated_at) %> ago) +

+
+
+
+
+
+ + + <% if @user.admin? %> +
+
+
+ Admin Activity +
+
+
+
+
+
+

<%= @user.imports.count %>

+ Imports Created +
+
+
+
+

<%= @user.imports.where(status: 'completed').count %>

+ Successful Imports +
+
+
+

+ <%= @user.imports.sum(:successful_rows) %> +

+ Users Imported +
+
+
+
+ <% end %> +
+
+
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..be4cf3f5f --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,44 @@ + + + + <%= content_for(:title) || "User Management App" %> + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + <%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %> + <%#= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %> + + + + + + <%# Bootstrap CSS %> + + + <%# Bootstrap Icons %> + + + <%# Includes all stylesheet files in app/assets/stylesheets %> + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <%= render 'shared/navbar' if user_signed_in? %> + +
+ <%= render 'shared/flash_messages' %> + <%= yield %> +
+ + <%= render 'shared/footer' if user_signed_in? %> + + <%# Bootstrap JavaScript %> + + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..3aac9002e --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/shared/_flash_messages.html.erb b/app/views/shared/_flash_messages.html.erb new file mode 100644 index 000000000..cfdc48ee2 --- /dev/null +++ b/app/views/shared/_flash_messages.html.erb @@ -0,0 +1,31 @@ +<% if notice || alert || flash.any? %> +
+ <% flash.each do |type, message| %> + <% + # Map Rails flash types to Bootstrap alert classes + alert_class = case type.to_s + 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 %> \ No newline at end of file diff --git a/app/views/shared/_footer.html.erb b/app/views/shared/_footer.html.erb new file mode 100644 index 000000000..482a1ccee --- /dev/null +++ b/app/views/shared/_footer.html.erb @@ -0,0 +1,20 @@ +
+
+
+
+
User Management App
+

+ A modern user management system built with Ruby on Rails and Bootstrap. +

+
+
+

+ © <%= Date.current.year %> User Management App. All rights reserved. +

+ + Built with using Rails <%= Rails.version %> + +
+
+
+
\ No newline at end of file diff --git a/app/views/shared/_navbar.html.erb b/app/views/shared/_navbar.html.erb new file mode 100644 index 000000000..84f0d8767 --- /dev/null +++ b/app/views/shared/_navbar.html.erb @@ -0,0 +1,63 @@ +
\ No newline at end of file From 6a562f25186f51f1a44d5bc3d744d2999233f1e2 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:54:26 -0300 Subject: [PATCH 09/20] feat: create user authentication and profile views - User profile and edit views with Bootstrap styling - Devise authentication forms (login, registration, password reset) - Home page with role-based content display - PWA manifest and service worker files - Responsive design with form validation and error handling --- app/views/devise/confirmations/new.html.erb | 20 ++ .../mailer/confirmation_instructions.html.erb | 5 + .../devise/mailer/email_changed.html.erb | 7 + .../devise/mailer/password_change.html.erb | 3 + .../reset_password_instructions.html.erb | 8 + .../mailer/unlock_instructions.html.erb | 7 + app/views/devise/passwords/edit.html.erb | 27 +++ app/views/devise/passwords/new.html.erb | 18 ++ app/views/devise/registrations/edit.html.erb | 35 +++ app/views/devise/registrations/new.html.erb | 183 +++++++++++++++ app/views/devise/sessions/new.html.erb | 86 ++++++++ .../devise/shared/_error_messages.html.erb | 15 ++ app/views/devise/shared/_links.html.erb | 45 ++++ app/views/devise/unlocks/new.html.erb | 19 ++ app/views/home/index.html.erb | 40 ++++ app/views/pwa/manifest.json.erb | 22 ++ app/views/pwa/service-worker.js | 26 +++ app/views/users/edit.html.erb | 208 ++++++++++++++++++ app/views/users/show.html.erb | 136 ++++++++++++ 19 files changed, 910 insertions(+) create mode 100644 app/views/devise/confirmations/new.html.erb create mode 100644 app/views/devise/mailer/confirmation_instructions.html.erb create mode 100644 app/views/devise/mailer/email_changed.html.erb create mode 100644 app/views/devise/mailer/password_change.html.erb create mode 100644 app/views/devise/mailer/reset_password_instructions.html.erb create mode 100644 app/views/devise/mailer/unlock_instructions.html.erb create mode 100644 app/views/devise/passwords/edit.html.erb create mode 100644 app/views/devise/passwords/new.html.erb create mode 100644 app/views/devise/registrations/edit.html.erb create mode 100644 app/views/devise/registrations/new.html.erb create mode 100644 app/views/devise/sessions/new.html.erb create mode 100644 app/views/devise/shared/_error_messages.html.erb create mode 100644 app/views/devise/shared/_links.html.erb create mode 100644 app/views/devise/unlocks/new.html.erb create mode 100644 app/views/home/index.html.erb create mode 100644 app/views/pwa/manifest.json.erb create mode 100644 app/views/pwa/service-worker.js create mode 100644 app/views/users/edit.html.erb create mode 100644 app/views/users/show.html.erb diff --git a/app/views/devise/confirmations/new.html.erb b/app/views/devise/confirmations/new.html.erb new file mode 100644 index 000000000..f7b4a65c5 --- /dev/null +++ b/app/views/devise/confirmations/new.html.erb @@ -0,0 +1,20 @@ +

Resend confirmation instructions

+ +<%= simple_form_for(resource, as: resource_name, url: confirmation_path(resource_name), html: { method: :post }) do |f| %> + <%= f.error_notification %> + <%= f.full_error :confirmation_token %> + +
+ <%= f.input :email, + required: true, + autofocus: true, + value: (resource.pending_reconfirmation? ? resource.unconfirmed_email : resource.email), + input_html: { autocomplete: "email" } %> +
+ +
+ <%= f.button :submit, "Resend confirmation instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/mailer/confirmation_instructions.html.erb b/app/views/devise/mailer/confirmation_instructions.html.erb new file mode 100644 index 000000000..dc55f64f6 --- /dev/null +++ b/app/views/devise/mailer/confirmation_instructions.html.erb @@ -0,0 +1,5 @@ +

Welcome <%= @email %>!

+ +

You can confirm your account email through the link below:

+ +

<%= link_to 'Confirm my account', confirmation_url(@resource, confirmation_token: @token) %>

diff --git a/app/views/devise/mailer/email_changed.html.erb b/app/views/devise/mailer/email_changed.html.erb new file mode 100644 index 000000000..32f4ba803 --- /dev/null +++ b/app/views/devise/mailer/email_changed.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @email %>!

+ +<% if @resource.try(:unconfirmed_email?) %> +

We're contacting you to notify you that your email is being changed to <%= @resource.unconfirmed_email %>.

+<% else %> +

We're contacting you to notify you that your email has been changed to <%= @resource.email %>.

+<% end %> diff --git a/app/views/devise/mailer/password_change.html.erb b/app/views/devise/mailer/password_change.html.erb new file mode 100644 index 000000000..b41daf476 --- /dev/null +++ b/app/views/devise/mailer/password_change.html.erb @@ -0,0 +1,3 @@ +

Hello <%= @resource.email %>!

+ +

We're contacting you to notify you that your password has been changed.

diff --git a/app/views/devise/mailer/reset_password_instructions.html.erb b/app/views/devise/mailer/reset_password_instructions.html.erb new file mode 100644 index 000000000..f667dc12f --- /dev/null +++ b/app/views/devise/mailer/reset_password_instructions.html.erb @@ -0,0 +1,8 @@ +

Hello <%= @resource.email %>!

+ +

Someone has requested a link to change your password. You can do this through the link below.

+ +

<%= link_to 'Change my password', edit_password_url(@resource, reset_password_token: @token) %>

+ +

If you didn't request this, please ignore this email.

+

Your password won't change until you access the link above and create a new one.

diff --git a/app/views/devise/mailer/unlock_instructions.html.erb b/app/views/devise/mailer/unlock_instructions.html.erb new file mode 100644 index 000000000..41e148bf2 --- /dev/null +++ b/app/views/devise/mailer/unlock_instructions.html.erb @@ -0,0 +1,7 @@ +

Hello <%= @resource.email %>!

+ +

Your account has been locked due to an excessive number of unsuccessful sign in attempts.

+ +

Click the link below to unlock your account:

+ +

<%= link_to 'Unlock my account', unlock_url(@resource, unlock_token: @token) %>

diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb new file mode 100644 index 000000000..591cd8c85 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,27 @@ +

Change your password

+ +<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> + <%= f.error_notification %> + + <%= f.input :reset_password_token, as: :hidden %> + <%= f.full_error :reset_password_token %> + +
+ <%= f.input :password, + label: "New password", + required: true, + autofocus: true, + hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), + input_html: { autocomplete: "new-password" } %> + <%= f.input :password_confirmation, + label: "Confirm your new password", + required: true, + input_html: { autocomplete: "new-password" } %> +
+ +
+ <%= f.button :submit, "Change my password" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 000000000..01ce0b8b9 --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,18 @@ +

Forgot your password?

+ +<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> + <%= f.error_notification %> + +
+ <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" } %> +
+ +
+ <%= f.button :submit, "Send me reset password instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/devise/registrations/edit.html.erb b/app/views/devise/registrations/edit.html.erb new file mode 100644 index 000000000..b3c0089ad --- /dev/null +++ b/app/views/devise/registrations/edit.html.erb @@ -0,0 +1,35 @@ +

Edit <%= resource_name.to_s.humanize %>

+ +<%= simple_form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %> + <%= f.error_notification %> + +
+ <%= f.input :email, required: true, autofocus: true %> + + <% if devise_mapping.confirmable? && resource.pending_reconfirmation? %> +

Currently waiting confirmation for: <%= resource.unconfirmed_email %>

+ <% end %> + + <%= f.input :password, + hint: "leave it blank if you don't want to change it", + required: false, + input_html: { autocomplete: "new-password" } %> + <%= f.input :password_confirmation, + required: false, + input_html: { autocomplete: "new-password" } %> + <%= f.input :current_password, + hint: "we need your current password to confirm your changes", + required: true, + input_html: { autocomplete: "current-password" } %> +
+ +
+ <%= f.button :submit, "Update" %> +
+<% end %> + +

Cancel my account

+ +
Unhappy? <%= button_to "Cancel my account", registration_path(resource_name), data: { confirm: "Are you sure?", turbo_confirm: "Are you sure?" }, method: :delete %>
+ +<%= link_to "Back", :back %> diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb new file mode 100644 index 000000000..b7fc194be --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,183 @@ +<% content_for :title, "Create Account" %> + +
+
+
+
+
+
+
+ +
+

Create Account

+

Join our platform today

+
+ + <%= form_with model: resource, + as: resource_name, + url: registration_path(resource_name), + local: true, + html: { + class: "auth-form needs-validation", + novalidate: true, + multipart: true + } do |f| %> + + <% if resource.errors.any? %> +
+
Please fix the following errors:
+
    + <% resource.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+ <% end %> + +
+ <%= f.label :full_name, class: "form-label" %> + <%= f.text_field :full_name, + class: "form-control #{'is-invalid' if resource.errors[:full_name].present?}", + placeholder: "Enter your full name", + autofocus: true, + required: true %> + <% if resource.errors[:full_name].present? %> +
+ <%= resource.errors[:full_name].first %> +
+ <% else %> +
+ Please enter your full name. +
+ <% end %> +
+ +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, + class: "form-control #{'is-invalid' if resource.errors[:email].present?}", + placeholder: "Enter your email address", + autocomplete: "email", + required: true %> + <% if resource.errors[:email].present? %> +
+ <%= resource.errors[:email].first %> +
+ <% else %> +
+ Please enter a valid email address. +
+ <% end %> +
+ +
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, + class: "form-control #{'is-invalid' if resource.errors[:password].present?}", + placeholder: "Create a password", + autocomplete: "new-password", + required: true, + minlength: (@minimum_password_length || 6) %> + <% if resource.errors[:password].present? %> +
+ <%= resource.errors[:password].first %> +
+ <% else %> +
+ <% if @minimum_password_length %> + Minimum <%= @minimum_password_length %> characters required. + <% else %> + Choose a strong password. + <% end %> +
+ <% end %> +
+ +
+ <%= f.label :password_confirmation, "Confirm Password", class: "form-label" %> + <%= f.password_field :password_confirmation, + class: "form-control #{'is-invalid' if resource.errors[:password_confirmation].present?}", + placeholder: "Confirm your password", + autocomplete: "new-password", + required: true %> + <% if resource.errors[:password_confirmation].present? %> +
+ <%= resource.errors[:password_confirmation].first %> +
+ <% else %> +
+ Please confirm your password. +
+ <% end %> +
+ +
+ <%= f.label :avatar, "Profile Picture (Optional)", class: "form-label" %> + <%= f.file_field :avatar, + class: "form-control #{'is-invalid' if resource.errors[:avatar].present?}", + accept: "image/*" %> + <% if resource.errors[:avatar].present? %> +
+ <%= resource.errors[:avatar].first %> +
+ <% else %> +
+ Upload a profile picture (JPG, PNG, or GIF). Max size: 5MB. +
+ <% end %> +
+ +
+ <%= f.submit "Create Account", class: "btn btn-primary btn-lg" %> +
+ <% end %> + +
+ or +
+ + +
+
+
+
+
+ + diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb new file mode 100644 index 000000000..059f973f1 --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,86 @@ +<% content_for :title, "Sign In" %> + +
+
+
+
+
+
+
+ +
+

Welcome Back

+

Sign in to your account

+
+ + <%= form_with model: resource, + as: resource_name, + url: session_path(resource_name), + local: true, + html: { class: "auth-form needs-validation", novalidate: true } do |f| %> + +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, + class: "form-control", + placeholder: "Enter your email", + autofocus: true, + autocomplete: "email", + required: true %> +
+ Please enter a valid email address. +
+
+ +
+ <%= f.label :password, class: "form-label" %> + <%= f.password_field :password, + class: "form-control", + placeholder: "Enter your password", + autocomplete: "current-password", + required: true %> +
+ Please enter your password. +
+
+ + <% if devise_mapping.rememberable? %> +
+ <%= f.check_box :remember_me, class: "form-check-input" %> + <%= f.label :remember_me, "Keep me signed in", class: "form-check-label" %> +
+ <% end %> + +
+ <%= f.submit "Sign In", class: "btn btn-primary btn-lg" %> +
+ <% end %> + +
+ or +
+ + +
+
+
+
+
+ + diff --git a/app/views/devise/shared/_error_messages.html.erb b/app/views/devise/shared/_error_messages.html.erb new file mode 100644 index 000000000..cabfe307e --- /dev/null +++ b/app/views/devise/shared/_error_messages.html.erb @@ -0,0 +1,15 @@ +<% if resource.errors.any? %> +
+

+ <%= I18n.t("errors.messages.not_saved", + count: resource.errors.count, + resource: resource.class.model_name.human.downcase) + %> +

+
    + <% resource.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+<% end %> diff --git a/app/views/devise/shared/_links.html.erb b/app/views/devise/shared/_links.html.erb new file mode 100644 index 000000000..b7be42eb2 --- /dev/null +++ b/app/views/devise/shared/_links.html.erb @@ -0,0 +1,45 @@ +<%- if controller_name != 'sessions' %> + <%= link_to new_session_path(resource_name), class: "btn btn-outline-primary w-100" do %> + Sign In + <% end %> +<% end %> + +<%- if devise_mapping.registerable? && controller_name != 'registrations' %> + <%= link_to new_registration_path(resource_name), class: "btn btn-outline-success w-100 mt-2" do %> + Create Account + <% end %> +<% end %> + +<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %> +
+ <%= link_to new_password_path(resource_name), class: "text-decoration-none" do %> + Forgot your password? + <% end %> +
+<% end %> + +<%- if devise_mapping.confirmable? && controller_name != 'confirmations' %> +
+ <%= link_to new_confirmation_path(resource_name), class: "text-decoration-none" do %> + Didn't receive confirmation instructions? + <% end %> +
+<% end %> + +<%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %> +
+ <%= link_to new_unlock_path(resource_name), class: "text-decoration-none" do %> + Didn't receive unlock instructions? + <% end %> +
+<% end %> + +<%- if devise_mapping.omniauthable? %> + <%- resource_class.omniauth_providers.each do |provider| %> + <%= button_to omniauth_authorize_path(resource_name, provider), + class: "btn btn-outline-secondary w-100 mt-2", + data: { turbo: false } do %> + Sign in with <%= OmniAuth::Utils.camelize(provider) %> + <% end %> + <% end %> +<% end %> diff --git a/app/views/devise/unlocks/new.html.erb b/app/views/devise/unlocks/new.html.erb new file mode 100644 index 000000000..c42de1738 --- /dev/null +++ b/app/views/devise/unlocks/new.html.erb @@ -0,0 +1,19 @@ +

Resend unlock instructions

+ +<%= simple_form_for(resource, as: resource_name, url: unlock_path(resource_name), html: { method: :post }) do |f| %> + <%= f.error_notification %> + <%= f.full_error :unlock_token %> + +
+ <%= f.input :email, + required: true, + autofocus: true, + input_html: { autocomplete: "email" } %> +
+ +
+ <%= f.button :submit, "Resend unlock instructions" %> +
+<% end %> + +<%= render "devise/shared/links" %> diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb new file mode 100644 index 000000000..668dd29bb --- /dev/null +++ b/app/views/home/index.html.erb @@ -0,0 +1,40 @@ +<% content_for :title, "Welcome to User Management" %> + +
+
+
+ +

User Management

+

Welcome! Please sign in to continue or register for a new account.

+
+ +
+ <%= link_to "Sign In", new_user_session_path, class: "btn btn-primary btn-lg" %> + <%= link_to "Register", new_user_registration_path, class: "btn btn-outline-primary btn-lg" %> +
+ +
+ Features +
+ +
+
+ +
Secure
+ Protected authentication +
+
+ +
Fast
+ Real-time updates +
+
+ +
Responsive
+ Mobile friendly +
+
+
+
diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..b47e0ae81 --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "UserManagementApp", + "icons": [ + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "start_url": "/", + "display": "standalone", + "scope": "/", + "description": "UserManagementApp.", + "theme_color": "red", + "background_color": "red" +} diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js new file mode 100644 index 000000000..b3a13fb7b --- /dev/null +++ b/app/views/pwa/service-worker.js @@ -0,0 +1,26 @@ +// Add a service worker for processing Web Push notifications: +// +// self.addEventListener("push", async (event) => { +// const { title, options } = await event.data.json() +// event.waitUntil(self.registration.showNotification(title, options)) +// }) +// +// self.addEventListener("notificationclick", function(event) { +// event.notification.close() +// event.waitUntil( +// clients.matchAll({ type: "window" }).then((clientList) => { +// for (let i = 0; i < clientList.length; i++) { +// let client = clientList[i] +// let clientPath = (new URL(client.url)).pathname +// +// if (clientPath == event.notification.data.path && "focus" in client) { +// return client.focus() +// } +// } +// +// if (clients.openWindow) { +// return clients.openWindow(event.notification.data.path) +// } +// }) +// ) +// }) diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 000000000..d4f776a82 --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,208 @@ +<% content_for :title, "Edit Profile" %> + +
+
+
+ +
+
+

Edit Profile

+

Update your personal information

+
+ <%= link_to profile_path, class: "btn btn-outline-secondary" do %> + Back to Profile + <% end %> +
+ + +
+ <%= simple_form_for @user, url: profile_path, method: :patch, multipart: true do |f| %> +
+ +
+
+ <% if @user.avatar %> + <%= image_tag @user.avatar, class: "avatar-lg rounded-circle mb-3", alt: @user.display_name, id: "avatar-preview" %> + <% else %> +
+ +
+ <% end %> + +
Profile Picture
+

Choose how you want to set your profile picture

+
+
+
+ + +
+
+
+ Avatar Options +
+
+
+ +
+ <%= f.input :avatar_image, + label: "Upload Image", + input_html: { + class: "form-control", + accept: "image/*", + onchange: "previewFile(this)" + } %> +
+ Supported formats: JPG, PNG, GIF. Maximum size: 5MB. +
+
+ +
+ — OR — +
+ + +
+ <%= f.input :avatar_url, + label: "Image URL", + placeholder: "https://example.com/avatar.jpg", + input_html: { + class: "form-control", + onchange: "previewUrl(this)" + } %> +
+ Enter a direct link to an image online. +
+
+
+
+ + +
+
+
+ Personal Information +
+
+
+ <%= f.input :full_name, + label: "Full Name", + required: true, + input_html: { class: "form-control" } %> + + <%= f.input :email, + label: "Email Address", + required: true, + input_html: { class: "form-control", readonly: true }, + hint: "Contact an administrator to change your email address" %> +
+
+ + +
+
+
+ Change Password +
+
+
+

+ Leave blank to keep your current password +

+ + <%= f.input :password, + label: "New Password", + input_html: { class: "form-control", autocomplete: "new-password" }, + hint: "Minimum 6 characters" %> + + <%= f.input :password_confirmation, + label: "Confirm New Password", + input_html: { class: "form-control", autocomplete: "new-password" } %> +
+
+ + +
+ <%= link_to profile_path, class: "btn btn-outline-secondary" do %> + Cancel + <% end %> + + <%= f.submit "Update Profile", class: "btn btn-primary" do %> + Update Profile + <% end %> +
+ <% end %> +
+
+
+
+ + diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb new file mode 100644 index 000000000..7c81a1b39 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,136 @@ +<% content_for :title, "My Profile" %> + +
+
+
+ +
+
+
+
+ <% if @user.avatar %> + <%= image_tag @user.avatar, class: "user-avatar rounded-circle mx-auto d-block", alt: @user.display_name %> + <% else %> +
+ +
+ <% end %> +
+
+ +
+
+
+
+ + +
+
+
+ Profile Settings +
+
+
+
+
+
Personal Information
+

+ Update your personal details and avatar image. +

+
+
+ <%= link_to profile_edit_path, class: "btn btn-primary" do %> + Edit Profile + <% end %> +
+
+ +
+ +
+
+
Account Security
+

+ Change your password and manage account settings. +

+
+
+ <%= link_to edit_user_registration_path, class: "btn btn-outline-secondary" do %> + Security Settings + <% end %> +
+
+ +
+ +
+
+
Danger Zone
+

+ Permanently delete your account and all data. +

+
+
+ <%= link_to profile_path, + method: :delete, + class: "btn btn-outline-danger", + data: { + confirm: "Are you sure you want to delete your account? This action cannot be undone." + } do %> + Delete Account + <% end %> +
+
+
+
+ + + <% if @user.admin? %> +
+
+
+ Admin Summary +
+
+
+
+
+

<%= User.total_count %>

+ Total Users +
+
+

<%= Import.where(status: 'completed').count %>

+ Completed Imports +
+
+

<%= Import.where(status: 'processing').count %>

+ Active Imports +
+
+

<%= User.where('created_at > ?', 30.days.ago).count %>

+ New Users (30d) +
+
+
+ <%= link_to admin_dashboard_path, class: "btn btn-primary" do %> + Go to Dashboard + <% end %> +
+
+
+ <% end %> +
+
+
From ad338ce2b88005f961c4b8e45b134f5d9ea79da5 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Thu, 6 Nov 2025 16:55:13 -0300 Subject: [PATCH 10/20] feat: setup assets pipeline, styling and comprehensive documentation - Bootstrap integration with custom SCSS components - JavaScript modules for Action Cable and interactive features - Importmap configuration for modern JS module loading - Simple Form configuration with Bootstrap styling - Complete README with installation and usage instructions - RSpec test structure and factories for development - Production deployment configuration and optimization --- README.md | 449 +++++++++++++++--- app/assets/builds/.keep | 0 app/assets/builds/application.css | 1 + app/assets/images/.keep | 0 app/assets/stylesheets/_custom.scss | 76 +++ app/assets/stylesheets/application.css | 10 + app/assets/stylesheets/application.scss | 10 + app/assets/stylesheets/components/_cards.scss | 133 ++++++ app/assets/stylesheets/components/_forms.scss | 79 +++ .../stylesheets/components/_navbar.scss | 44 ++ .../stylesheets/components/_tables.scss | 138 ++++++ .../stylesheets/layouts/_authentication.scss | 130 +++++ .../stylesheets/layouts/_dashboard.scss | 108 +++++ app/javascript/application.js | 4 + app/javascript/channels/consumer.js | 6 + app/javascript/channels/dashboard_channel.js | 15 + .../channels/import_progress_channel.js | 15 + app/javascript/channels/index.js | 3 + app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + app/javascript/controllers/index.js | 4 + config/cache.yml | 16 + config/deploy.yml | 116 +++++ config/importmap.rb | 9 + config/initializers/assets.rb | 7 + .../initializers/content_security_policy.rb | 25 + .../initializers/filter_parameter_logging.rb | 8 + config/initializers/inflections.rb | 16 + config/initializers/simple_form.rb | 176 +++++++ config/initializers/simple_form_bootstrap.rb | 372 +++++++++++++++ config/locales/en.yml | 31 ++ config/locales/simple_form.en.yml | 31 ++ config/puma.rb | 41 ++ config/storage.yml | 34 ++ lib/tasks/.keep | 0 lib/templates/erb/scaffold/_form.html.erb | 15 + log/.keep | 0 spec/factories/users.rb | 5 + spec/helpers/admin/dashboard_helper_spec.rb | 15 + spec/helpers/admin/users_helper_spec.rb | 15 + spec/helpers/home_helper_spec.rb | 15 + spec/helpers/users_helper_spec.rb | 15 + spec/models/user_spec.rb | 5 + spec/requests/admin/dashboard_spec.rb | 11 + spec/requests/admin/users_spec.rb | 60 +++ spec/requests/home_spec.rb | 11 + spec/requests/users_spec.rb | 32 ++ .../admin/dashboard/index.html.erb_spec.rb | 5 + .../views/admin/users/create.html.erb_spec.rb | 5 + .../admin/users/destroy.html.erb_spec.rb | 5 + spec/views/admin/users/edit.html.erb_spec.rb | 5 + spec/views/admin/users/index.html.erb_spec.rb | 5 + spec/views/admin/users/new.html.erb_spec.rb | 5 + spec/views/admin/users/show.html.erb_spec.rb | 5 + .../admin/users/toggle_role.html.erb_spec.rb | 5 + .../views/admin/users/update.html.erb_spec.rb | 5 + spec/views/home/index.html.erb_spec.rb | 5 + spec/views/users/destroy.html.erb_spec.rb | 5 + spec/views/users/edit.html.erb_spec.rb | 5 + spec/views/users/show.html.erb_spec.rb | 5 + spec/views/users/update.html.erb_spec.rb | 5 + vendor/.keep | 0 vendor/javascript/.keep | 0 63 files changed, 2325 insertions(+), 67 deletions(-) create mode 100644 app/assets/builds/.keep create mode 100644 app/assets/builds/application.css create mode 100644 app/assets/images/.keep create mode 100644 app/assets/stylesheets/_custom.scss create mode 100644 app/assets/stylesheets/application.css create mode 100644 app/assets/stylesheets/application.scss create mode 100644 app/assets/stylesheets/components/_cards.scss create mode 100644 app/assets/stylesheets/components/_forms.scss create mode 100644 app/assets/stylesheets/components/_navbar.scss create mode 100644 app/assets/stylesheets/components/_tables.scss create mode 100644 app/assets/stylesheets/layouts/_authentication.scss create mode 100644 app/assets/stylesheets/layouts/_dashboard.scss create mode 100644 app/javascript/application.js create mode 100644 app/javascript/channels/consumer.js create mode 100644 app/javascript/channels/dashboard_channel.js create mode 100644 app/javascript/channels/import_progress_channel.js create mode 100644 app/javascript/channels/index.js create mode 100644 app/javascript/controllers/application.js create mode 100644 app/javascript/controllers/hello_controller.js create mode 100644 app/javascript/controllers/index.js create mode 100644 config/cache.yml create mode 100644 config/deploy.yml create mode 100644 config/importmap.rb create mode 100644 config/initializers/assets.rb create mode 100644 config/initializers/content_security_policy.rb create mode 100644 config/initializers/filter_parameter_logging.rb create mode 100644 config/initializers/inflections.rb create mode 100644 config/initializers/simple_form.rb create mode 100644 config/initializers/simple_form_bootstrap.rb create mode 100644 config/locales/en.yml create mode 100644 config/locales/simple_form.en.yml create mode 100644 config/puma.rb create mode 100644 config/storage.yml create mode 100644 lib/tasks/.keep create mode 100644 lib/templates/erb/scaffold/_form.html.erb create mode 100644 log/.keep create mode 100644 spec/factories/users.rb create mode 100644 spec/helpers/admin/dashboard_helper_spec.rb create mode 100644 spec/helpers/admin/users_helper_spec.rb create mode 100644 spec/helpers/home_helper_spec.rb create mode 100644 spec/helpers/users_helper_spec.rb create mode 100644 spec/models/user_spec.rb create mode 100644 spec/requests/admin/dashboard_spec.rb create mode 100644 spec/requests/admin/users_spec.rb create mode 100644 spec/requests/home_spec.rb create mode 100644 spec/requests/users_spec.rb create mode 100644 spec/views/admin/dashboard/index.html.erb_spec.rb create mode 100644 spec/views/admin/users/create.html.erb_spec.rb create mode 100644 spec/views/admin/users/destroy.html.erb_spec.rb create mode 100644 spec/views/admin/users/edit.html.erb_spec.rb create mode 100644 spec/views/admin/users/index.html.erb_spec.rb create mode 100644 spec/views/admin/users/new.html.erb_spec.rb create mode 100644 spec/views/admin/users/show.html.erb_spec.rb create mode 100644 spec/views/admin/users/toggle_role.html.erb_spec.rb create mode 100644 spec/views/admin/users/update.html.erb_spec.rb create mode 100644 spec/views/home/index.html.erb_spec.rb create mode 100644 spec/views/users/destroy.html.erb_spec.rb create mode 100644 spec/views/users/edit.html.erb_spec.rb create mode 100644 spec/views/users/show.html.erb_spec.rb create mode 100644 spec/views/users/update.html.erb_spec.rb create mode 100644 vendor/.keep create mode 100644 vendor/javascript/.keep diff --git a/README.md b/README.md index e18f57431..c835fd819 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,382 @@ -# 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, ... +# 🚀 Sistema de Gerenciamento de Usuários + +Um sistema completo de gerenciamento de usuários em Ruby on Rails com funcionalidades avançadas de autenticação, autorização baseada em roles e importação de usuários via CSV com processamento em background e atualizações em tempo real. + +## 📋 Índice + +- [Funcionalidades](#-funcionalidades) +- [Tecnologias](#-tecnologias) +- [Instalação](#-instalação) +- [Configuração](#-configuração) +- [Como Usar](#-como-usar) +- [Arquitetura](#-arquitetura) +- [Segurança](#-segurança) +- [API](#-api) +- [Contribuição](#-contribuição) + +## ✨ Funcionalidades + +### 🔐 **Autenticação e Autorização** +- ✅ Sistema completo de autenticação com **Devise** +- ✅ **Roles** hierárquicos (Admin, Manager, User) +- ✅ Controle de acesso granular por funcionalidade +- ✅ Rastreamento de login para auditoria +- ✅ Proteção contra ataques comuns (CSRF, XSS) + +### 👥 **Gerenciamento de Usuários** +- ✅ **CRUD completo** para administradores +- ✅ **Perfil editável** pelos próprios usuários +- ✅ **Busca avançada** (nome, email, role, status) +- ✅ **Filtros dinâmicos** com paginação +- ✅ **Validações robustas** e feedback de erros + +### 📊 **Dashboard Administrativo** +- ✅ **Métricas em tempo real** via WebSockets +- ✅ **Estatísticas do sistema** (usuários, roles, atividade) +- ✅ **Interface responsiva** com Bootstrap 5 +- ✅ **Atualizações automáticas** sem refresh + +### 📁 **Importação CSV** +- ✅ **Upload de arquivos** com validação +- ✅ **Processamento assíncrono** em background +- ✅ **Progress tracking** em tempo real +- ✅ **Relatórios de erro** detalhados +- ✅ **Histórico de importações** com status + +## 🛠️ Tecnologias + +### Backend +- **Ruby 3.2.0** +- **Rails 7.x** +- **SQLite** (desenvolvimento) / **PostgreSQL** (produção) +- **Devise** (autenticação) +- **Active Job** (background processing) +- **Action Cable** (WebSockets) + +### Frontend +- **Bootstrap 5** (UI Framework) +- **Stimulus** (JavaScript framework) +- **Turbo** (SPA-like experience) +- **Simple Form** (formulários) +- **Importmap** (ES6 modules) + +### Ferramentas +- **Docker** (containerização) +- **Git** (controle de versão) +- **Rubocop** (linting) +- **Brakeman** (security scanning) + +## 🚀 Instalação + +### Pré-requisitos +- Ruby 3.2.0 ou superior +- Node.js 18+ e Yarn +- SQLite3 (desenvolvimento) +- Redis (para Action Cable em produção) + +### Setup Local + +1. **Clone o repositório:** +```bash +git clone https://github.com/lucasleandro1/Fullstack-Developer.git +cd Fullstack-Developer +``` + +2. **Instale as dependências:** +```bash +bundle install +yarn install +``` + +3. **Configure o banco de dados:** +```bash +rails db:create +rails db:migrate +rails db:seed +``` + +4. **Inicie o servidor:** +```bash +./bin/dev +# ou separadamente: +rails server +yarn build --watch +``` + +5. **Acesse a aplicação:** +``` +http://localhost:3000 +``` + +## ⚙️ Configuração + +### Variáveis de Ambiente + +Crie um arquivo `.env` na raiz do projeto: + +```env +# Database +DATABASE_URL=sqlite3:storage/development.sqlite3 + +# Redis (para Action Cable em produção) +REDIS_URL=redis://localhost:6379/0 + +# Email (opcional, para funcionalidades do Devise) +SMTP_ADDRESS=smtp.gmail.com +SMTP_PORT=587 +SMTP_USERNAME=your-email@gmail.com +SMTP_PASSWORD=your-app-password + +# Segurança +SECRET_KEY_BASE=your-secret-key-base +``` + +### Usuários de Teste + +Após rodar `rails db:seed`, você terá acesso a: + +| Email | Senha | Role | Descrição | +|-------|--------|------|-----------| +| `admin@example.com` | `password123` | Admin | Acesso total ao sistema | +| `manager@example.com` | `password123` | Manager | Gerenciamento de usuários | +| `user@example.com` | `password123` | User | Acesso básico | + +## 📖 Como Usar + +### 1. **Login no Sistema** +- Acesse `/users/sign_in` +- Use um dos usuários de teste ou registre-se + +### 2. **Dashboard (Admin/Manager)** +- Visualize métricas em tempo real +- Monitore atividade do sistema +- Acesse relatórios + +### 3. **Gerenciamento de Usuários (Admin)** +- **Listar:** Veja todos os usuários com filtros +- **Criar:** Adicione novos usuários manualmente +- **Editar:** Modifique informações e roles +- **Excluir:** Remove usuários do sistema + +### 4. **Importação CSV (Admin)** +- Acesse "Importações" no menu +- Faça upload de arquivo CSV +- Acompanhe o progresso em tempo real +- Veja relatório de resultados + +**Formato do CSV:** +```csv +first_name,last_name,email,role +João,Silva,joao@example.com,user +Maria,Santos,maria@example.com,manager +``` + +### 5. **Perfil do Usuário** +- Edite suas informações pessoais +- Altere senha +- Visualize histórico de login + +## 🏗️ Arquitetura + +### Estrutura de Diretórios + +``` +app/ +├── controllers/ +│ ├── application_controller.rb +│ ├── home_controller.rb +│ ├── users_controller.rb +│ └── admin/ +│ ├── dashboard_controller.rb +│ ├── users_controller.rb +│ └── imports_controller.rb +├── models/ +│ ├── user.rb +│ ├── import.rb +│ └── concerns/ +│ └── dashboard_broadcaster.rb +├── services/ +│ ├── application_service.rb +│ ├── user_management_service.rb +│ ├── user_search_service.rb +│ └── dashboard_stats_service.rb +├── jobs/ +│ └── user_import_job.rb +├── channels/ +│ ├── dashboard_channel.rb +│ └── import_progress_channel.rb +└── views/ + ├── layouts/ + ├── shared/ + ├── home/ + ├── users/ + └── admin/ +``` + +### Service Layer + +O projeto utiliza **Service Objects** para encapsular lógica de negócio: + +```ruby +# Exemplo de uso +result = UserManagementService.create_user(user_params) +if result.success? + redirect_to user_path(result.data) +else + flash[:error] = result.error +end +``` + +### Background Jobs + +Processamento assíncrono para operações pesadas: + +```ruby +# Importação CSV +UserImportJob.perform_later(import_id, current_user_id) +``` + +### Real-time Updates + +WebSockets para atualizações automáticas: + +```javascript +// Dashboard em tempo real +import consumer from "./consumer" + +consumer.subscriptions.create("DashboardChannel", { + received(data) { + updateDashboardMetrics(data) + } +}) +``` + +## 🛡️ Segurança + +### Implementações de Segurança + +- **Strong Parameters** para mass assignment protection +- **Authorization checks** em todos os controllers +- **Role-based access control** (RBAC) +- **File upload validation** com whitelist de tipos +- **CSRF protection** habilitada +- **SQL injection protection** via ActiveRecord +- **XSS protection** com sanitização automática + +### Auditoria + +- **Trackable fields** para monitoramento de login +- **Logs de atividade** para ações administrativas +- **Histórico de importações** com timestamps + +## 📡 API + +### Endpoints Principais + +| Método | Endpoint | Descrição | Auth | +|--------|----------|-----------|------| +| `GET` | `/` | Página inicial | - | +| `POST` | `/users/sign_in` | Login | - | +| `GET` | `/admin/dashboard` | Dashboard admin | Admin | +| `GET` | `/admin/users` | Lista usuários | Admin | +| `POST` | `/admin/imports` | Upload CSV | Admin | +| `GET` | `/users/profile` | Perfil do usuário | User | + +### WebSocket Channels + +- **DashboardChannel** - Métricas em tempo real +- **ImportProgressChannel** - Status de importação + +## 🧪 Testes + +```bash +# Executar testes +bundle exec rspec + +# Com coverage +bundle exec rspec --format documentation + +# Testes específicos +bundle exec rspec spec/models/ +bundle exec rspec spec/services/ +``` + +## 🚀 Deploy + +### Docker + +```bash +# Build da imagem +docker build -t user-management . + +# Executar container +docker run -p 3000:3000 -e RAILS_ENV=production user-management +``` + +### Deploy Manual + +```bash +# Preparar assets +rails assets:precompile + +# Executar migrations +rails db:migrate RAILS_ENV=production + +# Iniciar servidor +rails server -e production +``` + +## 📈 Performance + +### Otimizações Implementadas + +- **Paginação** para grandes datasets +- **Background jobs** para operações pesadas +- **Caching** de consultas frequentes +- **Lazy loading** de relacionamentos +- **Asset pipeline** otimizado + +### Monitoramento + +- Logs estruturados com timestamps +- Métricas de performance no dashboard +- Alertas para operações demoradas + +## 🤝 Contribuição + +### Como Contribuir + +1. Fork o projeto +2. Crie uma branch para sua feature (`git checkout -b feature/nova-funcionalidade`) +3. Commit suas mudanças (`git commit -am 'Adiciona nova funcionalidade'`) +4. Push para a branch (`git push origin feature/nova-funcionalidade`) +5. Crie um Pull Request + +### Padrões de Código + +- Siga as convenções do Ruby/Rails +- Use o Rubocop para linting +- Escreva testes para novas funcionalidades +- Documente APIs e métodos complexos + +### Issues + +Use as **issues** do GitHub para: +- Reportar bugs +- Sugerir funcionalidades +- Discutir melhorias + +## 📄 Licença + +Este projeto está sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais detalhes. + +## 👨‍💻 Autor + +**Lucas Leandro** +- GitHub: [@lucasleandro1](https://github.com/lucasleandro1) +- LinkedIn: [Lucas Leandro](https://linkedin.com/in/lucasleandro) +- Email: lucas@example.com + +--- + +⭐ **Se este projeto foi útil, considere dar uma estrela!** diff --git a/app/assets/builds/.keep b/app/assets/builds/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/builds/application.css b/app/assets/builds/application.css new file mode 100644 index 000000000..fffac1238 --- /dev/null +++ b/app/assets/builds/application.css @@ -0,0 +1 @@ +:root{--primary-color: #007bff;--secondary-color: #6c757d;--success-color: #28a745;--danger-color: #dc3545;--warning-color: #ffc107;--info-color: #17a2b8;--light-color: #f8f9fa;--dark-color: #343a40}body{font-family:"Segoe UI",Tahoma,Geneva,Verdana,sans-serif;background-color:#f8f9fa}.main-content{margin-top:2rem;margin-bottom:2rem}.text-truncate-2{overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical}.avatar-sm{width:32px;height:32px;object-fit:cover}.avatar-md{width:64px;height:64px;object-fit:cover}.avatar-lg{width:128px;height:128px;object-fit:cover}.flash-messages .alert{margin-bottom:1rem;border-radius:.5rem}.spinner-wrapper{display:flex;justify-content:center;align-items:center;min-height:200px}.progress-import{height:2rem}.progress-import .progress-bar{font-size:.875rem;line-height:2rem}.navbar{box-shadow:0 2px 4px rgba(0,0,0,.1)}.navbar .navbar-brand{font-weight:600;font-size:1.25rem}.navbar .navbar-nav .nav-link{font-weight:500;padding:.5rem 1rem}.navbar .navbar-nav .nav-link:hover{background-color:hsla(0,0%,100%,.1);border-radius:.25rem}.navbar .dropdown-menu{border:none;box-shadow:0 4px 6px rgba(0,0,0,.1);border-radius:.5rem}.navbar .navbar-toggler{border:none}.navbar .navbar-toggler:focus{box-shadow:none}.navbar-avatar{width:32px;height:32px;border-radius:50%;object-fit:cover;border:2px solid hsla(0,0%,100%,.2)}.form-container{max-width:500px;margin:0 auto;padding:2rem;background:#fff;border-radius:.75rem;box-shadow:0 4px 6px rgba(0,0,0,.1)}.form-group{margin-bottom:1.5rem}.form-control{border-radius:.5rem;border:1px solid #dee2e6;padding:.75rem 1rem}.form-control:focus{border-color:var(--primary-color);box-shadow:0 0 0 .2rem rgba(0,123,255,.25)}.form-label{font-weight:600;margin-bottom:.5rem;color:#495057}.form-text{font-size:.875rem;color:#6c757d}.form-file .form-file-input{border-radius:.5rem}.form-file .form-file-label{border-radius:.5rem}.form-check{padding-left:1.75rem}.form-check .form-check-input:checked{background-color:var(--primary-color);border-color:var(--primary-color)}.form-check .form-check-label{font-weight:500}.is-invalid{border-color:var(--danger-color)}.is-invalid:focus{border-color:var(--danger-color);box-shadow:0 0 0 .2rem rgba(220,53,69,.25)}.invalid-feedback{display:block;font-size:.875rem;color:var(--danger-color);margin-top:.25rem}.card{border:none;border-radius:.75rem;box-shadow:0 2px 4px rgba(0,0,0,.1);transition:transform .2s ease-in-out,box-shadow .2s ease-in-out}.card:hover{transform:translateY(-2px);box-shadow:0 4px 8px rgba(0,0,0,.15)}.card .card-header{background-color:#fff;border-bottom:1px solid #dee2e6;border-radius:.75rem .75rem 0 0 !important;padding:1.25rem}.card .card-header .card-title{margin-bottom:0;font-weight:600;color:#495057}.card .card-body{padding:1.25rem}.card .card-footer{background-color:#f8f9fa;border-top:1px solid #dee2e6;border-radius:0 0 .75rem .75rem !important;padding:1rem 1.25rem}.stats-card .card-body{display:flex;align-items:center;padding:1.5rem}.stats-card .stats-icon{width:60px;height:60px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:1.5rem;margin-right:1rem}.stats-card .stats-icon.stats-primary{background-color:rgba(0,123,255,.1);color:var(--primary-color)}.stats-card .stats-icon.stats-success{background-color:rgba(40,167,69,.1);color:var(--success-color)}.stats-card .stats-icon.stats-warning{background-color:rgba(255,193,7,.1);color:var(--warning-color)}.stats-card .stats-content{flex:1}.stats-card .stats-content .stats-number{font-size:2rem;font-weight:700;margin-bottom:0;color:#495057}.stats-card .stats-content .stats-label{font-size:.875rem;color:#6c757d;margin-bottom:0}.user-card .user-avatar{width:80px;height:80px;border-radius:50%;object-fit:cover;border:4px solid #fff;box-shadow:0 2px 4px rgba(0,0,0,.1)}.user-card .user-info .user-name{font-size:1.25rem;font-weight:600;margin-bottom:.25rem;color:#495057}.user-card .user-info .user-email{color:#6c757d;margin-bottom:.5rem}.user-card .user-info .user-role{display:inline-block;padding:.25rem .75rem;border-radius:.5rem;font-size:.75rem;font-weight:600;text-transform:uppercase}.user-card .user-info .user-role.role-admin{background-color:rgba(220,53,69,.1);color:var(--danger-color)}.user-card .user-info .user-role.role-user{background-color:rgba(0,123,255,.1);color:var(--primary-color)}.table-responsive{border-radius:.75rem;box-shadow:0 2px 4px rgba(0,0,0,.1);background:#fff}.table{margin-bottom:0}.table thead th{border-top:none;border-bottom:2px solid #dee2e6;font-weight:600;color:#495057;background-color:#f8f9fa;padding:1rem}.table thead th:first-child{border-radius:.75rem 0 0 0}.table thead th:last-child{border-radius:0 .75rem 0 0}.table tbody tr{transition:background-color .2s ease-in-out}.table tbody tr:hover{background-color:rgba(0,123,255,.05)}.table tbody tr:last-child td:first-child{border-radius:0 0 0 .75rem}.table tbody tr:last-child td:last-child{border-radius:0 0 .75rem 0}.table tbody td{padding:1rem;vertical-align:middle;border-top:1px solid #dee2e6}.user-table .user-avatar-cell{width:60px}.user-table .user-avatar-cell .user-avatar{width:40px;height:40px;border-radius:50%;object-fit:cover}.user-table .user-info-cell .user-name{font-weight:600;margin-bottom:.25rem;color:#495057}.user-table .user-info-cell .user-email{font-size:.875rem;color:#6c757d;margin-bottom:0}.user-table .user-role-cell .role-badge{display:inline-block;padding:.25rem .75rem;border-radius:.5rem;font-size:.75rem;font-weight:600;text-transform:uppercase}.user-table .user-role-cell .role-badge.role-admin{background-color:rgba(220,53,69,.1);color:var(--danger-color)}.user-table .user-role-cell .role-badge.role-user{background-color:rgba(0,123,255,.1);color:var(--primary-color)}.user-table .actions-cell{width:150px}.user-table .actions-cell .btn{margin-right:.25rem}.user-table .actions-cell .btn:last-child{margin-right:0}.pagination{justify-content:center;margin-top:2rem}.pagination .page-link{border-radius:.5rem;margin:0 .25rem;border:1px solid #dee2e6;color:var(--primary-color)}.pagination .page-link:hover{background-color:var(--primary-color);border-color:var(--primary-color);color:#fff}.pagination .page-item.active .page-link{background-color:var(--primary-color);border-color:var(--primary-color)}.dashboard-container{min-height:100vh;background-color:#f8f9fa}.dashboard-header{background:#fff;box-shadow:0 2px 4px rgba(0,0,0,.1);padding:1.5rem 0;margin-bottom:2rem}.dashboard-header .dashboard-title{font-size:2rem;font-weight:700;color:#495057;margin-bottom:.5rem}.dashboard-header .dashboard-subtitle{color:#6c757d;margin-bottom:0}.dashboard-stats{margin-bottom:2rem}.dashboard-stats .row .col-md-4{margin-bottom:1rem}.dashboard-content .row .col-lg-8,.dashboard-content .row .col-lg-4{margin-bottom:2rem}.live-indicator{display:inline-flex;align-items:center;font-size:.875rem;color:var(--success-color)}.live-indicator::before{content:"";width:8px;height:8px;background-color:var(--success-color);border-radius:50%;margin-right:.5rem;animation:pulse 2s infinite}@keyframes pulse{0%{transform:scale(0.95);box-shadow:0 0 0 0 rgba(40,167,69,.7)}70%{transform:scale(1);box-shadow:0 0 0 10px rgba(40,167,69,0)}100%{transform:scale(0.95);box-shadow:0 0 0 0 rgba(40,167,69,0)}}.import-progress-section .progress{height:2rem;border-radius:.5rem;background-color:#e9ecef}.import-progress-section .progress .progress-bar{line-height:2rem;font-weight:600}.import-progress-section .import-status{display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem}.import-progress-section .import-status .status-text{font-weight:600;color:#495057}.import-progress-section .import-status .status-percentage{font-size:.875rem;color:#6c757d}.auth-container{min-height:100vh;display:flex;align-items:center;justify-content:center;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);padding:2rem 0}.auth-card{width:100%;max-width:400px;background:#fff;border-radius:1rem;box-shadow:0 10px 25px rgba(0,0,0,.2);padding:2rem}.auth-card .auth-header{text-align:center;margin-bottom:2rem}.auth-card .auth-header .auth-logo{width:80px;height:80px;margin:0 auto 1rem;background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border-radius:50%;display:flex;align-items:center;justify-content:center;color:#fff;font-size:2rem;font-weight:700}.auth-card .auth-header .auth-title{font-size:1.75rem;font-weight:700;color:#495057;margin-bottom:.5rem}.auth-card .auth-header .auth-subtitle{color:#6c757d;margin-bottom:0}.auth-card .auth-form .form-group{margin-bottom:1.5rem}.auth-card .auth-form .form-control{padding:.75rem 1rem;border-radius:.5rem;border:1px solid #dee2e6}.auth-card .auth-form .form-control:focus{border-color:#667eea;box-shadow:0 0 0 .2rem rgba(102,126,234,.25)}.auth-card .auth-form .btn-primary{background:linear-gradient(135deg, #667eea 0%, #764ba2 100%);border:none;padding:.75rem 2rem;border-radius:.5rem;font-weight:600;width:100%}.auth-card .auth-form .btn-primary:hover{background:linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);transform:translateY(-1px)}.auth-card .auth-links{text-align:center;margin-top:1.5rem}.auth-card .auth-links a{color:#667eea;text-decoration:none;font-weight:500}.auth-card .auth-links a:hover{color:#5a6fd8;text-decoration:underline}.auth-card .auth-divider{text-align:center;margin:1.5rem 0;position:relative}.auth-card .auth-divider::before{content:"";position:absolute;top:50%;left:0;right:0;height:1px;background-color:#dee2e6}.auth-card .auth-divider span{background:#fff;padding:0 1rem;color:#6c757d;font-size:.875rem}@media(max-width: 576px){.auth-container{padding:1rem}.auth-card{padding:1.5rem}} diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/stylesheets/_custom.scss b/app/assets/stylesheets/_custom.scss new file mode 100644 index 000000000..6f43bf5bf --- /dev/null +++ b/app/assets/stylesheets/_custom.scss @@ -0,0 +1,76 @@ +// Custom variables +:root { + --primary-color: #007bff; + --secondary-color: #6c757d; + --success-color: #28a745; + --danger-color: #dc3545; + --warning-color: #ffc107; + --info-color: #17a2b8; + --light-color: #f8f9fa; + --dark-color: #343a40; +} + +// Global styles +body { + font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; + background-color: #f8f9fa; +} + +.main-content { + margin-top: 2rem; + margin-bottom: 2rem; +} + +// Utility classes +.text-truncate-2 { + overflow: hidden; + text-overflow: ellipsis; + display: -webkit-box; + -webkit-line-clamp: 2; + line-clamp: 2; // Standard property for compatibility + -webkit-box-orient: vertical; +} + +.avatar-sm { + width: 32px; + height: 32px; + object-fit: cover; +} + +.avatar-md { + width: 64px; + height: 64px; + object-fit: cover; +} + +.avatar-lg { + width: 128px; + height: 128px; + object-fit: cover; +} + +// Flash messages +.flash-messages { + .alert { + margin-bottom: 1rem; + border-radius: 0.5rem; + } +} + +// Loading spinner +.spinner-wrapper { + display: flex; + justify-content: center; + align-items: center; + min-height: 200px; +} + +// Progress bars +.progress-import { + height: 2rem; + + .progress-bar { + font-size: 0.875rem; + line-height: 2rem; + } +} \ No newline at end of file diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 000000000..fe93333c0 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss new file mode 100644 index 000000000..d2f896c35 --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,10 @@ +// Custom styles (Bootstrap loaded via CDN in layout) +@use "custom"; +@use "components/navbar"; +@use "components/forms"; +@use "components/cards"; +@use "components/tables"; + +// Layout styles +@use "layouts/dashboard"; +@use "layouts/authentication"; diff --git a/app/assets/stylesheets/components/_cards.scss b/app/assets/stylesheets/components/_cards.scss new file mode 100644 index 000000000..bc26c8e74 --- /dev/null +++ b/app/assets/stylesheets/components/_cards.scss @@ -0,0 +1,133 @@ +// Card components +.card { + border: none; + border-radius: 0.75rem; + box-shadow: 0 2px 4px rgba(0,0,0,.1); + transition: transform 0.2s ease-in-out, box-shadow 0.2s ease-in-out; + + &:hover { + transform: translateY(-2px); + box-shadow: 0 4px 8px rgba(0,0,0,.15); + } + + .card-header { + background-color: white; + border-bottom: 1px solid #dee2e6; + border-radius: 0.75rem 0.75rem 0 0 !important; + padding: 1.25rem; + + .card-title { + margin-bottom: 0; + font-weight: 600; + color: #495057; + } + } + + .card-body { + padding: 1.25rem; + } + + .card-footer { + background-color: #f8f9fa; + border-top: 1px solid #dee2e6; + border-radius: 0 0 0.75rem 0.75rem !important; + padding: 1rem 1.25rem; + } +} + +// Stats cards +.stats-card { + .card-body { + display: flex; + align-items: center; + padding: 1.5rem; + } + + .stats-icon { + width: 60px; + height: 60px; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + font-size: 1.5rem; + margin-right: 1rem; + + &.stats-primary { + background-color: rgba(0,123,255,0.1); + color: var(--primary-color); + } + + &.stats-success { + background-color: rgba(40,167,69,0.1); + color: var(--success-color); + } + + &.stats-warning { + background-color: rgba(255,193,7,0.1); + color: var(--warning-color); + } + } + + .stats-content { + flex: 1; + + .stats-number { + font-size: 2rem; + font-weight: 700; + margin-bottom: 0; + color: #495057; + } + + .stats-label { + font-size: 0.875rem; + color: #6c757d; + margin-bottom: 0; + } + } +} + +// User card +.user-card { + .user-avatar { + width: 80px; + height: 80px; + border-radius: 50%; + object-fit: cover; + border: 4px solid #fff; + box-shadow: 0 2px 4px rgba(0,0,0,.1); + } + + .user-info { + .user-name { + font-size: 1.25rem; + font-weight: 600; + margin-bottom: 0.25rem; + color: #495057; + } + + .user-email { + color: #6c757d; + margin-bottom: 0.5rem; + } + + .user-role { + display: inline-block; + padding: 0.25rem 0.75rem; + border-radius: 0.5rem; + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + + &.role-admin { + background-color: rgba(220,53,69,0.1); + color: var(--danger-color); + } + + &.role-user { + background-color: rgba(0,123,255,0.1); + color: var(--primary-color); + } + } + } +} \ No newline at end of file diff --git a/app/assets/stylesheets/components/_forms.scss b/app/assets/stylesheets/components/_forms.scss new file mode 100644 index 000000000..6103c9bd9 --- /dev/null +++ b/app/assets/stylesheets/components/_forms.scss @@ -0,0 +1,79 @@ +// Form styles +.form-container { + max-width: 500px; + margin: 0 auto; + padding: 2rem; + background: white; + border-radius: 0.75rem; + box-shadow: 0 4px 6px rgba(0,0,0,.1); +} + +.form-group { + margin-bottom: 1.5rem; +} + +.form-control { + border-radius: 0.5rem; + border: 1px solid #dee2e6; + padding: 0.75rem 1rem; + + &:focus { + border-color: var(--primary-color); + box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25); + } +} + +.form-label { + font-weight: 600; + margin-bottom: 0.5rem; + color: #495057; +} + +.form-text { + font-size: 0.875rem; + color: #6c757d; +} + +// File input styling +.form-file { + .form-file-input { + border-radius: 0.5rem; + } + + .form-file-label { + border-radius: 0.5rem; + } +} + +// Checkbox and radio styling +.form-check { + padding-left: 1.75rem; + + .form-check-input { + &:checked { + background-color: var(--primary-color); + border-color: var(--primary-color); + } + } + + .form-check-label { + font-weight: 500; + } +} + +// Error states +.is-invalid { + border-color: var(--danger-color); + + &:focus { + border-color: var(--danger-color); + box-shadow: 0 0 0 0.2rem rgba(220,53,69,.25); + } +} + +.invalid-feedback { + display: block; + font-size: 0.875rem; + color: var(--danger-color); + margin-top: 0.25rem; +} \ No newline at end of file diff --git a/app/assets/stylesheets/components/_navbar.scss b/app/assets/stylesheets/components/_navbar.scss new file mode 100644 index 000000000..287ea72ef --- /dev/null +++ b/app/assets/stylesheets/components/_navbar.scss @@ -0,0 +1,44 @@ +// Navbar styles +.navbar { + box-shadow: 0 2px 4px rgba(0,0,0,.1); + + .navbar-brand { + font-weight: 600; + font-size: 1.25rem; + } + + .navbar-nav { + .nav-link { + font-weight: 500; + padding: 0.5rem 1rem; + + &:hover { + background-color: rgba(255,255,255,0.1); + border-radius: 0.25rem; + } + } + } + + .dropdown-menu { + border: none; + box-shadow: 0 4px 6px rgba(0,0,0,.1); + border-radius: 0.5rem; + } + + .navbar-toggler { + border: none; + + &:focus { + box-shadow: none; + } + } +} + +// User avatar in navbar +.navbar-avatar { + width: 32px; + height: 32px; + border-radius: 50%; + object-fit: cover; + border: 2px solid rgba(255,255,255,0.2); +} \ No newline at end of file diff --git a/app/assets/stylesheets/components/_tables.scss b/app/assets/stylesheets/components/_tables.scss new file mode 100644 index 000000000..31a800bf2 --- /dev/null +++ b/app/assets/stylesheets/components/_tables.scss @@ -0,0 +1,138 @@ +// Table styles +.table-responsive { + border-radius: 0.75rem; + box-shadow: 0 2px 4px rgba(0,0,0,.1); + background: white; +} + +.table { + margin-bottom: 0; + + thead th { + border-top: none; + border-bottom: 2px solid #dee2e6; + font-weight: 600; + color: #495057; + background-color: #f8f9fa; + padding: 1rem; + + &:first-child { + border-radius: 0.75rem 0 0 0; + } + + &:last-child { + border-radius: 0 0.75rem 0 0; + } + } + + tbody { + tr { + transition: background-color 0.2s ease-in-out; + + &:hover { + background-color: rgba(0,123,255,0.05); + } + + &:last-child { + td:first-child { + border-radius: 0 0 0 0.75rem; + } + + td:last-child { + border-radius: 0 0 0.75rem 0; + } + } + } + + td { + padding: 1rem; + vertical-align: middle; + border-top: 1px solid #dee2e6; + } + } +} + +// User table specific styles +.user-table { + .user-avatar-cell { + width: 60px; + + .user-avatar { + width: 40px; + height: 40px; + border-radius: 50%; + object-fit: cover; + } + } + + .user-info-cell { + .user-name { + font-weight: 600; + margin-bottom: 0.25rem; + color: #495057; + } + + .user-email { + font-size: 0.875rem; + color: #6c757d; + margin-bottom: 0; + } + } + + .user-role-cell { + .role-badge { + display: inline-block; + padding: 0.25rem 0.75rem; + border-radius: 0.5rem; + font-size: 0.75rem; + font-weight: 600; + text-transform: uppercase; + + &.role-admin { + background-color: rgba(220,53,69,0.1); + color: var(--danger-color); + } + + &.role-user { + background-color: rgba(0,123,255,0.1); + color: var(--primary-color); + } + } + } + + .actions-cell { + width: 150px; + + .btn { + margin-right: 0.25rem; + + &:last-child { + margin-right: 0; + } + } + } +} + +// Pagination +.pagination { + justify-content: center; + margin-top: 2rem; + + .page-link { + border-radius: 0.5rem; + margin: 0 0.25rem; + border: 1px solid #dee2e6; + color: var(--primary-color); + + &:hover { + background-color: var(--primary-color); + border-color: var(--primary-color); + color: white; + } + } + + .page-item.active .page-link { + background-color: var(--primary-color); + border-color: var(--primary-color); + } +} \ No newline at end of file diff --git a/app/assets/stylesheets/layouts/_authentication.scss b/app/assets/stylesheets/layouts/_authentication.scss new file mode 100644 index 000000000..2ce37cbd3 --- /dev/null +++ b/app/assets/stylesheets/layouts/_authentication.scss @@ -0,0 +1,130 @@ +// Authentication layout styles +.auth-container { + min-height: 100vh; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + padding: 2rem 0; +} + +.auth-card { + width: 100%; + max-width: 400px; + background: white; + border-radius: 1rem; + box-shadow: 0 10px 25px rgba(0,0,0,.2); + padding: 2rem; + + .auth-header { + text-align: center; + margin-bottom: 2rem; + + .auth-logo { + width: 80px; + height: 80px; + margin: 0 auto 1rem; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: white; + font-size: 2rem; + font-weight: 700; + } + + .auth-title { + font-size: 1.75rem; + font-weight: 700; + color: #495057; + margin-bottom: 0.5rem; + } + + .auth-subtitle { + color: #6c757d; + margin-bottom: 0; + } + } + + .auth-form { + .form-group { + margin-bottom: 1.5rem; + } + + .form-control { + padding: 0.75rem 1rem; + border-radius: 0.5rem; + border: 1px solid #dee2e6; + + &:focus { + border-color: #667eea; + box-shadow: 0 0 0 0.2rem rgba(102,126,234,.25); + } + } + + .btn-primary { + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border: none; + padding: 0.75rem 2rem; + border-radius: 0.5rem; + font-weight: 600; + width: 100%; + + &:hover { + background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%); + transform: translateY(-1px); + } + } + } + + .auth-links { + text-align: center; + margin-top: 1.5rem; + + a { + color: #667eea; + text-decoration: none; + font-weight: 500; + + &:hover { + color: #5a6fd8; + text-decoration: underline; + } + } + } + + .auth-divider { + text-align: center; + margin: 1.5rem 0; + position: relative; + + &::before { + content: ''; + position: absolute; + top: 50%; + left: 0; + right: 0; + height: 1px; + background-color: #dee2e6; + } + + span { + background: white; + padding: 0 1rem; + color: #6c757d; + font-size: 0.875rem; + } + } +} + +// Responsive adjustments +@media (max-width: 576px) { + .auth-container { + padding: 1rem; + } + + .auth-card { + padding: 1.5rem; + } +} \ No newline at end of file diff --git a/app/assets/stylesheets/layouts/_dashboard.scss b/app/assets/stylesheets/layouts/_dashboard.scss new file mode 100644 index 000000000..796a91cb3 --- /dev/null +++ b/app/assets/stylesheets/layouts/_dashboard.scss @@ -0,0 +1,108 @@ +// Dashboard layout styles +.dashboard-container { + min-height: 100vh; + background-color: #f8f9fa; +} + +.dashboard-header { + background: white; + box-shadow: 0 2px 4px rgba(0,0,0,.1); + padding: 1.5rem 0; + margin-bottom: 2rem; + + .dashboard-title { + font-size: 2rem; + font-weight: 700; + color: #495057; + margin-bottom: 0.5rem; + } + + .dashboard-subtitle { + color: #6c757d; + margin-bottom: 0; + } +} + +.dashboard-stats { + margin-bottom: 2rem; + + .row { + .col-md-4 { + margin-bottom: 1rem; + } + } +} + +.dashboard-content { + .row { + .col-lg-8, .col-lg-4 { + margin-bottom: 2rem; + } + } +} + +// Real-time updates indicator +.live-indicator { + display: inline-flex; + align-items: center; + font-size: 0.875rem; + color: var(--success-color); + + &::before { + content: ''; + width: 8px; + height: 8px; + background-color: var(--success-color); + border-radius: 50%; + margin-right: 0.5rem; + animation: pulse 2s infinite; + } +} + +@keyframes pulse { + 0% { + transform: scale(0.95); + box-shadow: 0 0 0 0 rgba(40,167,69, 0.7); + } + + 70% { + transform: scale(1); + box-shadow: 0 0 0 10px rgba(40,167,69, 0); + } + + 100% { + transform: scale(0.95); + box-shadow: 0 0 0 0 rgba(40,167,69, 0); + } +} + +// Import progress section +.import-progress-section { + .progress { + height: 2rem; + border-radius: 0.5rem; + background-color: #e9ecef; + + .progress-bar { + line-height: 2rem; + font-weight: 600; + } + } + + .import-status { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 1rem; + + .status-text { + font-weight: 600; + color: #495057; + } + + .status-percentage { + font-size: 0.875rem; + color: #6c757d; + } + } +} \ No newline at end of file diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 000000000..a40135e37 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,4 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" +import "channels" diff --git a/app/javascript/channels/consumer.js b/app/javascript/channels/consumer.js new file mode 100644 index 000000000..8ec3aad3a --- /dev/null +++ b/app/javascript/channels/consumer.js @@ -0,0 +1,6 @@ +// Action Cable provides the framework to deal with WebSockets in Rails. +// You can generate new channels where WebSocket features live using the `bin/rails generate channel` command. + +import { createConsumer } from "@rails/actioncable" + +export default createConsumer() diff --git a/app/javascript/channels/dashboard_channel.js b/app/javascript/channels/dashboard_channel.js new file mode 100644 index 000000000..55f37c953 --- /dev/null +++ b/app/javascript/channels/dashboard_channel.js @@ -0,0 +1,15 @@ +import consumer from "channels/consumer" + +consumer.subscriptions.create("DashboardChannel", { + connected() { + // Called when the subscription is ready for use on the server + }, + + disconnected() { + // Called when the subscription has been terminated by the server + }, + + received(data) { + // Called when there's incoming data on the websocket for this channel + } +}); diff --git a/app/javascript/channels/import_progress_channel.js b/app/javascript/channels/import_progress_channel.js new file mode 100644 index 000000000..1f42431a5 --- /dev/null +++ b/app/javascript/channels/import_progress_channel.js @@ -0,0 +1,15 @@ +import consumer from "channels/consumer" + +consumer.subscriptions.create("ImportProgressChannel", { + connected() { + // Called when the subscription is ready for use on the server + }, + + disconnected() { + // Called when the subscription has been terminated by the server + }, + + received(data) { + // Called when there's incoming data on the websocket for this channel + } +}); diff --git a/app/javascript/channels/index.js b/app/javascript/channels/index.js new file mode 100644 index 000000000..db1c202eb --- /dev/null +++ b/app/javascript/channels/index.js @@ -0,0 +1,3 @@ +// Import all the channels to be used by Action Cable +import "channels/import_progress_channel" +import "channels/dashboard_channel" diff --git a/app/javascript/controllers/application.js b/app/javascript/controllers/application.js new file mode 100644 index 000000000..1213e85c7 --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/app/javascript/controllers/hello_controller.js b/app/javascript/controllers/hello_controller.js new file mode 100644 index 000000000..5975c0789 --- /dev/null +++ b/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 000000000..1156bf836 --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,4 @@ +// Import and register all your controllers from the importmap via controllers/**/*_controller +import { application } from "controllers/application" +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 000000000..19d490843 --- /dev/null +++ b/config/cache.yml @@ -0,0 +1,16 @@ +default: &default + store_options: + # Cap age of oldest cache entry to fulfill retention policies + # max_age: <%= 60.days.to_i %> + max_size: <%= 256.megabytes %> + namespace: <%= Rails.env %> + +development: + <<: *default + +test: + <<: *default + +production: + database: cache + <<: *default diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 000000000..ee361c033 --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: user_management_app + +# Name of the container image. +image: your-user/user_management_app + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# Remove this section when using multiple web servers and ensure you terminate SSL at your load balancer. +# +# Note: If using Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +proxy: + ssl: true + host: app.example.com + +# Credentials for your image host. +registry: + # Specify the registry server, if you're not using Docker Hub + # server: registry.digitalocean.com / ghcr.io / ... + username: your-user + + # Always use an access token rather than real password when possible. + password: + - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use user_management_app-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole" + + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "user_management_app_storage:/rails/storage" + + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: 3.4.4 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: redis:7.0 +# host: 192.168.0.2 +# port: 6379 +# directories: +# - data:/data diff --git a/config/importmap.rb b/config/importmap.rb new file mode 100644 index 000000000..4f0ed8625 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,9 @@ +# 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_all_from "app/javascript/controllers", under: "controllers" +pin "@rails/actioncable", to: "actioncable.esm.js" +pin_all_from "app/javascript/channels", under: "channels" diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..487324424 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,7 @@ +# 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 diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 000000000..b3076b38f --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,25 @@ +# Be sure to restart your server when you modify this file. + +# Define an application-wide content security policy. +# See the Securing Rails Applications Guide for more information: +# https://guides.rubyonrails.org/security.html#content-security-policy-header + +# Rails.application.configure do +# config.content_security_policy do |policy| +# policy.default_src :self, :https +# policy.font_src :self, :https, :data +# policy.img_src :self, :https, :data +# policy.object_src :none +# policy.script_src :self, :https +# policy.style_src :self, :https +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..c0b717f7e --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# 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, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..3860f659e --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# 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/simple_form.rb b/config/initializers/simple_form.rb new file mode 100644 index 000000000..d26878480 --- /dev/null +++ b/config/initializers/simple_form.rb @@ -0,0 +1,176 @@ +# frozen_string_literal: true +# +# Uncomment this and change the path if necessary to include your own +# components. +# See https://github.com/heartcombo/simple_form#custom-components to know +# more about custom components. +# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f } +# +# Use this setup block to configure all options available in SimpleForm. +SimpleForm.setup do |config| + # Wrappers are used by the form builder to generate a + # complete input. You can remove any component from the + # wrapper, change the order or even add your own to the + # stack. The options given below are used to wrap the + # whole input. + config.wrappers :default, class: :input, + hint_class: :field_with_hint, error_class: :field_with_errors, valid_class: :field_without_errors do |b| + ## Extensions enabled by default + # Any of these extensions can be disabled for a + # given input by passing: `f.input EXTENSION_NAME => false`. + # You can make any of these extensions optional by + # renaming `b.use` to `b.optional`. + + # Determines whether to use HTML5 (:email, :url, ...) + # and required attributes + b.use :html5 + + # Calculates placeholders automatically from I18n + # You can also pass a string as f.input placeholder: "Placeholder" + b.use :placeholder + + ## Optional extensions + # They are disabled unless you pass `f.input EXTENSION_NAME => true` + # to the input. If so, they will retrieve the values from the model + # if any exists. If you want to enable any of those + # extensions by default, you can change `b.optional` to `b.use`. + + # Calculates maxlength from length validations for string inputs + # and/or database column lengths + b.optional :maxlength + + # Calculate minlength from length validations for string inputs + b.optional :minlength + + # Calculates pattern from format validations for string inputs + b.optional :pattern + + # Calculates min and max from length validations for numeric inputs + b.optional :min_max + + # Calculates readonly automatically from readonly attributes + b.optional :readonly + + ## Inputs + # b.use :input, class: 'input', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :label_input + b.use :hint, wrap_with: { tag: :span, class: :hint } + b.use :error, wrap_with: { tag: :span, class: :error } + + ## full_messages_for + # If you want to display the full error message for the attribute, you can + # use the component :full_error, like: + # + # b.use :full_error, wrap_with: { tag: :span, class: :error } + end + + # The default wrapper to be used by the FormBuilder. + config.default_wrapper = :default + + # Define the way to render check boxes / radio buttons with labels. + # Defaults to :nested for bootstrap config. + # inline: input + label + # nested: label > input + config.boolean_style = :nested + + # Default class for buttons + config.button_class = 'btn' + + # Method used to tidy up errors. Specify any Rails Array method. + # :first lists the first message for each field. + # Use :to_sentence to list all errors for each field. + # config.error_method = :first + + # Default tag used for error notification helper. + config.error_notification_tag = :div + + # CSS class to add for error notification helper. + config.error_notification_class = 'error_notification' + + # Series of attempts to detect a default label method for collection. + # config.collection_label_methods = [ :to_label, :name, :title, :to_s ] + + # Series of attempts to detect a default value method for collection. + # config.collection_value_methods = [ :id, :to_s ] + + # You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none. + # config.collection_wrapper_tag = nil + + # You can define the class to use on all collection wrappers. Defaulting to none. + # config.collection_wrapper_class = nil + + # You can wrap each item in a collection of radio/check boxes with a tag, + # defaulting to :span. + # config.item_wrapper_tag = :span + + # You can define a class to use in all item wrappers. Defaulting to none. + # config.item_wrapper_class = nil + + # How the label text should be generated altogether with the required text. + # config.label_text = lambda { |label, required, explicit_label| "#{required} #{label}" } + + # You can define the class to use on all labels. Default is nil. + # config.label_class = nil + + # You can define the default class to be used on forms. Can be overridden + # with `html: { :class }`. Defaulting to none. + # config.default_form_class = nil + + # You can define which elements should obtain additional classes + # config.generate_additional_classes_for = [:wrapper, :label, :input] + + # Whether attributes are required by default (or not). Default is true. + # config.required_by_default = true + + # Tell browsers whether to use the native HTML5 validations (novalidate form option). + # These validations are enabled in SimpleForm's internal config but disabled by default + # in this configuration, which is recommended due to some quirks from different browsers. + # To stop SimpleForm from generating the novalidate option, enabling the HTML5 validations, + # change this configuration to true. + config.browser_validations = false + + # Custom mappings for input types. This should be a hash containing a regexp + # to match as key, and the input type that will be used when the field name + # matches the regexp as value. + # config.input_mappings = { /count/ => :integer } + + # Custom wrappers for input types. This should be a hash containing an input + # type as key and the wrapper that will be used for all inputs with specified type. + # config.wrapper_mappings = { string: :prepend } + + # Namespaces where SimpleForm should look for custom input classes that + # override default inputs. + # config.custom_inputs_namespaces << "CustomInputs" + + # Default priority for time_zone inputs. + # config.time_zone_priority = nil + + # Default priority for country inputs. + # config.country_priority = nil + + # When false, do not use translations for labels. + # config.translate_labels = true + + # Automatically discover new inputs in Rails' autoload path. + # config.inputs_discovery = true + + # Cache SimpleForm inputs discovery + # config.cache_discovery = !Rails.env.development? + + # Default class for inputs + # config.input_class = nil + + # Define the default class of the input wrapper of the boolean input. + config.boolean_label_class = 'checkbox' + + # Defines if the default input wrapper class should be included in radio + # collection wrappers. + # config.include_default_input_wrapper_class = true + + # Defines which i18n scope will be used in Simple Form. + # config.i18n_scope = 'simple_form' + + # Defines validation classes to the input_field. By default it's nil. + # config.input_field_valid_class = 'is-valid' + # config.input_field_error_class = 'is-invalid' +end diff --git a/config/initializers/simple_form_bootstrap.rb b/config/initializers/simple_form_bootstrap.rb new file mode 100644 index 000000000..7ec2ec6d3 --- /dev/null +++ b/config/initializers/simple_form_bootstrap.rb @@ -0,0 +1,372 @@ +# frozen_string_literal: true + +# These defaults are defined and maintained by the community at +# https://github.com/heartcombo/simple_form-bootstrap +# Please submit feedback, changes and tests only there. + +# Uncomment this and change the path if necessary to include your own +# components. +# See https://github.com/heartcombo/simple_form#custom-components +# to know more about custom components. +# Dir[Rails.root.join('lib/components/**/*.rb')].each { |f| require f } + +# Use this setup block to configure all options available in SimpleForm. +SimpleForm.setup do |config| + # Default class for buttons + config.button_class = 'btn' + + # Define the default class of the input wrapper of the boolean input. + config.boolean_label_class = 'form-check-label' + + # How the label text should be generated altogether with the required text. + config.label_text = lambda { |label, required, explicit_label| "#{label} #{required}" } + + # Define the way to render check boxes / radio buttons with labels. + config.boolean_style = :inline + + # You can wrap each item in a collection of radio/check boxes with a tag + config.item_wrapper_tag = :div + + # Defines if the default input wrapper class should be included in radio + # collection wrappers. + config.include_default_input_wrapper_class = false + + # CSS class to add for error notification helper. + config.error_notification_class = 'alert alert-danger' + + # Method used to tidy up errors. Specify any Rails Array method. + # :first lists the first message for each field. + # :to_sentence to list all errors for each field. + config.error_method = :to_sentence + + # add validation classes to `input_field` + config.input_field_error_class = 'is-invalid' + config.input_field_valid_class = 'is-valid' + + + # vertical forms + # + # vertical default_wrapper + config.wrappers :vertical_form, class: 'mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :pattern + b.optional :min_max + b.optional :readonly + b.use :label, class: 'form-label' + b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical input for boolean + config.wrappers :vertical_boolean, tag: 'fieldset', class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :form_check_wrapper, class: 'form-check' do |bb| + bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + bb.use :label, class: 'form-check-label' + bb.use :full_error, wrap_with: { class: 'invalid-feedback' } + bb.use :hint, wrap_with: { class: 'form-text' } + end + end + + # vertical input for radio buttons and check boxes + config.wrappers :vertical_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', tag: 'fieldset', class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| + ba.use :label_text + end + b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical input for inline radio buttons and check boxes + config.wrappers :vertical_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', tag: 'fieldset', class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :legend_tag, tag: 'legend', class: 'col-form-label pt-0' do |ba| + ba.use :label_text + end + b.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical file input + config.wrappers :vertical_file, class: 'mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :readonly + b.use :label, class: 'form-label' + b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical select input + config.wrappers :vertical_select, class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'form-label' + b.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical multi select + config.wrappers :vertical_multi_select, class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'form-label' + b.wrapper class: 'd-flex flex-row justify-content-between align-items-center' do |ba| + ba.use :input, class: 'form-select mx-1', error_class: 'is-invalid', valid_class: 'is-valid' + end + b.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # vertical range input + config.wrappers :vertical_range, class: 'mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :readonly + b.optional :step + b.use :label, class: 'form-label' + b.use :input, class: 'form-range', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + + # horizontal forms + # + # horizontal default_wrapper + config.wrappers :horizontal_form, class: 'row mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :pattern + b.optional :min_max + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal input for boolean + config.wrappers :horizontal_boolean, class: 'row mb-3' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :grid_wrapper, class: 'col-sm-9 offset-sm-3' do |wr| + wr.wrapper :form_check_wrapper, class: 'form-check' do |bb| + bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + bb.use :label, class: 'form-check-label' + bb.use :full_error, wrap_with: { class: 'invalid-feedback' } + bb.use :hint, wrap_with: { class: 'form-text' } + end + end + end + + # horizontal input for radio buttons and check boxes + config.wrappers :horizontal_collection, item_wrapper_class: 'form-check', item_label_class: 'form-check-label', class: 'row mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label pt-0' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal input for inline radio buttons and check boxes + config.wrappers :horizontal_collection_inline, item_wrapper_class: 'form-check form-check-inline', item_label_class: 'form-check-label', class: 'row mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label pt-0' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal file input + config.wrappers :horizontal_file, class: 'row mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal select input + config.wrappers :horizontal_select, class: 'row mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal multi select + config.wrappers :horizontal_multi_select, class: 'row mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :label, class: 'col-sm-3 col-form-label' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.wrapper class: 'd-flex flex-row justify-content-between align-items-center' do |bb| + bb.use :input, class: 'form-select mx-1', error_class: 'is-invalid', valid_class: 'is-valid' + end + ba.use :full_error, wrap_with: { class: 'invalid-feedback d-block' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + # horizontal range input + config.wrappers :horizontal_range, class: 'row mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :readonly + b.optional :step + b.use :label, class: 'col-sm-3 col-form-label pt-0' + b.wrapper :grid_wrapper, class: 'col-sm-9' do |ba| + ba.use :input, class: 'form-range', error_class: 'is-invalid', valid_class: 'is-valid' + ba.use :full_error, wrap_with: { class: 'invalid-feedback' } + ba.use :hint, wrap_with: { class: 'form-text' } + end + end + + + # inline forms + # + # inline default_wrapper + config.wrappers :inline_form, class: 'col-12' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :pattern + b.optional :min_max + b.optional :readonly + b.use :label, class: 'visually-hidden' + + b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :error, wrap_with: { class: 'invalid-feedback' } + b.optional :hint, wrap_with: { class: 'form-text' } + end + + # inline input for boolean + config.wrappers :inline_boolean, class: 'col-12' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :form_check_wrapper, class: 'form-check' do |bb| + bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + bb.use :label, class: 'form-check-label' + bb.use :error, wrap_with: { class: 'invalid-feedback' } + bb.optional :hint, wrap_with: { class: 'form-text' } + end + end + + + # bootstrap custom forms + # + # custom input switch for boolean + config.wrappers :custom_boolean_switch, class: 'mb-3' do |b| + b.use :html5 + b.optional :readonly + b.wrapper :form_check_wrapper, tag: 'div', class: 'form-check form-switch' do |bb| + bb.use :input, class: 'form-check-input', error_class: 'is-invalid', valid_class: 'is-valid' + bb.use :label, class: 'form-check-label' + bb.use :full_error, wrap_with: { tag: 'div', class: 'invalid-feedback' } + bb.use :hint, wrap_with: { class: 'form-text' } + end + end + + + # Input Group - custom component + # see example app and config at https://github.com/heartcombo/simple_form-bootstrap + config.wrappers :input_group, class: 'mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :pattern + b.optional :min_max + b.optional :readonly + b.use :label, class: 'form-label' + b.wrapper :input_group_tag, class: 'input-group' do |ba| + ba.optional :prepend + ba.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + ba.optional :append + ba.use :full_error, wrap_with: { class: 'invalid-feedback' } + end + b.use :hint, wrap_with: { class: 'form-text' } + end + + + # Floating Labels form + # + # floating labels default_wrapper + config.wrappers :floating_labels_form, class: 'form-floating mb-3' do |b| + b.use :html5 + b.use :placeholder + b.optional :maxlength + b.optional :minlength + b.optional :pattern + b.optional :min_max + b.optional :readonly + b.use :input, class: 'form-control', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :label + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + # custom multi select + config.wrappers :floating_labels_select, class: 'form-floating mb-3' do |b| + b.use :html5 + b.optional :readonly + b.use :input, class: 'form-select', error_class: 'is-invalid', valid_class: 'is-valid' + b.use :label + b.use :full_error, wrap_with: { class: 'invalid-feedback' } + b.use :hint, wrap_with: { class: 'form-text' } + end + + + # The default wrapper to be used by the FormBuilder. + config.default_wrapper = :vertical_form + + # Custom wrappers for input types. This should be a hash containing an input + # type as key and the wrapper that will be used for all inputs with specified type. + config.wrapper_mappings = { + boolean: :vertical_boolean, + check_boxes: :vertical_collection, + date: :vertical_multi_select, + datetime: :vertical_multi_select, + file: :vertical_file, + radio_buttons: :vertical_collection, + range: :vertical_range, + time: :vertical_multi_select, + select: :vertical_select + } +end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..6c349ae5e --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/config/locales/simple_form.en.yml b/config/locales/simple_form.en.yml new file mode 100644 index 000000000..237438334 --- /dev/null +++ b/config/locales/simple_form.en.yml @@ -0,0 +1,31 @@ +en: + simple_form: + "yes": 'Yes' + "no": 'No' + required: + text: 'required' + mark: '*' + # You can uncomment the line below if you need to overwrite the whole required html. + # When using html, text and mark won't be used. + # html: '*' + error_notification: + default_message: "Please review the problems below:" + # Examples + # labels: + # defaults: + # password: 'Password' + # user: + # new: + # email: 'E-mail to sign in.' + # edit: + # email: 'E-mail.' + # hints: + # defaults: + # username: 'User name to sign in.' + # password: 'No special characters, please.' + # include_blanks: + # defaults: + # age: 'Rather not say' + # prompts: + # defaults: + # age: 'Select your age' diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..a248513b2 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,41 @@ +# This configuration file will be evaluated by Puma. The top-level methods that +# are invoked here are part of Puma's configuration DSL. For more information +# about methods provided by the DSL, see https://puma.io/puma/Puma/DSL.html. +# +# Puma starts a configurable number of processes (workers) and each process +# serves each request in a thread from an internal thread pool. +# +# You can control the number of workers using ENV["WEB_CONCURRENCY"]. You +# should only set this value when you want to run 2 or more workers. The +# default is already 1. +# +# The ideal number of threads per worker depends both on how much time the +# application spends waiting for IO operations and on how much you wish to +# prioritize throughput over latency. +# +# As a rule of thumb, increasing the number of threads will increase how much +# traffic a given process can handle (throughput), but due to CRuby's +# Global VM Lock (GVL) it has diminishing returns and will degrade the +# response time (latency) of the application. +# +# The default is set to 3 threads as it's deemed a decent compromise between +# throughput and latency for the average Rails application. +# +# Any libraries that use a connection pool or another resource pool should +# be configured to provide at least as many connections as the number of +# threads. This includes Active Record's `pool` parameter in `database.yml`. +threads_count = ENV.fetch("RAILS_MAX_THREADS", 3) +threads threads_count, threads_count + +# Specifies the `port` that Puma will listen on to receive requests; default is 3000. +port ENV.fetch("PORT", 3000) + +# Allow puma to be restarted by `bin/rails restart` command. +plugin :tmp_restart + +# Run the Solid Queue supervisor inside of Puma for single-server deployments +plugin :solid_queue if ENV["SOLID_QUEUE_IN_PUMA"] + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..4942ab669 --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,34 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# Use bin/rails credentials:edit to set the Azure Storage secret (as azure_storage:storage_access_key) +# microsoft: +# service: AzureStorage +# storage_account_name: your_account_name +# storage_access_key: <%= Rails.application.credentials.dig(:azure_storage, :storage_access_key) %> +# container: your_container_name-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/lib/templates/erb/scaffold/_form.html.erb b/lib/templates/erb/scaffold/_form.html.erb new file mode 100644 index 000000000..106b71eef --- /dev/null +++ b/lib/templates/erb/scaffold/_form.html.erb @@ -0,0 +1,15 @@ +<%# frozen_string_literal: true %> +<%%= simple_form_for(@<%= singular_table_name %>) do |f| %> + <%%= f.error_notification %> + <%%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %> + +
+ <%- attributes.each do |attribute| -%> + <%%= f.<%= attribute.reference? ? :association : :input %> :<%= attribute.name %> %> + <%- end -%> +
+ +
+ <%%= f.button :submit %> +
+<%% end %> diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..628434c3d --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,5 @@ +FactoryBot.define do + factory :user do + + end +end diff --git a/spec/helpers/admin/dashboard_helper_spec.rb b/spec/helpers/admin/dashboard_helper_spec.rb new file mode 100644 index 000000000..628ccf824 --- /dev/null +++ b/spec/helpers/admin/dashboard_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the Admin::DashboardHelper. For example: +# +# describe Admin::DashboardHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe Admin::DashboardHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/admin/users_helper_spec.rb b/spec/helpers/admin/users_helper_spec.rb new file mode 100644 index 000000000..f26854ec3 --- /dev/null +++ b/spec/helpers/admin/users_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the Admin::UsersHelper. For example: +# +# describe Admin::UsersHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe Admin::UsersHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/home_helper_spec.rb b/spec/helpers/home_helper_spec.rb new file mode 100644 index 000000000..e537d8d9a --- /dev/null +++ b/spec/helpers/home_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the HomeHelper. For example: +# +# describe HomeHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe HomeHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/helpers/users_helper_spec.rb b/spec/helpers/users_helper_spec.rb new file mode 100644 index 000000000..b2e34440e --- /dev/null +++ b/spec/helpers/users_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the UsersHelper. For example: +# +# describe UsersHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe UsersHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 000000000..47a31bb43 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/requests/admin/dashboard_spec.rb b/spec/requests/admin/dashboard_spec.rb new file mode 100644 index 000000000..9c39b690a --- /dev/null +++ b/spec/requests/admin/dashboard_spec.rb @@ -0,0 +1,11 @@ +require 'rails_helper' + +RSpec.describe "Admin::Dashboards", type: :request do + describe "GET /index" do + it "returns http success" do + get "/admin/dashboard/index" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/requests/admin/users_spec.rb b/spec/requests/admin/users_spec.rb new file mode 100644 index 000000000..c28b1b88e --- /dev/null +++ b/spec/requests/admin/users_spec.rb @@ -0,0 +1,60 @@ +require 'rails_helper' + +RSpec.describe "Admin::Users", type: :request do + describe "GET /index" do + it "returns http success" do + get "/admin/users/index" + expect(response).to have_http_status(:success) + end + end + + describe "GET /show" do + it "returns http success" do + get "/admin/users/show" + expect(response).to have_http_status(:success) + end + end + + describe "GET /new" do + it "returns http success" do + get "/admin/users/new" + expect(response).to have_http_status(:success) + end + end + + describe "GET /create" do + it "returns http success" do + get "/admin/users/create" + expect(response).to have_http_status(:success) + end + end + + describe "GET /edit" do + it "returns http success" do + get "/admin/users/edit" + expect(response).to have_http_status(:success) + end + end + + describe "GET /update" do + it "returns http success" do + get "/admin/users/update" + expect(response).to have_http_status(:success) + end + end + + describe "GET /destroy" do + it "returns http success" do + get "/admin/users/destroy" + expect(response).to have_http_status(:success) + end + end + + describe "GET /toggle_role" do + it "returns http success" do + get "/admin/users/toggle_role" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/requests/home_spec.rb b/spec/requests/home_spec.rb new file mode 100644 index 000000000..fdbd64231 --- /dev/null +++ b/spec/requests/home_spec.rb @@ -0,0 +1,11 @@ +require 'rails_helper' + +RSpec.describe "Homes", type: :request do + describe "GET /index" do + it "returns http success" do + get "/home/index" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/requests/users_spec.rb b/spec/requests/users_spec.rb new file mode 100644 index 000000000..d0a99f7d1 --- /dev/null +++ b/spec/requests/users_spec.rb @@ -0,0 +1,32 @@ +require 'rails_helper' + +RSpec.describe "Users", type: :request do + describe "GET /show" do + it "returns http success" do + get "/users/show" + expect(response).to have_http_status(:success) + end + end + + describe "GET /edit" do + it "returns http success" do + get "/users/edit" + expect(response).to have_http_status(:success) + end + end + + describe "GET /update" do + it "returns http success" do + get "/users/update" + expect(response).to have_http_status(:success) + end + end + + describe "GET /destroy" do + it "returns http success" do + get "/users/destroy" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/spec/views/admin/dashboard/index.html.erb_spec.rb b/spec/views/admin/dashboard/index.html.erb_spec.rb new file mode 100644 index 000000000..d9dbe041a --- /dev/null +++ b/spec/views/admin/dashboard/index.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "dashboard/index.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/create.html.erb_spec.rb b/spec/views/admin/users/create.html.erb_spec.rb new file mode 100644 index 000000000..e3141c566 --- /dev/null +++ b/spec/views/admin/users/create.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/create.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/destroy.html.erb_spec.rb b/spec/views/admin/users/destroy.html.erb_spec.rb new file mode 100644 index 000000000..c5955f41c --- /dev/null +++ b/spec/views/admin/users/destroy.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/destroy.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/edit.html.erb_spec.rb b/spec/views/admin/users/edit.html.erb_spec.rb new file mode 100644 index 000000000..7d1e93697 --- /dev/null +++ b/spec/views/admin/users/edit.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/edit.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/index.html.erb_spec.rb b/spec/views/admin/users/index.html.erb_spec.rb new file mode 100644 index 000000000..3e5309f6d --- /dev/null +++ b/spec/views/admin/users/index.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/index.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/new.html.erb_spec.rb b/spec/views/admin/users/new.html.erb_spec.rb new file mode 100644 index 000000000..47b47d3d0 --- /dev/null +++ b/spec/views/admin/users/new.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/new.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/show.html.erb_spec.rb b/spec/views/admin/users/show.html.erb_spec.rb new file mode 100644 index 000000000..34ad7a422 --- /dev/null +++ b/spec/views/admin/users/show.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/show.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/toggle_role.html.erb_spec.rb b/spec/views/admin/users/toggle_role.html.erb_spec.rb new file mode 100644 index 000000000..40fd77734 --- /dev/null +++ b/spec/views/admin/users/toggle_role.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/toggle_role.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/admin/users/update.html.erb_spec.rb b/spec/views/admin/users/update.html.erb_spec.rb new file mode 100644 index 000000000..7d2a4b9c9 --- /dev/null +++ b/spec/views/admin/users/update.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/update.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/home/index.html.erb_spec.rb b/spec/views/home/index.html.erb_spec.rb new file mode 100644 index 000000000..75bb045bc --- /dev/null +++ b/spec/views/home/index.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "home/index.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/users/destroy.html.erb_spec.rb b/spec/views/users/destroy.html.erb_spec.rb new file mode 100644 index 000000000..c5955f41c --- /dev/null +++ b/spec/views/users/destroy.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/destroy.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/users/edit.html.erb_spec.rb b/spec/views/users/edit.html.erb_spec.rb new file mode 100644 index 000000000..7d1e93697 --- /dev/null +++ b/spec/views/users/edit.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/edit.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/users/show.html.erb_spec.rb b/spec/views/users/show.html.erb_spec.rb new file mode 100644 index 000000000..34ad7a422 --- /dev/null +++ b/spec/views/users/show.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/show.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/spec/views/users/update.html.erb_spec.rb b/spec/views/users/update.html.erb_spec.rb new file mode 100644 index 000000000..7d2a4b9c9 --- /dev/null +++ b/spec/views/users/update.html.erb_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "users/update.html.erb", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 000000000..e69de29bb From 2e5b5d01222440c3ff6df7c6fe4c7490388f20f0 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Fri, 7 Nov 2025 14:34:03 -0300 Subject: [PATCH 11/20] adjiust readme --- .kamal/hooks/docker-setup.sample | 3 + .kamal/hooks/post-app-boot.sample | 3 + .kamal/hooks/post-deploy.sample | 14 +++ .kamal/hooks/post-proxy-reboot.sample | 3 + .kamal/hooks/pre-app-boot.sample | 3 + .kamal/hooks/pre-build.sample | 51 +++++++++++ .kamal/hooks/pre-connect.sample | 47 ++++++++++ .kamal/hooks/pre-deploy.sample | 122 ++++++++++++++++++++++++++ .kamal/hooks/pre-proxy-reboot.sample | 3 + .ruby-version | 1 + tmp/.keep | 0 tmp/pids/.keep | 0 12 files changed, 250 insertions(+) create mode 100755 .kamal/hooks/docker-setup.sample create mode 100755 .kamal/hooks/post-app-boot.sample create mode 100755 .kamal/hooks/post-deploy.sample create mode 100755 .kamal/hooks/post-proxy-reboot.sample create mode 100755 .kamal/hooks/pre-app-boot.sample create mode 100755 .kamal/hooks/pre-build.sample create mode 100755 .kamal/hooks/pre-connect.sample create mode 100755 .kamal/hooks/pre-deploy.sample create mode 100755 .kamal/hooks/pre-proxy-reboot.sample create mode 100644 .ruby-version create mode 100644 tmp/.keep create mode 100644 tmp/pids/.keep diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 000000000..2fb07d7d7 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 000000000..70f9c4bc9 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 000000000..fd364c2a7 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/bin/sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 000000000..1435a677f --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 000000000..45f735504 --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 000000000..c5a55678b --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/bin/sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 000000000..77744bdca --- /dev/null +++ b/.kamal/hooks/pre-connect.sample @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby + +# A sample pre-connect check +# +# Warms DNS before connecting to hosts in parallel +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +hosts = ENV["KAMAL_HOSTS"].split(",") +results = nil +max = 3 + +elapsed = Benchmark.realtime do + results = hosts.map do |host| + Thread.new do + tries = 1 + + begin + Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) + rescue SocketError + if tries < max + puts "Retrying DNS warmup: #{host}" + tries += 1 + sleep rand + retry + else + puts "DNS warmup failed: #{host}" + host + end + end + + tries + end + end.map(&:value) +end + +retries = results.sum - hosts.size +nopes = results.count { |r| r == max } + +puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/.kamal/hooks/pre-deploy.sample b/.kamal/hooks/pre-deploy.sample new file mode 100755 index 000000000..05b3055b7 --- /dev/null +++ b/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby + +# A sample pre-deploy hook +# +# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. +# +# Fails unless the combined status is "success" +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_COMMAND +# KAMAL_SUBCOMMAND +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +# Only check the build status for production deployments +if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" + exit 0 +end + +require "bundler/inline" + +# true = install gems so this is fast on repeat invocations +gemfile(true, quiet: true) do + source "https://rubygems.org" + + gem "octokit" + gem "faraday-retry" +end + +MAX_ATTEMPTS = 72 +ATTEMPTS_GAP = 10 + +def exit_with_error(message) + $stderr.puts message + exit 1 +end + +class GithubStatusChecks + attr_reader :remote_url, :git_sha, :github_client, :combined_status + + def initialize + @remote_url = github_repo_from_remote_url + @git_sha = `git rev-parse HEAD`.strip + @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) + refresh! + end + + def refresh! + @combined_status = github_client.combined_status(remote_url, git_sha) + end + + def state + combined_status[:state] + end + + def first_status_url + first_status = combined_status[:statuses].find { |status| status[:state] == state } + first_status && first_status[:target_url] + end + + def complete_count + combined_status[:statuses].count { |status| status[:state] != "pending"} + end + + def total_count + combined_status[:statuses].count + end + + def current_status + if total_count > 0 + "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." + else + "Build not started..." + end + end + + private + def github_repo_from_remote_url + url = `git config --get remote.origin.url`.strip.delete_suffix(".git") + if url.start_with?("https://github.com/") + url.delete_prefix("https://github.com/") + elsif url.start_with?("git@github.com:") + url.delete_prefix("git@github.com:") + else + url + end + end +end + + +$stdout.sync = true + +begin + puts "Checking build status..." + + attempts = 0 + checks = GithubStatusChecks.new + + loop do + case checks.state + when "success" + puts "Checks passed, see #{checks.first_status_url}" + exit 0 + when "failure" + exit_with_error "Checks failed, see #{checks.first_status_url}" + when "pending" + attempts += 1 + end + + exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS + + puts checks.current_status + sleep(ATTEMPTS_GAP) + checks.refresh! + end +rescue Octokit::NotFound + exit_with_error "Build status could not be found" +end diff --git a/.kamal/hooks/pre-proxy-reboot.sample b/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 000000000..061f8059e --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 000000000..f9892605c --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.4.4 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 From 50bd5ded233476b412dc0644e9c7b5d5170f5d69 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Fri, 7 Nov 2025 14:34:30 -0300 Subject: [PATCH 12/20] adjiust readme --- README.md | 153 ------------------------------------------------------ 1 file changed, 153 deletions(-) diff --git a/README.md b/README.md index c835fd819..4161686de 100644 --- a/README.md +++ b/README.md @@ -108,29 +108,6 @@ yarn build --watch http://localhost:3000 ``` -## ⚙️ Configuração - -### Variáveis de Ambiente - -Crie um arquivo `.env` na raiz do projeto: - -```env -# Database -DATABASE_URL=sqlite3:storage/development.sqlite3 - -# Redis (para Action Cable em produção) -REDIS_URL=redis://localhost:6379/0 - -# Email (opcional, para funcionalidades do Devise) -SMTP_ADDRESS=smtp.gmail.com -SMTP_PORT=587 -SMTP_USERNAME=your-email@gmail.com -SMTP_PASSWORD=your-app-password - -# Segurança -SECRET_KEY_BASE=your-secret-key-base -``` - ### Usuários de Teste Após rodar `rails db:seed`, você terá acesso a: @@ -213,44 +190,6 @@ app/ └── admin/ ``` -### Service Layer - -O projeto utiliza **Service Objects** para encapsular lógica de negócio: - -```ruby -# Exemplo de uso -result = UserManagementService.create_user(user_params) -if result.success? - redirect_to user_path(result.data) -else - flash[:error] = result.error -end -``` - -### Background Jobs - -Processamento assíncrono para operações pesadas: - -```ruby -# Importação CSV -UserImportJob.perform_later(import_id, current_user_id) -``` - -### Real-time Updates - -WebSockets para atualizações automáticas: - -```javascript -// Dashboard em tempo real -import consumer from "./consumer" - -consumer.subscriptions.create("DashboardChannel", { - received(data) { - updateDashboardMetrics(data) - } -}) -``` - ## 🛡️ Segurança ### Implementações de Segurança @@ -287,96 +226,4 @@ consumer.subscriptions.create("DashboardChannel", { - **DashboardChannel** - Métricas em tempo real - **ImportProgressChannel** - Status de importação -## 🧪 Testes - -```bash -# Executar testes -bundle exec rspec - -# Com coverage -bundle exec rspec --format documentation - -# Testes específicos -bundle exec rspec spec/models/ -bundle exec rspec spec/services/ -``` - -## 🚀 Deploy - -### Docker - -```bash -# Build da imagem -docker build -t user-management . - -# Executar container -docker run -p 3000:3000 -e RAILS_ENV=production user-management -``` - -### Deploy Manual - -```bash -# Preparar assets -rails assets:precompile - -# Executar migrations -rails db:migrate RAILS_ENV=production - -# Iniciar servidor -rails server -e production -``` - -## 📈 Performance - -### Otimizações Implementadas - -- **Paginação** para grandes datasets -- **Background jobs** para operações pesadas -- **Caching** de consultas frequentes -- **Lazy loading** de relacionamentos -- **Asset pipeline** otimizado - -### Monitoramento - -- Logs estruturados com timestamps -- Métricas de performance no dashboard -- Alertas para operações demoradas - -## 🤝 Contribuição - -### Como Contribuir - -1. Fork o projeto -2. Crie uma branch para sua feature (`git checkout -b feature/nova-funcionalidade`) -3. Commit suas mudanças (`git commit -am 'Adiciona nova funcionalidade'`) -4. Push para a branch (`git push origin feature/nova-funcionalidade`) -5. Crie um Pull Request - -### Padrões de Código - -- Siga as convenções do Ruby/Rails -- Use o Rubocop para linting -- Escreva testes para novas funcionalidades -- Documente APIs e métodos complexos - -### Issues - -Use as **issues** do GitHub para: -- Reportar bugs -- Sugerir funcionalidades -- Discutir melhorias - -## 📄 Licença - -Este projeto está sob a licença MIT. Veja o arquivo [LICENSE](LICENSE) para mais detalhes. - -## 👨‍💻 Autor - -**Lucas Leandro** -- GitHub: [@lucasleandro1](https://github.com/lucasleandro1) -- LinkedIn: [Lucas Leandro](https://linkedin.com/in/lucasleandro) -- Email: lucas@example.com - ---- - ⭐ **Se este projeto foi útil, considere dar uma estrela!** From 4aaeefec0c34113074151604a0593d5af4f3d06c Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Mon, 10 Nov 2025 17:56:11 -0300 Subject: [PATCH 13/20] create docker and refactor import users --- Gemfile | 3 +- Gemfile.lock | 29 ++- README.md | 55 +---- app/controllers/admin/imports_controller.rb | 1 - app/jobs/user_import_job.rb | 8 +- app/models/concerns/dashboard_broadcaster.rb | 2 +- app/models/import.rb | 33 ++- app/models/user.rb | 11 +- app/services/dashboard_stats_service.rb | 4 +- app/services/user_management_service.rb | 2 - app/views/admin/dashboard/index.html.erb | 71 ++---- app/views/admin/imports/create.html.erb | 25 +-- app/views/admin/imports/index.html.erb | 5 +- app/views/admin/imports/show.html.erb | 56 ++--- app/views/admin/users/edit.html.erb | 20 +- app/views/admin/users/index.html.erb | 20 +- app/views/admin/users/new.html.erb | 136 +----------- app/views/admin/users/show.html.erb | 11 +- app/views/devise/registrations/new.html.erb | 6 +- app/views/devise/sessions/new.html.erb | 2 +- app/views/home/index.html.erb | 22 -- app/views/layouts/application.html.erb | 2 - app/views/shared/_footer.html.erb | 20 -- app/views/shared/_navbar.html.erb | 19 +- app/views/users/edit.html.erb | 1 - app/views/users/show.html.erb | 36 ---- config/environments/development.rb | 3 + config/environments/production.rb | 4 +- config/initializers/sidekiq.rb | 25 +++ .../20251110195347_add_counters_to_imports.rb | 6 + ...0195421_change_progress_type_in_imports.rb | 7 + db/schema.rb | 18 +- docker-compose.yml | 91 ++++++++ spec/examples.txt | 32 +++ spec/factories/users.rb | 14 +- spec/fixtures/users_valid.csv | 11 + spec/models/user_spec.rb | 203 +++++++++++++++++- spec/rails_helper.rb | 67 ++++++ spec/spec_helper.rb | 86 ++++++++ 39 files changed, 661 insertions(+), 506 deletions(-) delete mode 100644 app/views/shared/_footer.html.erb create mode 100644 config/initializers/sidekiq.rb create mode 100644 db/migrate/20251110195347_add_counters_to_imports.rb create mode 100644 db/migrate/20251110195421_change_progress_type_in_imports.rb create mode 100644 docker-compose.yml create mode 100644 spec/examples.txt create mode 100644 spec/fixtures/users_valid.csv create mode 100644 spec/rails_helper.rb create mode 100644 spec/spec_helper.rb diff --git a/Gemfile b/Gemfile index 091e73f42..b15ca93dd 100644 --- a/Gemfile +++ b/Gemfile @@ -35,7 +35,8 @@ gem "roo", "~> 2.9" gem "csv" # For background job processing -gem "sidekiq", "~> 7.0" +gem "sidekiq", "~> 6.5" +gem "redis", "~> 4.8" # For authorization (CanCanCan) gem "cancancan" diff --git a/Gemfile.lock b/Gemfile.lock index 35320aa9c..edd57044f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -276,14 +276,14 @@ GEM nio4r (~> 2.0) raabro (1.4.0) racc (1.8.1) - rack (3.2.4) - rack-session (2.1.1) - base64 (>= 0.1.0) - rack (>= 3.0.0) + rack (2.2.21) + rack-session (1.0.2) + rack (< 3) rack-test (2.2.0) rack (>= 1.3) - rackup (2.2.1) - rack (>= 3) + rackup (1.0.1) + rack (< 3) + webrick rails (8.0.4) actioncable (= 8.0.4) actionmailbox (= 8.0.4) @@ -320,8 +320,7 @@ GEM erb psych (>= 4.0.0) tsort - redis-client (0.26.1) - connection_pool + redis (4.8.1) regexp_parser (2.11.3) reline (0.6.2) io-console (~> 0.5) @@ -403,12 +402,10 @@ GEM websocket (~> 1.0) shoulda-matchers (7.0.1) activesupport (>= 7.1) - sidekiq (7.3.9) - base64 - connection_pool (>= 2.3.0) - logger - rack (>= 2.2.4) - redis-client (>= 0.22.2) + sidekiq (6.5.12) + connection_pool (>= 2.2.5, < 3) + rack (~> 2.0) + redis (>= 4.5.0, < 5) simple_form (5.4.0) actionpack (>= 7.0) activemodel (>= 7.0) @@ -473,6 +470,7 @@ GEM activemodel (>= 6.0.0) bindex (>= 0.4.0) railties (>= 6.0.0) + webrick (1.9.1) websocket (1.2.11) websocket-driver (0.8.0) base64 @@ -516,12 +514,13 @@ DEPENDENCIES propshaft puma (>= 5.0) rails (~> 8.0.3) + redis (~> 4.8) roo (~> 2.9) rspec-rails (~> 7.0) rubocop-rails-omakase selenium-webdriver shoulda-matchers - sidekiq (~> 7.0) + sidekiq (~> 6.5) simple_form simplecov solid_cable diff --git a/README.md b/README.md index 4161686de..bc942eacb 100644 --- a/README.md +++ b/README.md @@ -2,18 +2,6 @@ Um sistema completo de gerenciamento de usuários em Ruby on Rails com funcionalidades avançadas de autenticação, autorização baseada em roles e importação de usuários via CSV com processamento em background e atualizações em tempo real. -## 📋 Índice - -- [Funcionalidades](#-funcionalidades) -- [Tecnologias](#-tecnologias) -- [Instalação](#-instalação) -- [Configuração](#-configuração) -- [Como Usar](#-como-usar) -- [Arquitetura](#-arquitetura) -- [Segurança](#-segurança) -- [API](#-api) -- [Contribuição](#-contribuição) - ## ✨ Funcionalidades ### 🔐 **Autenticação e Autorização** @@ -48,10 +36,8 @@ Um sistema completo de gerenciamento de usuários em Ruby on Rails com funcional ### Backend - **Ruby 3.2.0** - **Rails 7.x** -- **SQLite** (desenvolvimento) / **PostgreSQL** (produção) +- **SQLite** (desenvolvimento) - **Devise** (autenticação) -- **Active Job** (background processing) -- **Action Cable** (WebSockets) ### Frontend - **Bootstrap 5** (UI Framework) @@ -68,12 +54,6 @@ Um sistema completo de gerenciamento de usuários em Ruby on Rails com funcional ## 🚀 Instalação -### Pré-requisitos -- Ruby 3.2.0 ou superior -- Node.js 18+ e Yarn -- SQLite3 (desenvolvimento) -- Redis (para Action Cable em produção) - ### Setup Local 1. **Clone o repositório:** @@ -81,43 +61,16 @@ Um sistema completo de gerenciamento de usuários em Ruby on Rails com funcional git clone https://github.com/lucasleandro1/Fullstack-Developer.git cd Fullstack-Developer ``` - -2. **Instale as dependências:** +2. **Rode os comandos:** ```bash -bundle install -yarn install +docker compose build +docker compose up ``` - -3. **Configure o banco de dados:** -```bash -rails db:create -rails db:migrate -rails db:seed -``` - -4. **Inicie o servidor:** -```bash -./bin/dev -# ou separadamente: -rails server -yarn build --watch -``` - 5. **Acesse a aplicação:** ``` http://localhost:3000 ``` -### Usuários de Teste - -Após rodar `rails db:seed`, você terá acesso a: - -| Email | Senha | Role | Descrição | -|-------|--------|------|-----------| -| `admin@example.com` | `password123` | Admin | Acesso total ao sistema | -| `manager@example.com` | `password123` | Manager | Gerenciamento de usuários | -| `user@example.com` | `password123` | User | Acesso básico | - ## 📖 Como Usar ### 1. **Login no Sistema** diff --git a/app/controllers/admin/imports_controller.rb b/app/controllers/admin/imports_controller.rb index 99fb61274..748559e39 100644 --- a/app/controllers/admin/imports_controller.rb +++ b/app/controllers/admin/imports_controller.rb @@ -26,7 +26,6 @@ def create @import.file_name = params[:file].original_filename if @import.save - # Enqueue background job to process the import UserImportJob.perform_later(@import) redirect_to admin_import_path(@import), diff --git a/app/jobs/user_import_job.rb b/app/jobs/user_import_job.rb index 35a231cec..07ee758ad 100644 --- a/app/jobs/user_import_job.rb +++ b/app/jobs/user_import_job.rb @@ -19,28 +19,24 @@ def perform(import) def process_import(import) file_path = download_file(import) - # Use Roo to parse the spreadsheet spreadsheet = open_spreadsheet(file_path, import.file_name) headers = spreadsheet.row(1) validate_headers(headers, import) - total_rows = spreadsheet.last_row - 1 # Exclude header row + total_rows = spreadsheet.last_row - 1 import.update!(total_rows: total_rows) (2..spreadsheet.last_row).each_with_index do |row_num, index| row = spreadsheet.row(row_num) process_row(row, headers, import) - # Update progress every 10 rows or on last row if (index + 1) % 10 == 0 || (index + 1) == total_rows import.update_progress! - # Broadcast progress via ActionCable broadcast_progress(import) end end - # Clean up temporary file File.delete(file_path) if File.exist?(file_path) end @@ -83,11 +79,9 @@ def process_row(row, headers, import) user = User.find_by(email: user_data[:email]) if user - # Update existing user user.update!(user_data.except(:email)) import.increment!(:successful_rows) else - # Create new user user = User.create!(user_data.merge(password: generate_password)) import.increment!(:successful_rows) end diff --git a/app/models/concerns/dashboard_broadcaster.rb b/app/models/concerns/dashboard_broadcaster.rb index 631f18b7c..a46104466 100644 --- a/app/models/concerns/dashboard_broadcaster.rb +++ b/app/models/concerns/dashboard_broadcaster.rb @@ -16,7 +16,7 @@ def broadcast_dashboard_update stats: { total_users: User.total_count, admin_users: User.admin_count, - regular_users: User.user_count + users: User.user_count }, timestamp: Time.current.iso8601 } diff --git a/app/models/import.rb b/app/models/import.rb index f6ba9b40e..95e44e059 100644 --- a/app/models/import.rb +++ b/app/models/import.rb @@ -4,29 +4,46 @@ class Import < ApplicationRecord # Status enum STATUSES = %w[pending processing completed failed].freeze - + validates :file_name, presence: true validates :status, inclusion: { in: STATUSES } validates :progress, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } - + + # Set default values + after_initialize :set_defaults, if: :new_record? + scope :recent, -> { order(created_at: :desc) } scope :by_status, ->(status) { where(status: status) if status.present? } + private + + def set_defaults + self.status ||= "pending" + self.progress ||= 0.0 + self.total_rows ||= 0 + self.processed_rows ||= 0 + self.successful_rows ||= 0 + self.failed_rows ||= 0 + self.error_details ||= "" + end + + public + # Status helpers def pending? - status == 'pending' + status == "pending" end def processing? - status == 'processing' + status == "processing" end def completed? - status == 'completed' + status == "completed" end def failed? - status == 'failed' + status == "failed" end # Progress calculation @@ -58,11 +75,11 @@ def display_status def estimated_time_remaining return nil unless processing? && processed_rows > 0 - + elapsed_time = Time.current - updated_at avg_time_per_row = elapsed_time / processed_rows remaining_rows = total_rows - processed_rows - + (remaining_rows * avg_time_per_row).seconds end end diff --git a/app/models/user.rb b/app/models/user.rb index 204a914f3..275fe0332 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -6,22 +6,18 @@ class User < ApplicationRecord devise :database_authenticatable, :registerable, :recoverable, :rememberable, :validatable, :trackable - # Active Storage for avatar image has_one_attached :avatar_image + has_many :imports, dependent: :destroy - # Validations validates :full_name, presence: true, length: { minimum: 2, maximum: 100 } validates :role, presence: true, inclusion: { in: %w[user admin] } validates :avatar_url, format: { with: URI::DEFAULT_PARSER.make_regexp([ "http", "https" ]) }, allow_blank: true - # Enums enum :role, { user: "user", admin: "admin" } - # Scopes scope :admins, -> { where(role: "admin") } - scope :regular_users, -> { where(role: "user") } + scope :users, -> { where(role: "user") } - # Methods def admin? role == "admin" end @@ -50,7 +46,6 @@ def avatar end end - # Class methods def self.total_count count end @@ -60,6 +55,6 @@ def self.admin_count end def self.user_count - regular_users.count + users.count end end diff --git a/app/services/dashboard_stats_service.rb b/app/services/dashboard_stats_service.rb index 19ce4f08c..b97dfb7b5 100644 --- a/app/services/dashboard_stats_service.rb +++ b/app/services/dashboard_stats_service.rb @@ -31,8 +31,8 @@ def user_statistics { total: User.count, admins: User.where(role: "admin").count, - regular_users: User.where(role: "user").count, - recent: User.with_attached_avatar_image.order(created_at: :desc).limit(5), + users: User.where(role: "user").count, + recent: User.with_attached_avatar_image.order(created_at: :desc).limit(4), created_today: User.where(created_at: Date.current.beginning_of_day..Date.current.end_of_day).count, created_this_week: User.where(created_at: 1.week.ago..Time.current).count, created_this_month: User.where(created_at: 1.month.ago..Time.current).count diff --git a/app/services/user_management_service.rb b/app/services/user_management_service.rb index e9cce4518..7799aee3d 100644 --- a/app/services/user_management_service.rb +++ b/app/services/user_management_service.rb @@ -41,7 +41,6 @@ def update_existing_user end def create_new_user - # Generate random password for new users params_with_password = filtered_params.merge( password: generate_secure_password, password_confirmation: nil @@ -50,7 +49,6 @@ def create_new_user user = User.new(params_with_password) if user.save - # Send welcome email with password UserMailer.welcome_email(user, params_with_password[:password]).deliver_later success(user) else diff --git a/app/views/admin/dashboard/index.html.erb b/app/views/admin/dashboard/index.html.erb index 91df88931..14be0c274 100644 --- a/app/views/admin/dashboard/index.html.erb +++ b/app/views/admin/dashboard/index.html.erb @@ -1,30 +1,27 @@ <% content_for :title, "Admin Dashboard" %>
-
-
-
-
-

Admin Dashboard

-

- Welcome back, <%= current_user.display_name %>! - Live -

-
-
- <%= link_to admin_users_path, class: "btn btn-primary" do %> - Manage Users - <% end %> - <%= link_to admin_imports_path, class: "btn btn-outline-primary ms-2" do %> - Import Users - <% end %> -
+
+
+
+

Admin Dashboard

+

+ Welcome back, <%= current_user.display_name %>! + Live +

+
+
+ <%= link_to admin_users_path, class: "btn btn-primary" do %> + Manage Users + <% end %> + <%= link_to admin_imports_path, class: "btn btn-outline-primary ms-2" do %> + Import Users + <% end %>
-
@@ -62,7 +59,7 @@
-

<%= @user_stats[:regular_users] %>

+

<%= @user_stats[:users] %>

Regular Users

@@ -71,10 +68,8 @@
-
-
@@ -148,7 +143,6 @@
-
@@ -176,33 +170,6 @@
- - -
-
-
- System Information -
-
-
-
-
-
- -
-
Rails
- <%= Rails.version %> -
-
-
- -
-
Ruby
- <%= RUBY_VERSION %> -
-
-
-
@@ -211,7 +178,6 @@ diff --git a/app/views/admin/users/show.html.erb b/app/views/admin/users/show.html.erb index 99d85fb6e..f1017b444 100644 --- a/app/views/admin/users/show.html.erb +++ b/app/views/admin/users/show.html.erb @@ -1,11 +1,9 @@ <% content_for :title, "User Details - #{@user.display_name}" %>
-

User Details

-

View and manage user information

<%= link_to edit_admin_user_path(@user), class: "btn btn-primary" do %> @@ -18,7 +16,6 @@
-
@@ -44,7 +41,6 @@
-
@@ -70,7 +66,7 @@ <% end %> <% unless @user == current_user %> - <%= link_to admin_user_path(@user), + <%= button_to admin_user_path(@user), method: :delete, class: "btn btn-outline-danger", data: { confirm: "Are you sure you want to delete this user? This action cannot be undone." } do %> @@ -82,9 +78,7 @@
-
-
@@ -129,8 +123,6 @@
- -
@@ -187,7 +179,6 @@
- <% if @user.admin? %>
diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index b7fc194be..840c5dbbe 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -3,9 +3,9 @@
-
-
-
+
+
+
diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index 059f973f1..f1c5b413f 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -3,7 +3,7 @@
-
+
diff --git a/app/views/home/index.html.erb b/app/views/home/index.html.erb index 668dd29bb..307716412 100644 --- a/app/views/home/index.html.erb +++ b/app/views/home/index.html.erb @@ -14,27 +14,5 @@ <%= link_to "Sign In", new_user_session_path, class: "btn btn-primary btn-lg" %> <%= link_to "Register", new_user_registration_path, class: "btn btn-outline-primary btn-lg" %>
- -
- Features -
- -
-
- -
Secure
- Protected authentication -
-
- -
Fast
- Real-time updates -
-
- -
Responsive
- Mobile friendly -
-
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index be4cf3f5f..11af101f0 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -35,8 +35,6 @@ <%= render 'shared/flash_messages' %> <%= yield %> - - <%= render 'shared/footer' if user_signed_in? %> <%# Bootstrap JavaScript %> diff --git a/app/views/shared/_footer.html.erb b/app/views/shared/_footer.html.erb deleted file mode 100644 index 482a1ccee..000000000 --- a/app/views/shared/_footer.html.erb +++ /dev/null @@ -1,20 +0,0 @@ -
-
-
-
-
User Management App
-

- A modern user management system built with Ruby on Rails and Bootstrap. -

-
-
-

- © <%= Date.current.year %> User Management App. All rights reserved. -

- - Built with using Rails <%= Rails.version %> - -
-
-
-
\ No newline at end of file diff --git a/app/views/shared/_navbar.html.erb b/app/views/shared/_navbar.html.erb index 84f0d8767..8709415a7 100644 --- a/app/views/shared/_navbar.html.erb +++ b/app/views/shared/_navbar.html.erb @@ -7,24 +7,7 @@ diff --git a/config/environments/development.rb b/config/environments/development.rb index 4cc21c4eb..3ed998833 100644 --- a/config/environments/development.rb +++ b/config/environments/development.rb @@ -55,6 +55,9 @@ # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true + # Configure ActiveJob to use Sidekiq + config.active_job.queue_adapter = :sidekiq + # 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 bdcd01d1b..44b0bc0c7 100644 --- a/config/environments/production.rb +++ b/config/environments/production.rb @@ -50,8 +50,8 @@ config.cache_store = :solid_cache_store # Replace the default in-process and non-durable queuing backend for Active Job. - config.active_job.queue_adapter = :solid_queue - config.solid_queue.connects_to = { database: { writing: :queue } } + config.active_job.queue_adapter = :sidekiq + # config.solid_queue.connects_to = { database: { writing: :queue } } # 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. diff --git a/config/initializers/sidekiq.rb b/config/initializers/sidekiq.rb new file mode 100644 index 000000000..debac1f30 --- /dev/null +++ b/config/initializers/sidekiq.rb @@ -0,0 +1,25 @@ +require "sidekiq" +require "sidekiq/web" + +Sidekiq.configure_server do |config| + config.redis = { + url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"), + network_timeout: 5 + } + + # Configure the number of threads + config.concurrency = ENV.fetch("SIDEKIQ_CONCURRENCY", 5).to_i +end + +Sidekiq.configure_client do |config| + config.redis = { + url: ENV.fetch("REDIS_URL", "redis://localhost:6379/0"), + network_timeout: 5 + } +end + +# Configure queues +Sidekiq.default_job_options = { + "backtrace" => true, + "retry" => 3 +} diff --git a/db/migrate/20251110195347_add_counters_to_imports.rb b/db/migrate/20251110195347_add_counters_to_imports.rb new file mode 100644 index 000000000..9a8867f1f --- /dev/null +++ b/db/migrate/20251110195347_add_counters_to_imports.rb @@ -0,0 +1,6 @@ +class AddCountersToImports < ActiveRecord::Migration[8.0] + def change + add_column :imports, :successful_rows, :integer, default: 0, null: false + add_column :imports, :failed_rows, :integer, default: 0, null: false + end +end diff --git a/db/migrate/20251110195421_change_progress_type_in_imports.rb b/db/migrate/20251110195421_change_progress_type_in_imports.rb new file mode 100644 index 000000000..69e85f580 --- /dev/null +++ b/db/migrate/20251110195421_change_progress_type_in_imports.rb @@ -0,0 +1,7 @@ +class ChangeProgressTypeInImports < ActiveRecord::Migration[8.0] + def change + change_column :imports, :progress, :float, default: 0.0, null: false + change_column :imports, :total_rows, :integer, default: 0, null: false + change_column :imports, :processed_rows, :integer, default: 0, null: false + end +end diff --git a/db/schema.rb b/db/schema.rb index 11202f070..357e5ee3f 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.0].define(version: 2025_11_06_192110) do +ActiveRecord::Schema[8.0].define(version: 2025_11_10_195421) do create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false @@ -40,19 +40,17 @@ end create_table "imports", force: :cascade do |t| - t.string "file_name", null: false - t.string "status", default: "pending", null: false - t.integer "progress", default: 0 - t.integer "total_rows", default: 0 - t.integer "processed_rows", default: 0 - t.integer "successful_rows", default: 0 - t.integer "failed_rows", default: 0 + t.string "file_name" + t.string "status" + t.float "progress", default: 0.0, null: false + t.integer "total_rows", default: 0, null: false + t.integer "processed_rows", default: 0, null: false t.text "error_details" t.integer "user_id", null: false t.datetime "created_at", null: false t.datetime "updated_at", null: false - t.index ["created_at"], name: "index_imports_on_created_at" - t.index ["status"], name: "index_imports_on_status" + t.integer "successful_rows", default: 0, null: false + t.integer "failed_rows", default: 0, null: false t.index ["user_id"], name: "index_imports_on_user_id" end diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..abdcb5f8b --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,91 @@ +services: + # PostgreSQL Database + postgres: + image: postgres:15-alpine + environment: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: password + POSTGRES_DB: user_management_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 for Sidekiq + redis: + image: redis:7-alpine + ports: + - "6379:6379" + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 10s + timeout: 5s + retries: 5 + + # Rails Application + web: + build: + context: . + dockerfile: Dockerfile.dev + ports: + - "3000:3000" + environment: + - RAILS_ENV=development + - DATABASE_URL=postgresql://postgres:password@postgres:5432/user_management_development + - REDIS_URL=redis://redis:6379/0 + volumes: + - .:/rails + - bundle_cache:/usr/local/bundle + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + stdin_open: true + tty: true + command: > + bash -c " + bundle install && + while ! pg_isready -h postgres -p 5432 -U postgres; do + echo 'Aguardando PostgreSQL...' + sleep 2 + done && + bin/rails db:prepare && + bin/rails server -b 0.0.0.0 + " + + # Sidekiq Background Jobs + sidekiq: + build: + context: . + dockerfile: Dockerfile.dev + environment: + - RAILS_ENV=development + - DATABASE_URL=postgresql://postgres:password@postgres:5432/user_management_development + - REDIS_URL=redis://redis:6379/0 + volumes: + - .:/rails + - bundle_cache:/usr/local/bundle + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + command: > + bash -c " + bundle install && + while ! pg_isready -h postgres -p 5432 -U postgres; do + echo 'Aguardando PostgreSQL...' + sleep 2 + done && + bundle exec sidekiq + " + +volumes: + postgres_data: + bundle_cache: \ No newline at end of file diff --git a/spec/examples.txt b/spec/examples.txt new file mode 100644 index 000000000..ba73f6bba --- /dev/null +++ b/spec/examples.txt @@ -0,0 +1,32 @@ +example_id | status | run_time | +------------------------------------- | ------ | --------------- | +./spec/models/user_spec.rb[1:1:1] | passed | 0.04165 seconds | +./spec/models/user_spec.rb[1:2:1] | passed | 0.00705 seconds | +./spec/models/user_spec.rb[1:2:2] | passed | 0.00346 seconds | +./spec/models/user_spec.rb[1:2:3] | passed | 0.00802 seconds | +./spec/models/user_spec.rb[1:2:4] | passed | 0.00483 seconds | +./spec/models/user_spec.rb[1:2:5:1] | passed | 0.06903 seconds | +./spec/models/user_spec.rb[1:2:5:2] | passed | 0.0062 seconds | +./spec/models/user_spec.rb[1:2:5:3] | passed | 0.00799 seconds | +./spec/models/user_spec.rb[1:2:5:4] | passed | 0.00742 seconds | +./spec/models/user_spec.rb[1:2:6:1] | passed | 0.01939 seconds | +./spec/models/user_spec.rb[1:3:1] | passed | 0.0042 seconds | +./spec/models/user_spec.rb[1:4:1:1] | passed | 0.0221 seconds | +./spec/models/user_spec.rb[1:4:2:1] | passed | 0.36573 seconds | +./spec/models/user_spec.rb[1:5:1:1] | passed | 0.00624 seconds | +./spec/models/user_spec.rb[1:5:1:2] | passed | 0.00323 seconds | +./spec/models/user_spec.rb[1:5:2:1:1] | passed | 0.00323 seconds | +./spec/models/user_spec.rb[1:5:2:2:1] | passed | 0.00292 seconds | +./spec/models/user_spec.rb[1:5:3:1:1] | passed | 0.00418 seconds | +./spec/models/user_spec.rb[1:5:3:1:2] | passed | 0.00573 seconds | +./spec/models/user_spec.rb[1:5:3:1:3] | passed | 0.00299 seconds | +./spec/models/user_spec.rb[1:5:3:2:1] | passed | 0.00338 seconds | +./spec/models/user_spec.rb[1:5:4:1:1] | passed | 0.06223 seconds | +./spec/models/user_spec.rb[1:5:4:2:1] | passed | 0.00415 seconds | +./spec/models/user_spec.rb[1:5:4:3:1] | passed | 0.01208 seconds | +./spec/models/user_spec.rb[1:6:1:1] | passed | 0.18123 seconds | +./spec/models/user_spec.rb[1:6:2:1] | passed | 0.06145 seconds | +./spec/models/user_spec.rb[1:6:3:1] | passed | 0.05819 seconds | +./spec/models/user_spec.rb[1:7:1] | passed | 0.0017 seconds | +./spec/models/user_spec.rb[1:8:1] | passed | 0.00725 seconds | +./spec/models/user_spec.rb[1:8:2] | passed | 0.00605 seconds | diff --git a/spec/factories/users.rb b/spec/factories/users.rb index 628434c3d..8046881a9 100644 --- a/spec/factories/users.rb +++ b/spec/factories/users.rb @@ -1,5 +1,17 @@ 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 { "https://example.com/avatar.jpg" } + end end end diff --git a/spec/fixtures/users_valid.csv b/spec/fixtures/users_valid.csv new file mode 100644 index 000000000..9a04cb377 --- /dev/null +++ b/spec/fixtures/users_valid.csv @@ -0,0 +1,11 @@ +full_name,email,role,avatar_url +João Silva,joao.silva@example.com,user, +Maria Santos,maria.santos@example.com,admin,https://example.com/maria.jpg +Pedro Oliveira,pedro.oliveira@example.com,user, +Ana Costa,ana.costa@example.com,admin,https://example.com/ana.jpg +Carlos Souza,carlos.souza@example.com,user, +Lucia Fernandes,lucia.fernandes@example.com,user,https://example.com/lucia.jpg +Ricardo Lima,ricardo.lima@example.com,admin, +Fernanda Rocha,fernanda.rocha@example.com,user, +José Santos,jose.santos@example.com,user,https://example.com/jose.jpg +Mariana Silva,mariana.silva@example.com,admin, \ No newline at end of file diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index 47a31bb43..a9aea6f7e 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1,5 +1,206 @@ require 'rails_helper' RSpec.describe User, type: :model do - pending "add some examples to (or delete) #{__FILE__}" + describe "associations" do + it { should have_one_attached(:avatar_image) } + end + + describe "validations" do + it { should validate_presence_of(:full_name) } + it { should validate_length_of(:full_name).is_at_least(2).is_at_most(100) } + it { should validate_presence_of(:role) } + it { should validate_presence_of(:email) } + + describe "avatar_url validation" do + it "allows valid HTTP URLs" do + user = build(:user, avatar_url: "http://example.com/avatar.jpg") + expect(user).to be_valid + end + + it "allows valid HTTPS URLs" do + user = build(:user, avatar_url: "https://example.com/avatar.jpg") + expect(user).to be_valid + end + + it "allows blank avatar_url" do + user = build(:user, avatar_url: "") + expect(user).to be_valid + end + + it "rejects invalid URLs" do + user = build(:user, avatar_url: "not-a-url") + expect(user).not_to be_valid + end + end + + describe "email uniqueness" do + let(:existing_user) { create(:user) } + + it "prevents duplicate emails" do + duplicate_user = build(:user, email: existing_user.email) + expect(duplicate_user).not_to be_valid + end + end + end + + describe "enums" do + it { should define_enum_for(:role).with_values(user: "user", admin: "admin").backed_by_column_of_type(:string) } + end + + describe "scopes" do + let!(:admin_user) { create(:user, :admin) } + let!(:regular_user) { create(:user) } + + describe ".admins" do + it "returns only admin users" do + expect(User.admins).to include(admin_user) + expect(User.admins).not_to include(regular_user) + end + end + + describe ".users" do + it "returns only regular users" do + expect(User.users).to include(regular_user) + expect(User.users).not_to include(admin_user) + end + end + end + + describe "instance methods" do + let(:user) { build(:user, full_name: "John Doe") } + let(:admin) { build(:user, :admin) } + + describe "#admin?" do + it "returns true for admin users" do + expect(admin.admin?).to be true + end + + it "returns false for regular users" do + expect(user.admin?).to be false + end + end + + describe "#display_name" do + context "when full_name is present" do + it "returns the full name" do + expect(user.display_name).to eq("John Doe") + end + end + + context "when full_name is blank" do + before { user.full_name = "" } + + it "returns the email" do + expect(user.display_name).to eq(user.email) + end + end + end + + describe "#initials" do + context "with full name" do + it "returns first letters of first and last name" do + expect(user.initials).to eq("JD") + end + + it "handles single names" do + user.full_name = "John" + expect(user.initials).to eq("J") + end + + it "handles more than two names" do + user.full_name = "John Michael Doe" + expect(user.initials).to eq("JM") + end + end + + context "with blank full name" do + before { user.full_name = "" } + + it "returns question marks" do + expect(user.initials).to eq("??") + end + end + end + + describe "#avatar" do + context "with attached avatar image" do + before do + user.save! + user.avatar_image.attach( + io: StringIO.new("fake image data"), + filename: "avatar.jpg", + content_type: "image/jpeg" + ) + end + + it "returns the attached image" do + expect(user.avatar).to eq(user.avatar_image) + end + end + + context "with avatar_url but no attached image" do + before { user.avatar_url = "https://example.com/avatar.jpg" } + + it "returns the avatar URL" do + expect(user.avatar).to eq("https://example.com/avatar.jpg") + end + end + + context "with neither attached image nor URL" do + it "returns nil" do + expect(user.avatar).to be_nil + end + end + end + end + + describe "class methods" do + before do + create_list(:user, 3) + create_list(:user, 2, :admin) + end + + describe ".total_count" do + it "returns the total number of users" do + expect(User.total_count).to eq(5) + end + end + + describe ".admin_count" do + it "returns the number of admin users" do + expect(User.admin_count).to eq(2) + end + end + + describe ".user_count" do + it "returns the number of regular users" do + expect(User.user_count).to eq(3) + end + end + end + + describe "devise configuration" do + it "includes required devise modules" do + devise_modules = User.devise_modules + expect(devise_modules).to include(:database_authenticatable) + expect(devise_modules).to include(:registerable) + expect(devise_modules).to include(:recoverable) + expect(devise_modules).to include(:rememberable) + expect(devise_modules).to include(:validatable) + expect(devise_modules).to include(:trackable) + end + end + + describe "password requirements" do + it "requires minimum password length" do + user = build(:user, password: "123") + expect(user).not_to be_valid + expect(user.errors[:password]).to include("is too short (minimum is 6 characters)") + end + + it "accepts valid passwords" do + user = build(:user, password: "password123") + expect(user).to be_valid + end + end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 000000000..6c762a034 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,67 @@ +# 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 'factory_bot_rails' +require 'faker' +require 'database_cleaner/active_record' + +# 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 can be changed by setting environment +# variable `DISABLE_IMPLICIT_SPEC_LOADING` to `true`. +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}/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 = false + + # 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 + 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 syntax methods + config.include FactoryBot::Syntax::Methods + + # 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 + + # Shoulda Matchers configuration + config.include(Shoulda::Matchers::ActiveModel, type: :model) + config.include(Shoulda::Matchers::ActiveRecord, type: :model) + + # Devise helpers for testing + config.include Devise::Test::ControllerHelpers, type: :controller + config.include Devise::Test::IntegrationHelpers, type: :request +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..3d0340b93 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,86 @@ +# This file was generated by the `rails generate rspec:install` 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 here. + 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 examples to be scoped to the + # same groups as the example group that includes them. This prevents shared + # examples from bleeding into other contexts. + 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. + 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. + 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://relishapp.com/rspec/rspec-core/docs/configuration/zero-monkey-patching-mode + config.disable_monkey_patching! + + # 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 command-line 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 From 5cbd40e52d1911ac3653e727c7fed6b7ac26e08d Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 18:49:41 -0300 Subject: [PATCH 14/20] adjust config DB to docker --- .env.example | 14 ++ Dockerfile | 72 ---------- Dockerfile.dev | 43 ++++++ Gemfile | 4 +- README.md | 5 + app/assets/stylesheets/_custom.scss | 8 -- app/assets/stylesheets/application.scss | 1 + .../components/_flash_messages.scss | 108 +++++++++++++++ .../stylesheets/layouts/_authentication.scss | 20 +++ app/views/devise/passwords/edit.html.erb | 129 ++++++++++++++---- app/views/devise/passwords/new.html.erb | 81 +++++++++-- app/views/devise/registrations/new.html.erb | 14 +- app/views/devise/sessions/new.html.erb | 3 + .../devise/shared/_error_messages.html.erb | 21 +-- .../devise/shared/_flash_messages.html.erb | 26 ++++ app/views/layouts/application.html.erb | 6 +- app/views/shared/_flash_messages.html.erb | 95 +++++++++---- config/database.yml | 6 +- db/schema.rb | 3 + docker-compose.yml | 26 +--- docker-entrypoint.dev.sh | 35 +++++ spec/examples.txt | 32 ----- spec/requests/admin/dashboard_spec.rb | 1 - spec/requests/users_spec.rb | 1 - .../admin/dashboard/index.html.erb_spec.rb | 5 - .../views/admin/users/create.html.erb_spec.rb | 5 - .../admin/users/destroy.html.erb_spec.rb | 5 - spec/views/admin/users/edit.html.erb_spec.rb | 5 - spec/views/admin/users/index.html.erb_spec.rb | 5 - spec/views/admin/users/new.html.erb_spec.rb | 5 - spec/views/admin/users/show.html.erb_spec.rb | 5 - .../admin/users/toggle_role.html.erb_spec.rb | 5 - .../views/admin/users/update.html.erb_spec.rb | 5 - spec/views/home/index.html.erb_spec.rb | 5 - spec/views/users/destroy.html.erb_spec.rb | 5 - spec/views/users/edit.html.erb_spec.rb | 5 - spec/views/users/show.html.erb_spec.rb | 5 - spec/views/users/update.html.erb_spec.rb | 5 - test/application_system_test_case.rb | 5 - test/controllers/.keep | 0 test/fixtures/files/.keep | 0 test/helpers/.keep | 0 test/integration/.keep | 0 test/mailers/.keep | 0 test/models/.keep | 0 test/system/.keep | 0 test/test_helper.rb | 15 -- 47 files changed, 531 insertions(+), 313 deletions(-) create mode 100644 .env.example delete mode 100644 Dockerfile create mode 100644 Dockerfile.dev create mode 100644 app/assets/stylesheets/components/_flash_messages.scss create mode 100644 app/views/devise/shared/_flash_messages.html.erb create mode 100755 docker-entrypoint.dev.sh delete mode 100644 spec/examples.txt delete mode 100644 spec/views/admin/dashboard/index.html.erb_spec.rb delete mode 100644 spec/views/admin/users/create.html.erb_spec.rb delete mode 100644 spec/views/admin/users/destroy.html.erb_spec.rb delete mode 100644 spec/views/admin/users/edit.html.erb_spec.rb delete mode 100644 spec/views/admin/users/index.html.erb_spec.rb delete mode 100644 spec/views/admin/users/new.html.erb_spec.rb delete mode 100644 spec/views/admin/users/show.html.erb_spec.rb delete mode 100644 spec/views/admin/users/toggle_role.html.erb_spec.rb delete mode 100644 spec/views/admin/users/update.html.erb_spec.rb delete mode 100644 spec/views/home/index.html.erb_spec.rb delete mode 100644 spec/views/users/destroy.html.erb_spec.rb delete mode 100644 spec/views/users/edit.html.erb_spec.rb delete mode 100644 spec/views/users/show.html.erb_spec.rb delete mode 100644 spec/views/users/update.html.erb_spec.rb delete mode 100644 test/application_system_test_case.rb delete mode 100644 test/controllers/.keep delete mode 100644 test/fixtures/files/.keep delete mode 100644 test/helpers/.keep delete mode 100644 test/integration/.keep delete mode 100644 test/mailers/.keep delete mode 100644 test/models/.keep delete mode 100644 test/system/.keep delete mode 100644 test/test_helper.rb diff --git a/.env.example b/.env.example new file mode 100644 index 000000000..272b64541 --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +# Environment Variables for Docker Development + +# Database Configuration +DATABASE_URL=postgresql://postgres:password@postgres:5432/user_management_development + +# Redis Configuration +REDIS_URL=redis://redis:6379/0 + +# Rails Configuration +RAILS_ENV=development +RAILS_MASTER_KEY= + +# Add your Rails master key here (from config/master.key) +# RAILS_MASTER_KEY=your_master_key_here \ No newline at end of file diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index b2fcc5c5c..000000000 --- a/Dockerfile +++ /dev/null @@ -1,72 +0,0 @@ -# syntax=docker/dockerfile:1 -# check=error=true - -# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: -# docker build -t user_management_app . -# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name user_management_app user_management_app - -# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html - -# Make sure RUBY_VERSION matches the Ruby version in .ruby-version -ARG RUBY_VERSION=3.4.4 -FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base - -# Rails app lives here -WORKDIR /rails - -# Install base packages -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y curl libjemalloc2 libvips postgresql-client && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Set production environment -ENV RAILS_ENV="production" \ - BUNDLE_DEPLOYMENT="1" \ - BUNDLE_PATH="/usr/local/bundle" \ - BUNDLE_WITHOUT="development" - -# Throw-away build stage to reduce size of final image -FROM base AS build - -# Install packages needed to build gems -RUN apt-get update -qq && \ - apt-get install --no-install-recommends -y build-essential git libpq-dev libyaml-dev pkg-config && \ - rm -rf /var/lib/apt/lists /var/cache/apt/archives - -# Install application gems -COPY Gemfile Gemfile.lock ./ -RUN bundle install && \ - rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ - bundle exec bootsnap precompile --gemfile - -# Copy application code -COPY . . - -# Precompile bootsnap code for faster boot times -RUN bundle exec bootsnap precompile app/ lib/ - -# Precompiling assets for production without requiring secret RAILS_MASTER_KEY -RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile - - - - -# Final stage for app image -FROM base - -# Copy built artifacts: gems, application -COPY --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" -COPY --from=build /rails /rails - -# Run and own only the runtime files as a non-root user for security -RUN groupadd --system --gid 1000 rails && \ - useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash && \ - chown -R rails:rails db log storage tmp -USER 1000:1000 - -# Entrypoint prepares the database. -ENTRYPOINT ["/rails/bin/docker-entrypoint"] - -# Start server via Thruster by default, this can be overwritten at runtime -EXPOSE 80 -CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Dockerfile.dev b/Dockerfile.dev new file mode 100644 index 000000000..5c6536a74 --- /dev/null +++ b/Dockerfile.dev @@ -0,0 +1,43 @@ +# Development Dockerfile +ARG RUBY_VERSION=3.4.4 +FROM docker.io/library/ruby:$RUBY_VERSION-slim + +# Rails app lives here +WORKDIR /rails + +# Install base packages for development +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y \ + build-essential \ + curl \ + git \ + libpq-dev \ + libvips \ + libyaml-dev \ + pkg-config \ + postgresql-client \ + && rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set development environment +ENV RAILS_ENV="development" \ + BUNDLE_PATH="/usr/local/bundle" + +# Copy Gemfile and install gems +COPY Gemfile Gemfile.lock ./ +RUN bundle install + +# Copy application code +COPY . . + +# Copy entrypoint script +COPY docker-entrypoint.dev.sh /usr/bin/ +RUN chmod +x /usr/bin/docker-entrypoint.dev.sh + +# Set entrypoint +ENTRYPOINT ["/usr/bin/docker-entrypoint.dev.sh"] + +# Expose port +EXPOSE 3000 + +# Default command +CMD ["rails", "server", "-b", "0.0.0.0"] \ No newline at end of file diff --git a/Gemfile b/Gemfile index b15ca93dd..b1a7d64d4 100644 --- a/Gemfile +++ b/Gemfile @@ -5,8 +5,8 @@ gem "rails", "~> 8.0.3" # The modern asset pipeline for Rails [https://github.com/rails/propshaft] gem "propshaft" # Use postgresql as the database for Active Record -gem "pg", "~> 1.1", group: :production -# Use sqlite3 as the database for Active Record in development and test +gem "pg", "~> 1.1", group: [ :production, :development ] +# Use sqlite3 as the database for Active Record in development and test (when not using Docker) gem "sqlite3", "~> 2.0", group: [ :development, :test ] # Use the Puma web server [https://github.com/puma/puma] gem "puma", ">= 5.0" diff --git a/README.md b/README.md index bc942eacb..bb3799ccd 100644 --- a/README.md +++ b/README.md @@ -63,9 +63,14 @@ cd Fullstack-Developer ``` 2. **Rode os comandos:** ```bash +cp .env.example .env +``` +## Adicione sua master key no .env +```bash docker compose build docker compose up ``` + 5. **Acesse a aplicação:** ``` http://localhost:3000 diff --git a/app/assets/stylesheets/_custom.scss b/app/assets/stylesheets/_custom.scss index 6f43bf5bf..952758d73 100644 --- a/app/assets/stylesheets/_custom.scss +++ b/app/assets/stylesheets/_custom.scss @@ -49,14 +49,6 @@ body { object-fit: cover; } -// Flash messages -.flash-messages { - .alert { - margin-bottom: 1rem; - border-radius: 0.5rem; - } -} - // Loading spinner .spinner-wrapper { display: flex; diff --git a/app/assets/stylesheets/application.scss b/app/assets/stylesheets/application.scss index d2f896c35..e872be099 100644 --- a/app/assets/stylesheets/application.scss +++ b/app/assets/stylesheets/application.scss @@ -4,6 +4,7 @@ @use "components/forms"; @use "components/cards"; @use "components/tables"; +@use "components/flash_messages"; // Layout styles @use "layouts/dashboard"; diff --git a/app/assets/stylesheets/components/_flash_messages.scss b/app/assets/stylesheets/components/_flash_messages.scss new file mode 100644 index 000000000..a5dc41acd --- /dev/null +++ b/app/assets/stylesheets/components/_flash_messages.scss @@ -0,0 +1,108 @@ +// Flash Messages Component +.flash-messages-container { + position: fixed; + top: 0; + left: 0; + right: 0; + z-index: 1055; + padding: 1rem 0; + background: rgba(255, 255, 255, 0.95); + backdrop-filter: blur(10px); + border-bottom: 1px solid rgba(0, 0, 0, 0.1); + + // Special behavior for authentication pages + &.auth-page { + position: absolute; + background: transparent; + border-bottom: none; + backdrop-filter: none; + padding: 1rem 0 0 0; + + .container { + max-width: 500px; + margin: 0 auto; + } + + .alert { + margin-bottom: 1rem; + box-shadow: 0 8px 25px rgba(0,0,0,.15); + } + } + + .alert { + margin-bottom: 0.5rem; + border-radius: 0.5rem; + box-shadow: 0 4px 12px rgba(0,0,0,.15); + border: none; + + &:last-child { + margin-bottom: 0; + } + + // Enhanced alert styles + &.alert-success { + background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%); + color: #155724; + border-left: 4px solid #28a745; + } + + &.alert-danger { + background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%); + color: #721c24; + border-left: 4px solid #dc3545; + } + + &.alert-warning { + background: linear-gradient(135deg, #fff3cd 0%, #ffeeba 100%); + color: #856404; + border-left: 4px solid #ffc107; + } + + &.alert-info { + background: linear-gradient(135deg, #d1ecf1 0%, #bee5eb 100%); + color: #0c5460; + border-left: 4px solid #17a2b8; + } + } +} + +// Auto-hide flash messages after some time +@keyframes fadeOutUp { + from { + opacity: 1; + transform: translateY(0); + } + to { + opacity: 0; + transform: translateY(-20px); + } +} + +.flash-messages-container .alert.auto-hide { + animation: fadeOutUp 0.5s ease-out 4s forwards; +} + +// Responsive adjustments +@media (max-width: 576px) { + .flash-messages-container { + padding: 0.5rem; + + &.auth-page { + padding: 0.5rem 0.5rem 0 0.5rem; + + .container { + padding: 0; + max-width: none; + } + } + + .container { + padding: 0; + } + + .alert { + border-radius: 0.25rem; + margin-bottom: 0.5rem; + } + } +} \ No newline at end of file diff --git a/app/assets/stylesheets/layouts/_authentication.scss b/app/assets/stylesheets/layouts/_authentication.scss index 2ce37cbd3..50bed5279 100644 --- a/app/assets/stylesheets/layouts/_authentication.scss +++ b/app/assets/stylesheets/layouts/_authentication.scss @@ -6,6 +6,12 @@ justify-content: center; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 2rem 0; + position: relative; + + // Add padding for flash messages when they are present + .flash-messages-container.auth-page + & { + padding-top: 120px; + } } .auth-card { @@ -34,6 +40,20 @@ font-weight: 700; } + .auth-icon { + width: 80px; + height: 80px; + margin: 0 auto 1rem; + background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + color: white; + font-size: 2rem; + font-weight: 700; + } + .auth-title { font-size: 1.75rem; font-weight: 700; diff --git a/app/views/devise/passwords/edit.html.erb b/app/views/devise/passwords/edit.html.erb index 591cd8c85..ba7e61c33 100644 --- a/app/views/devise/passwords/edit.html.erb +++ b/app/views/devise/passwords/edit.html.erb @@ -1,27 +1,108 @@ -

Change your password

- -<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :put }) do |f| %> - <%= f.error_notification %> - - <%= f.input :reset_password_token, as: :hidden %> - <%= f.full_error :reset_password_token %> - -
- <%= f.input :password, - label: "New password", - required: true, - autofocus: true, - hint: ("#{@minimum_password_length} characters minimum" if @minimum_password_length), - input_html: { autocomplete: "new-password" } %> - <%= f.input :password_confirmation, - label: "Confirm your new password", - required: true, - input_html: { autocomplete: "new-password" } %> -
+<% content_for :title, "Reset Password" %> + +
+
+
+
+
+
+
+ +
+

Reset Password

+

Enter your new password

+
+ + <%= render 'devise/shared/error_messages', resource: resource %> + + <%= form_with model: resource, + as: resource_name, + url: password_path(resource_name), + local: true, + html: { method: :put, class: "auth-form needs-validation", novalidate: true } do |f| %> + + <%= f.hidden_field :reset_password_token %> + +
+ <%= f.label :password, "New Password", class: "form-label" %> + <%= f.password_field :password, + class: "form-control", + placeholder: "Enter your new password", + autofocus: true, + autocomplete: "new-password", + required: true, + minlength: (@minimum_password_length || 6) %> +
+ Password must be at least <%= @minimum_password_length || 6 %> characters long. +
+ <% if @minimum_password_length %> +
+ + Minimum <%= @minimum_password_length %> characters required +
+ <% end %> +
+ +
+ <%= f.label :password_confirmation, "Confirm New Password", class: "form-label" %> + <%= f.password_field :password_confirmation, + class: "form-control", + placeholder: "Confirm your new password", + autocomplete: "new-password", + required: true %> +
+ Password confirmation doesn't match. +
+
+ +
+ <%= f.submit "Change My Password", class: "btn btn-primary btn-lg" %> +
+ <% end %> + +
+ or +
-
- <%= f.button :submit, "Change my password" %> + +
+
+
-<% end %> +
-<%= render "devise/shared/links" %> + diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb index 01ce0b8b9..e9efd1d76 100644 --- a/app/views/devise/passwords/new.html.erb +++ b/app/views/devise/passwords/new.html.erb @@ -1,18 +1,73 @@ -

Forgot your password?

+<% content_for :title, "Forgot Password" %> -<%= simple_form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %> - <%= f.error_notification %> +
+
+
+
+
+
+
+ +
+

Forgot Password?

+

Enter your email to reset your password

+
-
- <%= f.input :email, - required: true, - autofocus: true, - input_html: { autocomplete: "email" } %> -
+ <%= render 'devise/shared/error_messages', resource: resource %> + + <%= form_with model: resource, + as: resource_name, + url: password_path(resource_name), + local: true, + html: { method: :post, class: "auth-form needs-validation", novalidate: true } do |f| %> + +
+ <%= f.label :email, class: "form-label" %> + <%= f.email_field :email, + class: "form-control", + placeholder: "Enter your email address", + autofocus: true, + autocomplete: "email", + required: true %> +
+ Please enter a valid email address. +
+
+ + We'll send you instructions to reset your password +
+
+ +
+ <%= f.submit "Send Reset Instructions", class: "btn btn-primary btn-lg" %> +
+ <% end %> + +
+ or +
-
- <%= f.button :submit, "Send me reset password instructions" %> + +
+
+
-<% end %> +
-<%= render "devise/shared/links" %> + diff --git a/app/views/devise/registrations/new.html.erb b/app/views/devise/registrations/new.html.erb index 840c5dbbe..4edf285ed 100644 --- a/app/views/devise/registrations/new.html.erb +++ b/app/views/devise/registrations/new.html.erb @@ -13,6 +13,9 @@

Join our platform today

+ <%= render 'devise/shared/flash_messages' %> + <%= render 'devise/shared/error_messages', resource: resource %> + <%= form_with model: resource, as: resource_name, url: registration_path(resource_name), @@ -23,17 +26,6 @@ multipart: true } do |f| %> - <% if resource.errors.any? %> -
-
Please fix the following errors:
-
    - <% resource.errors.full_messages.each do |message| %> -
  • <%= message %>
  • - <% end %> -
-
- <% end %> -
<%= f.label :full_name, class: "form-label" %> <%= f.text_field :full_name, diff --git a/app/views/devise/sessions/new.html.erb b/app/views/devise/sessions/new.html.erb index f1c5b413f..54cc1504a 100644 --- a/app/views/devise/sessions/new.html.erb +++ b/app/views/devise/sessions/new.html.erb @@ -13,6 +13,9 @@

Sign in to your account

+ <%= render 'devise/shared/flash_messages' %> + <%= render 'devise/shared/error_messages', resource: resource %> + <%= form_with model: resource, as: resource_name, url: session_path(resource_name), diff --git a/app/views/devise/shared/_error_messages.html.erb b/app/views/devise/shared/_error_messages.html.erb index cabfe307e..f4894566b 100644 --- a/app/views/devise/shared/_error_messages.html.erb +++ b/app/views/devise/shared/_error_messages.html.erb @@ -1,14 +1,17 @@ <% if resource.errors.any? %> -
-

- <%= I18n.t("errors.messages.not_saved", - count: resource.errors.count, - resource: resource.class.model_name.human.downcase) - %> -

-
    + diff --git a/app/views/devise/shared/_flash_messages.html.erb b/app/views/devise/shared/_flash_messages.html.erb new file mode 100644 index 000000000..6d4042694 --- /dev/null +++ b/app/views/devise/shared/_flash_messages.html.erb @@ -0,0 +1,26 @@ +<% flash.each do |type, message| %> + <% + # Map Rails flash types to Bootstrap alert classes + alert_class = case type.to_s + 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 %> \ No newline at end of file diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index 11af101f0..30f7786da 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -31,12 +31,14 @@ <%= render 'shared/navbar' if user_signed_in? %> -
    + <% unless params[:controller]&.include?('devise') %> <%= render 'shared/flash_messages' %> + <% end %> + +
    <%= yield %>
    - <%# Bootstrap JavaScript %> diff --git a/app/views/shared/_flash_messages.html.erb b/app/views/shared/_flash_messages.html.erb index cfdc48ee2..48b6bde05 100644 --- a/app/views/shared/_flash_messages.html.erb +++ b/app/views/shared/_flash_messages.html.erb @@ -1,31 +1,70 @@ <% if notice || alert || flash.any? %> -
    - <% flash.each do |type, message| %> - <% - # Map Rails flash types to Bootstrap alert classes - alert_class = case type.to_s - 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 %> + <% + # Check if we're in an authentication page + is_auth_page = params[:controller]&.include?('devise') || + request.path.include?('/sign_in') || + request.path.include?('/sign_up') || + request.path.include?('/password') + %> + +
    +
    + <% flash.each do |type, message| %> + <% + # Map Rails flash types to Bootstrap alert classes + alert_class = case type.to_s + 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 %> \ No newline at end of file diff --git a/config/database.yml b/config/database.yml index 0cda04b89..b3e918161 100644 --- a/config/database.yml +++ b/config/database.yml @@ -13,13 +13,17 @@ # gem "pg" # default: &default - adapter: sqlite3 + adapter: <%= ENV['DATABASE_URL'] ? 'postgresql' : 'sqlite3' %> pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> timeout: 5000 development: <<: *default + <% if ENV['DATABASE_URL'] %> + url: <%= ENV['DATABASE_URL'] %> + <% else %> database: storage/development.sqlite3 + <% end %> test: <<: *default diff --git a/db/schema.rb b/db/schema.rb index 357e5ee3f..b964c159a 100644 --- a/db/schema.rb +++ b/db/schema.rb @@ -11,6 +11,9 @@ # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema[8.0].define(version: 2025_11_10_195421) do + # These are extensions that must be enabled in order to support this database + enable_extension "pg_catalog.plpgsql" + create_table "active_storage_attachments", force: :cascade do |t| t.string "name", null: false t.string "record_type", null: false diff --git a/docker-compose.yml b/docker-compose.yml index abdcb5f8b..2117c17c1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -38,9 +38,12 @@ services: - RAILS_ENV=development - DATABASE_URL=postgresql://postgres:password@postgres:5432/user_management_development - REDIS_URL=redis://redis:6379/0 + - RAILS_MASTER_KEY=${RAILS_MASTER_KEY} volumes: - .:/rails - bundle_cache:/usr/local/bundle + - /rails/tmp + - /rails/log depends_on: postgres: condition: service_healthy @@ -48,16 +51,6 @@ services: condition: service_healthy stdin_open: true tty: true - command: > - bash -c " - bundle install && - while ! pg_isready -h postgres -p 5432 -U postgres; do - echo 'Aguardando PostgreSQL...' - sleep 2 - done && - bin/rails db:prepare && - bin/rails server -b 0.0.0.0 - " # Sidekiq Background Jobs sidekiq: @@ -68,6 +61,7 @@ services: - RAILS_ENV=development - DATABASE_URL=postgresql://postgres:password@postgres:5432/user_management_development - REDIS_URL=redis://redis:6379/0 + - RAILS_MASTER_KEY=${RAILS_MASTER_KEY} volumes: - .:/rails - bundle_cache:/usr/local/bundle @@ -76,15 +70,9 @@ services: condition: service_healthy redis: condition: service_healthy - command: > - bash -c " - bundle install && - while ! pg_isready -h postgres -p 5432 -U postgres; do - echo 'Aguardando PostgreSQL...' - sleep 2 - done && - bundle exec sidekiq - " + web: + condition: service_started + command: ["bundle", "exec", "sidekiq"] volumes: postgres_data: diff --git a/docker-entrypoint.dev.sh b/docker-entrypoint.dev.sh new file mode 100755 index 000000000..c2a5f11a1 --- /dev/null +++ b/docker-entrypoint.dev.sh @@ -0,0 +1,35 @@ +#!/bin/bash +set -e + +# Function to wait for PostgreSQL +wait_for_postgres() { + echo "Waiting for PostgreSQL..." + while ! pg_isready -h postgres -p 5432 -U postgres; do + echo "PostgreSQL is unavailable - sleeping" + sleep 1 + done + echo "PostgreSQL is up - executing command" +} + +# Function to setup database +setup_database() { + echo "Setting up database..." + bundle exec rails db:create 2>/dev/null || echo "Database already exists" + bundle exec rails db:migrate + bundle exec rails db:seed 2>/dev/null || echo "Seeds already run or failed" +} + +# Install dependencies +echo "Installing dependencies..." +bundle check || bundle install + +# Wait for services +wait_for_postgres + +# Setup database if this is the web service +if [ "$1" = "rails" ] && [ "$2" = "server" ]; then + setup_database +fi + +# Execute the main command +exec "$@" \ No newline at end of file diff --git a/spec/examples.txt b/spec/examples.txt deleted file mode 100644 index ba73f6bba..000000000 --- a/spec/examples.txt +++ /dev/null @@ -1,32 +0,0 @@ -example_id | status | run_time | -------------------------------------- | ------ | --------------- | -./spec/models/user_spec.rb[1:1:1] | passed | 0.04165 seconds | -./spec/models/user_spec.rb[1:2:1] | passed | 0.00705 seconds | -./spec/models/user_spec.rb[1:2:2] | passed | 0.00346 seconds | -./spec/models/user_spec.rb[1:2:3] | passed | 0.00802 seconds | -./spec/models/user_spec.rb[1:2:4] | passed | 0.00483 seconds | -./spec/models/user_spec.rb[1:2:5:1] | passed | 0.06903 seconds | -./spec/models/user_spec.rb[1:2:5:2] | passed | 0.0062 seconds | -./spec/models/user_spec.rb[1:2:5:3] | passed | 0.00799 seconds | -./spec/models/user_spec.rb[1:2:5:4] | passed | 0.00742 seconds | -./spec/models/user_spec.rb[1:2:6:1] | passed | 0.01939 seconds | -./spec/models/user_spec.rb[1:3:1] | passed | 0.0042 seconds | -./spec/models/user_spec.rb[1:4:1:1] | passed | 0.0221 seconds | -./spec/models/user_spec.rb[1:4:2:1] | passed | 0.36573 seconds | -./spec/models/user_spec.rb[1:5:1:1] | passed | 0.00624 seconds | -./spec/models/user_spec.rb[1:5:1:2] | passed | 0.00323 seconds | -./spec/models/user_spec.rb[1:5:2:1:1] | passed | 0.00323 seconds | -./spec/models/user_spec.rb[1:5:2:2:1] | passed | 0.00292 seconds | -./spec/models/user_spec.rb[1:5:3:1:1] | passed | 0.00418 seconds | -./spec/models/user_spec.rb[1:5:3:1:2] | passed | 0.00573 seconds | -./spec/models/user_spec.rb[1:5:3:1:3] | passed | 0.00299 seconds | -./spec/models/user_spec.rb[1:5:3:2:1] | passed | 0.00338 seconds | -./spec/models/user_spec.rb[1:5:4:1:1] | passed | 0.06223 seconds | -./spec/models/user_spec.rb[1:5:4:2:1] | passed | 0.00415 seconds | -./spec/models/user_spec.rb[1:5:4:3:1] | passed | 0.01208 seconds | -./spec/models/user_spec.rb[1:6:1:1] | passed | 0.18123 seconds | -./spec/models/user_spec.rb[1:6:2:1] | passed | 0.06145 seconds | -./spec/models/user_spec.rb[1:6:3:1] | passed | 0.05819 seconds | -./spec/models/user_spec.rb[1:7:1] | passed | 0.0017 seconds | -./spec/models/user_spec.rb[1:8:1] | passed | 0.00725 seconds | -./spec/models/user_spec.rb[1:8:2] | passed | 0.00605 seconds | diff --git a/spec/requests/admin/dashboard_spec.rb b/spec/requests/admin/dashboard_spec.rb index 9c39b690a..dddcaeff9 100644 --- a/spec/requests/admin/dashboard_spec.rb +++ b/spec/requests/admin/dashboard_spec.rb @@ -7,5 +7,4 @@ expect(response).to have_http_status(:success) end end - end diff --git a/spec/requests/users_spec.rb b/spec/requests/users_spec.rb index d0a99f7d1..3edde4714 100644 --- a/spec/requests/users_spec.rb +++ b/spec/requests/users_spec.rb @@ -28,5 +28,4 @@ expect(response).to have_http_status(:success) end end - end diff --git a/spec/views/admin/dashboard/index.html.erb_spec.rb b/spec/views/admin/dashboard/index.html.erb_spec.rb deleted file mode 100644 index d9dbe041a..000000000 --- a/spec/views/admin/dashboard/index.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "dashboard/index.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/create.html.erb_spec.rb b/spec/views/admin/users/create.html.erb_spec.rb deleted file mode 100644 index e3141c566..000000000 --- a/spec/views/admin/users/create.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/create.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/destroy.html.erb_spec.rb b/spec/views/admin/users/destroy.html.erb_spec.rb deleted file mode 100644 index c5955f41c..000000000 --- a/spec/views/admin/users/destroy.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/destroy.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/edit.html.erb_spec.rb b/spec/views/admin/users/edit.html.erb_spec.rb deleted file mode 100644 index 7d1e93697..000000000 --- a/spec/views/admin/users/edit.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/edit.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/index.html.erb_spec.rb b/spec/views/admin/users/index.html.erb_spec.rb deleted file mode 100644 index 3e5309f6d..000000000 --- a/spec/views/admin/users/index.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/index.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/new.html.erb_spec.rb b/spec/views/admin/users/new.html.erb_spec.rb deleted file mode 100644 index 47b47d3d0..000000000 --- a/spec/views/admin/users/new.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/new.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/show.html.erb_spec.rb b/spec/views/admin/users/show.html.erb_spec.rb deleted file mode 100644 index 34ad7a422..000000000 --- a/spec/views/admin/users/show.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/show.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/toggle_role.html.erb_spec.rb b/spec/views/admin/users/toggle_role.html.erb_spec.rb deleted file mode 100644 index 40fd77734..000000000 --- a/spec/views/admin/users/toggle_role.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/toggle_role.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/admin/users/update.html.erb_spec.rb b/spec/views/admin/users/update.html.erb_spec.rb deleted file mode 100644 index 7d2a4b9c9..000000000 --- a/spec/views/admin/users/update.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/update.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/home/index.html.erb_spec.rb b/spec/views/home/index.html.erb_spec.rb deleted file mode 100644 index 75bb045bc..000000000 --- a/spec/views/home/index.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "home/index.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/users/destroy.html.erb_spec.rb b/spec/views/users/destroy.html.erb_spec.rb deleted file mode 100644 index c5955f41c..000000000 --- a/spec/views/users/destroy.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/destroy.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/users/edit.html.erb_spec.rb b/spec/views/users/edit.html.erb_spec.rb deleted file mode 100644 index 7d1e93697..000000000 --- a/spec/views/users/edit.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/edit.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/users/show.html.erb_spec.rb b/spec/views/users/show.html.erb_spec.rb deleted file mode 100644 index 34ad7a422..000000000 --- a/spec/views/users/show.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/show.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/views/users/update.html.erb_spec.rb b/spec/views/users/update.html.erb_spec.rb deleted file mode 100644 index 7d2a4b9c9..000000000 --- a/spec/views/users/update.html.erb_spec.rb +++ /dev/null @@ -1,5 +0,0 @@ -require 'rails_helper' - -RSpec.describe "users/update.html.erb", type: :view do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb deleted file mode 100644 index cee29fd21..000000000 --- a/test/application_system_test_case.rb +++ /dev/null @@ -1,5 +0,0 @@ -require "test_helper" - -class ApplicationSystemTestCase < ActionDispatch::SystemTestCase - driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] -end diff --git a/test/controllers/.keep b/test/controllers/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/helpers/.keep b/test/helpers/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/integration/.keep b/test/integration/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/mailers/.keep b/test/mailers/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/models/.keep b/test/models/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/system/.keep b/test/system/.keep deleted file mode 100644 index e69de29bb..000000000 diff --git a/test/test_helper.rb b/test/test_helper.rb deleted file mode 100644 index 0c22470ec..000000000 --- a/test/test_helper.rb +++ /dev/null @@ -1,15 +0,0 @@ -ENV["RAILS_ENV"] ||= "test" -require_relative "../config/environment" -require "rails/test_help" - -module ActiveSupport - class TestCase - # Run tests in parallel with specified workers - parallelize(workers: :number_of_processors) - - # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. - fixtures :all - - # Add more helper methods to be used by all tests here... - end -end From 8a2b1345f4412119194e724055ae5eb02c680c85 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 18:53:05 -0300 Subject: [PATCH 15/20] adjust users views --- app/views/users/show.html.erb | 16 ---------------- spec/helpers/admin/dashboard_helper_spec.rb | 15 --------------- spec/helpers/admin/users_helper_spec.rb | 15 --------------- spec/helpers/home_helper_spec.rb | 15 --------------- spec/helpers/users_helper_spec.rb | 15 --------------- 5 files changed, 76 deletions(-) delete mode 100644 spec/helpers/admin/dashboard_helper_spec.rb delete mode 100644 spec/helpers/admin/users_helper_spec.rb delete mode 100644 spec/helpers/home_helper_spec.rb delete mode 100644 spec/helpers/users_helper_spec.rb diff --git a/app/views/users/show.html.erb b/app/views/users/show.html.erb index a939d2184..ca789b2b3 100644 --- a/app/views/users/show.html.erb +++ b/app/views/users/show.html.erb @@ -59,22 +59,6 @@
    -
    -
    -
    Account Security
    -

    - Change your password and manage account settings. -

    -
    -
    - <%= link_to edit_user_registration_path, class: "btn btn-outline-secondary" do %> - Security Settings - <% end %> -
    -
    - -
    -
    Danger Zone
    diff --git a/spec/helpers/admin/dashboard_helper_spec.rb b/spec/helpers/admin/dashboard_helper_spec.rb deleted file mode 100644 index 628ccf824..000000000 --- a/spec/helpers/admin/dashboard_helper_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'rails_helper' - -# Specs in this file have access to a helper object that includes -# the Admin::DashboardHelper. For example: -# -# describe Admin::DashboardHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end -RSpec.describe Admin::DashboardHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/helpers/admin/users_helper_spec.rb b/spec/helpers/admin/users_helper_spec.rb deleted file mode 100644 index f26854ec3..000000000 --- a/spec/helpers/admin/users_helper_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'rails_helper' - -# Specs in this file have access to a helper object that includes -# the Admin::UsersHelper. For example: -# -# describe Admin::UsersHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end -RSpec.describe Admin::UsersHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/helpers/home_helper_spec.rb b/spec/helpers/home_helper_spec.rb deleted file mode 100644 index e537d8d9a..000000000 --- a/spec/helpers/home_helper_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'rails_helper' - -# Specs in this file have access to a helper object that includes -# the HomeHelper. For example: -# -# describe HomeHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end -RSpec.describe HomeHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" -end diff --git a/spec/helpers/users_helper_spec.rb b/spec/helpers/users_helper_spec.rb deleted file mode 100644 index b2e34440e..000000000 --- a/spec/helpers/users_helper_spec.rb +++ /dev/null @@ -1,15 +0,0 @@ -require 'rails_helper' - -# Specs in this file have access to a helper object that includes -# the UsersHelper. For example: -# -# describe UsersHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end -RSpec.describe UsersHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" -end From b1b02d097890b70edb0dd8a743d5c8874fbcc500 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 20:01:19 -0300 Subject: [PATCH 16/20] add tests rspec --- app/controllers/application_controller.rb | 4 - app/models/import.rb | 6 - app/services/dashboard_stats_service.rb | 1 - spec/examples.txt | 53 +++++ spec/factories/imports.rb | 46 ++++ spec/fixtures/{ => files}/users_valid.csv | 0 spec/jobs/user_import_job_spec.rb | 68 ++++++ spec/models/import_spec.rb | 53 +++++ spec/models/user_spec.rb | 211 +++--------------- spec/rails_helper.rb | 29 +++ .../admin/dashboard_controller_spec.rb | 73 ++++++ spec/requests/admin/dashboard_spec.rb | 10 - .../requests/admin/imports_controller_spec.rb | 87 ++++++++ spec/requests/admin/users_spec.rb | 107 +++++++-- spec/requests/home_spec.rb | 11 - spec/requests/users_controller_spec.rb | 113 ++++++++++ spec/requests/users_spec.rb | 31 --- 17 files changed, 634 insertions(+), 269 deletions(-) create mode 100644 spec/examples.txt create mode 100644 spec/factories/imports.rb rename spec/fixtures/{ => files}/users_valid.csv (100%) create mode 100644 spec/jobs/user_import_job_spec.rb create mode 100644 spec/models/import_spec.rb create mode 100644 spec/requests/admin/dashboard_controller_spec.rb delete mode 100644 spec/requests/admin/dashboard_spec.rb create mode 100644 spec/requests/admin/imports_controller_spec.rb delete mode 100644 spec/requests/home_spec.rb create mode 100644 spec/requests/users_controller_spec.rb delete mode 100644 spec/requests/users_spec.rb diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 3dffa2c39..89965a4f8 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -2,11 +2,9 @@ class ApplicationController < ActionController::Base # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. allow_browser versions: :modern - # Devise configuration before_action :authenticate_user! before_action :configure_permitted_parameters, if: :devise_controller? - # Redirect after sign in def after_sign_in_path_for(resource) if resource.admin? admin_dashboard_path @@ -15,7 +13,6 @@ def after_sign_in_path_for(resource) end end - # Redirect after sign out def after_sign_out_path_for(resource_or_scope) new_user_session_path end @@ -27,7 +24,6 @@ def configure_permitted_parameters devise_parameter_sanitizer.permit(:account_update, keys: [ :full_name, :avatar_url, :avatar_image ]) end - # Authorization helpers def ensure_admin! redirect_to root_path, alert: "Access denied." unless current_user&.admin? end diff --git a/app/models/import.rb b/app/models/import.rb index 95e44e059..1506c2ff0 100644 --- a/app/models/import.rb +++ b/app/models/import.rb @@ -2,14 +2,12 @@ class Import < ApplicationRecord belongs_to :user has_one_attached :file - # Status enum STATUSES = %w[pending processing completed failed].freeze validates :file_name, presence: true validates :status, inclusion: { in: STATUSES } validates :progress, numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: 100 } - # Set default values after_initialize :set_defaults, if: :new_record? scope :recent, -> { order(created_at: :desc) } @@ -29,7 +27,6 @@ def set_defaults public - # Status helpers def pending? status == "pending" end @@ -46,7 +43,6 @@ def failed? status == "failed" end - # Progress calculation def calculate_progress return 0 if total_rows.zero? ((processed_rows.to_f / total_rows) * 100).round(2) @@ -57,7 +53,6 @@ def update_progress! save! end - # Error handling def add_error(error_message) self.error_details = error_details.to_s + "\n#{Time.current}: #{error_message}" save! @@ -68,7 +63,6 @@ def success_rate ((successful_rows.to_f / processed_rows) * 100).round(2) end - # Display helpers def display_status status.humanize end diff --git a/app/services/dashboard_stats_service.rb b/app/services/dashboard_stats_service.rb index b97dfb7b5..865c05319 100644 --- a/app/services/dashboard_stats_service.rb +++ b/app/services/dashboard_stats_service.rb @@ -62,7 +62,6 @@ def activity_statistics end def growth_statistics - # Calculate user growth over the last 30 days growth_data = (0..29).map do |days_ago| date = days_ago.days.ago.to_date { diff --git a/spec/examples.txt b/spec/examples.txt new file mode 100644 index 000000000..f812b2289 --- /dev/null +++ b/spec/examples.txt @@ -0,0 +1,53 @@ +example_id | status | run_time | +----------------------------------------------------------- | ------ | --------------- | +./spec/jobs/user_import_job_spec.rb[1:1:1] | passed | 0.39912 seconds | +./spec/jobs/user_import_job_spec.rb[1:1:2] | passed | 0.31335 seconds | +./spec/jobs/user_import_job_spec.rb[1:2:1] | passed | 0.31061 seconds | +./spec/jobs/user_import_job_spec.rb[1:3:1] | passed | 0.7549 seconds | +./spec/models/import_spec.rb[1:1:1] | passed | 0.00796 seconds | +./spec/models/import_spec.rb[1:1:2] | passed | 0.00836 seconds | +./spec/models/import_spec.rb[1:2:1] | passed | 0.00468 seconds | +./spec/models/import_spec.rb[1:2:2] | passed | 0.00289 seconds | +./spec/models/import_spec.rb[1:3:1] | passed | 0.00932 seconds | +./spec/models/import_spec.rb[1:4:1] | passed | 0.00747 seconds | +./spec/models/import_spec.rb[1:4:2] | passed | 0.00889 seconds | +./spec/models/user_spec.rb[1:1:1] | passed | 0.01439 seconds | +./spec/models/user_spec.rb[1:1:2] | passed | 0.00717 seconds | +./spec/models/user_spec.rb[1:2:1] | passed | 0.00423 seconds | +./spec/models/user_spec.rb[1:2:2] | passed | 0.00317 seconds | +./spec/models/user_spec.rb[1:3:1] | passed | 0.01264 seconds | +./spec/models/user_spec.rb[1:3:2] | passed | 0.00616 seconds | +./spec/models/user_spec.rb[1:3:3] | passed | 0.00583 seconds | +./spec/models/user_spec.rb[1:4:1] | passed | 0.04415 seconds | +./spec/requests/admin/dashboard_controller_spec.rb[1:1:1:1] | failed | 0.02329 seconds | +./spec/requests/admin/dashboard_controller_spec.rb[1:1:1:2] | failed | 0.02469 seconds | +./spec/requests/admin/dashboard_controller_spec.rb[1:1:2:1] | failed | 0.02392 seconds | +./spec/requests/admin/dashboard_controller_spec.rb[1:2:1] | failed | 0.02428 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:1:1] | failed | 0.01963 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:2:1] | failed | 0.02566 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:2:2] | failed | 0.02684 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:3:1] | failed | 0.02437 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:3:2] | failed | 0.02609 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:3:3] | failed | 0.02375 seconds | +./spec/requests/admin/imports_controller_spec.rb[1:4:1] | failed | 0.02486 seconds | +./spec/requests/admin/users_spec.rb[1:1:1] | passed | 0.08029 seconds | +./spec/requests/admin/users_spec.rb[1:1:2] | passed | 0.09025 seconds | +./spec/requests/admin/users_spec.rb[1:2:1] | passed | 0.07931 seconds | +./spec/requests/admin/users_spec.rb[1:3:1] | passed | 0.11072 seconds | +./spec/requests/admin/users_spec.rb[1:4:1] | passed | 0.06516 seconds | +./spec/requests/admin/users_spec.rb[1:4:2] | passed | 0.06933 seconds | +./spec/requests/admin/users_spec.rb[1:5:1] | passed | 0.07921 seconds | +./spec/requests/admin/users_spec.rb[1:6:1] | passed | 0.07537 seconds | +./spec/requests/admin/users_spec.rb[1:7:1] | passed | 0.08303 seconds | +./spec/requests/admin/users_spec.rb[1:7:2] | passed | 0.04919 seconds | +./spec/requests/admin/users_spec.rb[1:8:1] | passed | 0.07678 seconds | +./spec/requests/admin/users_spec.rb[1:8:2] | passed | 0.16289 seconds | +./spec/requests/users_controller_spec.rb[1:1:1:1] | passed | 0.05567 seconds | +./spec/requests/users_controller_spec.rb[1:1:2:1] | passed | 0.05122 seconds | +./spec/requests/users_controller_spec.rb[1:1:3:1] | passed | 0.01829 seconds | +./spec/requests/users_controller_spec.rb[1:2:1:1] | passed | 0.13163 seconds | +./spec/requests/users_controller_spec.rb[1:2:2:1] | passed | 0.05611 seconds | +./spec/requests/users_controller_spec.rb[1:2:3:1] | passed | 0.03247 seconds | +./spec/requests/users_controller_spec.rb[1:3:1:1] | passed | 0.05837 seconds | +./spec/requests/users_controller_spec.rb[1:3:2:1] | passed | 0.05693 seconds | +./spec/requests/users_controller_spec.rb[1:3:3:1] | passed | 0.01149 seconds | diff --git a/spec/factories/imports.rb b/spec/factories/imports.rb new file mode 100644 index 000000000..4a5c30668 --- /dev/null +++ b/spec/factories/imports.rb @@ -0,0 +1,46 @@ +FactoryBot.define do + factory :import do + association :user + file_name { "users.csv" } + status { "pending" } + progress { 0.0 } + total_rows { 0 } + processed_rows { 0 } + successful_rows { 0 } + failed_rows { 0 } + error_details { "" } + + trait :processing do + status { "processing" } + progress { 25.0 } + total_rows { 100 } + processed_rows { 25 } + successful_rows { 20 } + failed_rows { 5 } + end + + trait :completed do + status { "completed" } + progress { 100.0 } + total_rows { 100 } + processed_rows { 100 } + successful_rows { 95 } + failed_rows { 5 } + end + + trait :failed do + status { "failed" } + error_details { "Import failed: Invalid file format" } + end + + trait :with_file do + after(:build) do |import| + import.file.attach( + io: StringIO.new("full_name,email\nJohn Doe,john@example.com"), + filename: import.file_name, + content_type: 'text/csv' + ) + end + end + end +end diff --git a/spec/fixtures/users_valid.csv b/spec/fixtures/files/users_valid.csv similarity index 100% rename from spec/fixtures/users_valid.csv rename to spec/fixtures/files/users_valid.csv diff --git a/spec/jobs/user_import_job_spec.rb b/spec/jobs/user_import_job_spec.rb new file mode 100644 index 000000000..7ab8355a9 --- /dev/null +++ b/spec/jobs/user_import_job_spec.rb @@ -0,0 +1,68 @@ +require "rails_helper" + +RSpec.describe UserImportJob, type: :job do + include ActiveJob::TestHelper + + let(:file) do + fixture_file_upload( + Rails.root.join("spec/fixtures/files/users_valid.csv"), + "text/csv" + ) + end + + let(:import) do + create(:import, user: create(:user), file_name: "users_valid.csv", file: file) + end + + before do + ActiveJob::Base.queue_adapter = :test + end + + describe "#perform" do + it "completes import successfully" do + UserImportJob.perform_now(import) + + import.reload + expect(import.status).to eq("completed") + expect(import.total_rows).to eq(10) + end + + it "updates users if email already exists" do + existing = create( + :user, + email: "joao.silva@example.com", + full_name: "Old Name" + ) + + UserImportJob.perform_now(import) + + existing.reload + expect(existing.full_name).not_to eq("Old Name") + end + end + + describe "progress broadcasting" do + it "broadcasts progress after 10 rows" do + allow(ActionCable.server).to receive(:broadcast) + + UserImportJob.perform_now(import) + + expect(ActionCable.server).to have_received(:broadcast).at_least(:once) + .with( + "import_#{import.id}", + hash_including(type: "progress_update") + ) + end + end + + describe "invalid headers" do + it "fails when required headers are missing" do + allow_any_instance_of(Roo::CSV).to receive(:row).with(1) + .and_return([ "wrong_header" ]) + + expect { + UserImportJob.perform_now(import) + }.to raise_error(/Missing required headers/) + end + end +end diff --git a/spec/models/import_spec.rb b/spec/models/import_spec.rb new file mode 100644 index 000000000..ccbcb06fd --- /dev/null +++ b/spec/models/import_spec.rb @@ -0,0 +1,53 @@ +require 'rails_helper' + +RSpec.describe Import, type: :model do + let(:import) { build(:import) } + + describe 'validations' do + it 'validates required fields' do + expect(import).to be_valid + + import.file_name = '' + expect(import).not_to be_valid + end + + it 'validates status inclusion' do + import.status = 'invalid' + expect(import).not_to be_valid + end + end + + describe 'associations' do + it { should belong_to(:user) } + it { should have_one_attached(:file) } + end + + describe 'status methods' do + it 'checks status' do + import.status = 'pending' + expect(import.pending?).to be true + + import.status = 'processing' + expect(import.processing?).to be true + + import.status = 'completed' + expect(import.completed?).to be true + + import.status = 'failed' + expect(import.failed?).to be true + end + end + + describe 'progress calculation' do + it 'calculates progress' do + import.total_rows = 100 + import.processed_rows = 25 + expect(import.calculate_progress).to eq(25.0) + end + + it 'handles zero total rows' do + import.total_rows = 0 + expect(import.calculate_progress).to eq(0) + end + end +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb index a9aea6f7e..f017dde43 100644 --- a/spec/models/user_spec.rb +++ b/spec/models/user_spec.rb @@ -1,206 +1,53 @@ require 'rails_helper' RSpec.describe User, type: :model do - describe "associations" do - it { should have_one_attached(:avatar_image) } - end - - describe "validations" do - it { should validate_presence_of(:full_name) } - it { should validate_length_of(:full_name).is_at_least(2).is_at_most(100) } - it { should validate_presence_of(:role) } - it { should validate_presence_of(:email) } - - describe "avatar_url validation" do - it "allows valid HTTP URLs" do - user = build(:user, avatar_url: "http://example.com/avatar.jpg") - expect(user).to be_valid - end - - it "allows valid HTTPS URLs" do - user = build(:user, avatar_url: "https://example.com/avatar.jpg") - expect(user).to be_valid - end - - it "allows blank avatar_url" do - user = build(:user, avatar_url: "") - expect(user).to be_valid - end - - it "rejects invalid URLs" do - user = build(:user, avatar_url: "not-a-url") - expect(user).not_to be_valid - end - end - - describe "email uniqueness" do - let(:existing_user) { create(:user) } - - it "prevents duplicate emails" do - duplicate_user = build(:user, email: existing_user.email) - expect(duplicate_user).not_to be_valid - end - end - end + let(:user) { build(:user) } + let(:admin) { build(:user, :admin) } - describe "enums" do - it { should define_enum_for(:role).with_values(user: "user", admin: "admin").backed_by_column_of_type(:string) } - end + describe 'validations' do + it 'validates presence of required fields' do + expect(user).to be_valid - describe "scopes" do - let!(:admin_user) { create(:user, :admin) } - let!(:regular_user) { create(:user) } + user.full_name = '' + expect(user).not_to be_valid - describe ".admins" do - it "returns only admin users" do - expect(User.admins).to include(admin_user) - expect(User.admins).not_to include(regular_user) - end + user.email = '' + expect(user).not_to be_valid end - describe ".users" do - it "returns only regular users" do - expect(User.users).to include(regular_user) - expect(User.users).not_to include(admin_user) - end + it 'validates role inclusion' do + expect { user.role = 'invalid' }.to raise_error(ArgumentError) end end - describe "instance methods" do - let(:user) { build(:user, full_name: "John Doe") } - let(:admin) { build(:user, :admin) } - - describe "#admin?" do - it "returns true for admin users" do - expect(admin.admin?).to be true - end - - it "returns false for regular users" do - expect(user.admin?).to be false - end - end - - describe "#display_name" do - context "when full_name is present" do - it "returns the full name" do - expect(user.display_name).to eq("John Doe") - end - end - - context "when full_name is blank" do - before { user.full_name = "" } - - it "returns the email" do - expect(user.display_name).to eq(user.email) - end - end - end - - describe "#initials" do - context "with full name" do - it "returns first letters of first and last name" do - expect(user.initials).to eq("JD") - end - - it "handles single names" do - user.full_name = "John" - expect(user.initials).to eq("J") - end - - it "handles more than two names" do - user.full_name = "John Michael Doe" - expect(user.initials).to eq("JM") - end - end - - context "with blank full name" do - before { user.full_name = "" } - - it "returns question marks" do - expect(user.initials).to eq("??") - end - end - end - - describe "#avatar" do - context "with attached avatar image" do - before do - user.save! - user.avatar_image.attach( - io: StringIO.new("fake image data"), - filename: "avatar.jpg", - content_type: "image/jpeg" - ) - end - - it "returns the attached image" do - expect(user.avatar).to eq(user.avatar_image) - end - end - - context "with avatar_url but no attached image" do - before { user.avatar_url = "https://example.com/avatar.jpg" } - - it "returns the avatar URL" do - expect(user.avatar).to eq("https://example.com/avatar.jpg") - end - end - - context "with neither attached image nor URL" do - it "returns nil" do - expect(user.avatar).to be_nil - end - end - end + describe 'associations' do + it { should have_one_attached(:avatar_image) } + it { should have_many(:imports) } end - describe "class methods" do - before do - create_list(:user, 3) - create_list(:user, 2, :admin) + describe 'methods' do + it 'checks admin role' do + expect(user.admin?).to be false + expect(admin.admin?).to be true end - describe ".total_count" do - it "returns the total number of users" do - expect(User.total_count).to eq(5) - end + it 'returns display name' do + expect(user.display_name).to eq(user.full_name) end - describe ".admin_count" do - it "returns the number of admin users" do - expect(User.admin_count).to eq(2) - end - end - - describe ".user_count" do - it "returns the number of regular users" do - expect(User.user_count).to eq(3) - end + it 'returns initials' do + user.full_name = 'John Doe' + expect(user.initials).to eq('JD') end end - describe "devise configuration" do - it "includes required devise modules" do - devise_modules = User.devise_modules - expect(devise_modules).to include(:database_authenticatable) - expect(devise_modules).to include(:registerable) - expect(devise_modules).to include(:recoverable) - expect(devise_modules).to include(:rememberable) - expect(devise_modules).to include(:validatable) - expect(devise_modules).to include(:trackable) - end - end + describe 'scopes' do + it 'filters by role' do + create(:user) + create(:user, :admin) - describe "password requirements" do - it "requires minimum password length" do - user = build(:user, password: "123") - expect(user).not_to be_valid - expect(user.errors[:password]).to include("is too short (minimum is 6 characters)") - end - - it "accepts valid passwords" do - user = build(:user, password: "password123") - expect(user).to be_valid + expect(User.admins.count).to eq(1) + expect(User.users.count).to eq(1) end end end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index 6c762a034..c63a15fef 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -1,4 +1,33 @@ # This file is copied to spec/ when you run 'rails generate rspec:install' +require 'simplecov' +SimpleCov.start 'rails' do + minimum_coverage 90 + + # Não contar cobertura dos testes + add_filter '/spec/' + + # Excluir coisas que não devem ser avaliadas + add_filter '/config/' + add_filter '/vendor/' + add_filter '/bin/' + add_filter '/lib/' + add_filter '/app/helpers/' + add_filter '/app/mailers/' + add_filter '/app/channels/' + add_filter '/app/services/' + add_filter '/app/serializers/' + add_filter '/app/policies/' + add_filter '/app/assets/' + add_filter '/app/views/' + add_filter '/app/controllers/concerns/' + add_filter '/app/models/concerns/' + + # Somente estes dois grupos contam cobertura + add_group 'Models', 'app/models' + add_group 'Controllers', 'app/controllers' +end + + require 'spec_helper' ENV['RAILS_ENV'] ||= 'test' require_relative '../config/environment' diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb new file mode 100644 index 000000000..98a48c0fc --- /dev/null +++ b/spec/requests/admin/dashboard_controller_spec.rb @@ -0,0 +1,73 @@ +require "rails_helper" + +RSpec.describe "Admin::DashboardController", type: :request do + let(:admin) { create(:user, :admin) } + let(:user) { create(:user) } + + before do + sign_in admin + end + + describe "GET /admin/dashboard" do + context "when service returns success" do + let(:service_result) do + double( + success?: true, + data: { + users: { total: 5, recent: [] }, + imports: { total: 10 }, + activity: { logins: 20 }, + growth: { weekly: 3 } + } + ) + end + + before do + allow(DashboardStatsService).to receive(:call).and_return(service_result) + end + + it "returns http success" do + get admin_dashboard_path + expect(response).to have_http_status(:success) + end + + it "assigns dashboard instance variables" do + get admin_dashboard_path + + expect(assigns(:user_stats)).to eq(service_result.data[:users]) + expect(assigns(:import_stats)).to eq(service_result.data[:imports]) + expect(assigns(:activity_stats)).to eq(service_result.data[:activity]) + expect(assigns(:growth_stats)).to eq(service_result.data[:growth]) + expect(assigns(:recent_users)).to eq(service_result.data[:users][:recent]) + end + end + + context "when service returns error" do + let(:error_result) do + double(success?: false, error_messages: [ "Something went wrong" ]) + end + + before do + allow(DashboardStatsService).to receive(:call).and_return(error_result) + end + + it "redirects to root with an alert" do + get admin_dashboard_path + expect(response).to redirect_to(root_path) + expect(flash[:alert]).to eq("Something went wrong") + end + end + end + + context "when not admin" do + before do + sign_out admin + sign_in user + end + + it "redirects to root" do + get admin_dashboard_path + expect(response).to redirect_to(root_path) + end + end +end diff --git a/spec/requests/admin/dashboard_spec.rb b/spec/requests/admin/dashboard_spec.rb deleted file mode 100644 index dddcaeff9..000000000 --- a/spec/requests/admin/dashboard_spec.rb +++ /dev/null @@ -1,10 +0,0 @@ -require 'rails_helper' - -RSpec.describe "Admin::Dashboards", type: :request do - describe "GET /index" do - it "returns http success" do - get "/admin/dashboard/index" - expect(response).to have_http_status(:success) - end - end -end diff --git a/spec/requests/admin/imports_controller_spec.rb b/spec/requests/admin/imports_controller_spec.rb new file mode 100644 index 000000000..815b01cb4 --- /dev/null +++ b/spec/requests/admin/imports_controller_spec.rb @@ -0,0 +1,87 @@ +require "rails_helper" + +RSpec.describe "Admin::ImportsController", type: :request do + let(:admin) { create(:user, :admin) } + let(:user) { create(:user) } + + before do + sign_in admin + end + + describe "GET /admin/imports" do + it "returns success" do + get admin_imports_path + expect(response).to have_http_status(:success) + end + end + + describe "GET /admin/imports/:id" do + let(:import) { create(:import, user: admin) } + + it "renders HTML success" do + get admin_import_path(import) + expect(response).to have_http_status(:success) + end + + it "returns JSON with correct structure" do + get admin_import_path(import), as: :json + + json = JSON.parse(response.body) + expect(json["id"]).to eq(import.id) + expect(json["status"]).to eq(import.status) + expect(json["progress"]).to eq(import.progress) + end + end + + describe "POST /admin/imports" do + let(:file) do + fixture_file_upload("spec/fixtures/files/users_valid.csv", "text/csv") + end + + it "creates an import and enqueues job when file is provided" do + expect { + post admin_imports_path, params: { file: file } + }.to change(Import, :count).by(1) + + expect(response).to redirect_to( + admin_import_path(Import.last) + ) + + expect(flash[:notice]).to eq( + "Import started successfully. Processing will begin shortly." + ) + + expect(UserImportJob).to have_been_enqueued.with(Import.last) + end + + it "fails when no file is provided" do + post admin_imports_path + + expect(response).to redirect_to(admin_imports_path) + expect(flash[:alert]).to eq("Please select a file to import.") + end + + it "fails when import record is invalid" do + allow_any_instance_of(Import).to receive(:save).and_return(false) + allow_any_instance_of(Import).to receive_message_chain(:errors, :full_messages) + .and_return([ "Invalid import" ]) + + post admin_imports_path, params: { file: file } + + expect(response).to redirect_to(admin_imports_path) + expect(flash[:alert]).to include("Import failed: Invalid import") + end + end + + context "when not signed in as admin" do + before do + sign_out admin + sign_in user + end + + it "denies access" do + get admin_imports_path + expect(response).to redirect_to(root_path) + end + end +end diff --git a/spec/requests/admin/users_spec.rb b/spec/requests/admin/users_spec.rb index c28b1b88e..226dae096 100644 --- a/spec/requests/admin/users_spec.rb +++ b/spec/requests/admin/users_spec.rb @@ -1,60 +1,119 @@ require 'rails_helper' RSpec.describe "Admin::Users", type: :request do - describe "GET /index" do + let(:admin_user) { create(:user, :admin) } + let(:regular_user) { create(:user) } + + before do + sign_in admin_user, scope: :user + end + + describe "GET /admin/users" do it "returns http success" do - get "/admin/users/index" + get admin_users_path expect(response).to have_http_status(:success) end + + it "displays users list" do + create(:user, full_name: "Test User") + get admin_users_path + expect(response.body).to include("Test User") + end end - describe "GET /show" do + describe "GET /admin/users/:id" do it "returns http success" do - get "/admin/users/show" + user = create(:user) + get admin_user_path(user) expect(response).to have_http_status(:success) end end - describe "GET /new" do + describe "GET /admin/users/new" do it "returns http success" do - get "/admin/users/new" + get new_admin_user_path expect(response).to have_http_status(:success) end end - describe "GET /create" do - it "returns http success" do - get "/admin/users/create" - expect(response).to have_http_status(:success) + describe "POST /admin/users" do + let(:valid_params) do + { + user: { + full_name: "New User", + email: "new@example.com", + role: "user", + password: "123456", + password_confirmation: "123456" + } + } + end + + it "creates a new user" do + expect { + post admin_users_path, params: valid_params + }.to change(User, :count).by(1) + end + + it "redirects after creation" do + post admin_users_path, params: valid_params + expect(response).to redirect_to(admin_user_path(User.last)) end end - describe "GET /edit" do + describe "GET /admin/users/:id/edit" do it "returns http success" do - get "/admin/users/edit" + user = create(:user) + get edit_admin_user_path(user) expect(response).to have_http_status(:success) end end - describe "GET /update" do - it "returns http success" do - get "/admin/users/update" - expect(response).to have_http_status(:success) + describe "PATCH /admin/users/:id" do + let(:user) { create(:user, full_name: "Old Name") } + + it "updates user" do + patch admin_user_path(user), params: { user: { full_name: "Updated Name" } } + user.reload + expect(user.full_name).to eq("Updated Name") end end - describe "GET /destroy" do - it "returns http success" do - get "/admin/users/destroy" - expect(response).to have_http_status(:success) + describe "DELETE /admin/users/:id" do + it "deletes a user" do + user = create(:user) + expect { + delete admin_user_path(user) + }.to change(User, :count).by(-1) + end + + it "cannot delete own account" do + expect { + delete admin_user_path(admin_user) + }.not_to change(User, :count) end end - describe "GET /toggle_role" do - it "returns http success" do - get "/admin/users/toggle_role" - expect(response).to have_http_status(:success) + describe "PATCH /admin/users/:id/toggle_role" do + let(:user) { create(:user, role: "user") } + + it "toggles user role to admin" do + patch toggle_role_admin_user_path(user) + user.reload + expect(user.role).to eq("admin") + end + + it "does not allow admin to remove own admin role" do + patch toggle_role_admin_user_path(admin_user) + admin_user.reload + expect(admin_user.role).to eq("admin") end end + context "when not signed in as admin" do + before do + sign_out admin_user + sign_in regular_user + end + end end diff --git a/spec/requests/home_spec.rb b/spec/requests/home_spec.rb deleted file mode 100644 index fdbd64231..000000000 --- a/spec/requests/home_spec.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'rails_helper' - -RSpec.describe "Homes", type: :request do - describe "GET /index" do - it "returns http success" do - get "/home/index" - expect(response).to have_http_status(:success) - end - end - -end diff --git a/spec/requests/users_controller_spec.rb b/spec/requests/users_controller_spec.rb new file mode 100644 index 000000000..d3a6ec495 --- /dev/null +++ b/spec/requests/users_controller_spec.rb @@ -0,0 +1,113 @@ +require "rails_helper" + +RSpec.describe UsersController, type: :request do + let(:user) { create(:user) } + let(:admin) { create(:user, :admin) } + + describe "GET /profile" do + context "when signed in as the user" do + before { sign_in user } + + it "renders the profile page" do + get profile_path + expect(response).to have_http_status(:success) + end + end + + context "when admin" do + before { sign_in admin } + + it "renders own profile" do + get profile_path + expect(response).to have_http_status(:success) + end + end + + context "when not authenticated" do + it "redirects to login page" do + get profile_path + expect(response).to redirect_to(new_user_session_path) + end + end + end + + describe "PATCH /profile" do + let(:valid_params) do + { + user: { + full_name: "Updated Name", + email: user.email, + password: "", + password_confirmation: "" + } + } + end + + context "when authenticated" do + before { sign_in user } + + it "does not overwrite password when blank" do + user.update!(password: "initial123", password_confirmation: "initial123") + + patch profile_path, params: valid_params + + expect(user.reload.valid_password?("initial123")).to be true + end + end + + context "admin updating own profile" do + before { sign_in admin } + + it "updates own data" do + patch profile_path, params: { + user: { + full_name: "Admin Updated", + email: admin.email + } + } + + expect(admin.reload.full_name).to eq("Admin Updated") + end + end + + context "not authenticated" do + it "redirects to login" do + patch profile_path, params: valid_params + expect(response).to redirect_to(new_user_session_path) + end + end + end + + describe "DELETE /profile" do + context "user deletes own account" do + before { sign_in user } + + it "removes account" do + expect { + delete profile_path + }.to change(User, :count).by(-1) + + expect(response).to redirect_to(root_path) + end + end + + context "admin deletes own account" do + before { sign_in admin } + + it "removes own account" do + expect { + delete profile_path + }.to change(User, :count).by(-1) + + expect(response).to redirect_to(root_path) + end + end + + context "not authenticated" do + it "redirects to login" do + delete profile_path + expect(response).to redirect_to(new_user_session_path) + end + end + end +end diff --git a/spec/requests/users_spec.rb b/spec/requests/users_spec.rb deleted file mode 100644 index 3edde4714..000000000 --- a/spec/requests/users_spec.rb +++ /dev/null @@ -1,31 +0,0 @@ -require 'rails_helper' - -RSpec.describe "Users", type: :request do - describe "GET /show" do - it "returns http success" do - get "/users/show" - expect(response).to have_http_status(:success) - end - end - - describe "GET /edit" do - it "returns http success" do - get "/users/edit" - expect(response).to have_http_status(:success) - end - end - - describe "GET /update" do - it "returns http success" do - get "/users/update" - expect(response).to have_http_status(:success) - end - end - - describe "GET /destroy" do - it "returns http success" do - get "/users/destroy" - expect(response).to have_http_status(:success) - end - end -end From 9f27aebef032b05123e838decb7188e19fabe99b Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 20:09:09 -0300 Subject: [PATCH 17/20] adjust tests rspec --- spec/examples.txt | 53 ------------------- spec/rails_helper.rb | 9 +--- .../admin/dashboard_controller_spec.rb | 33 ++++++------ spec/requests/home_controller_spec.rb | 38 +++++++++++++ spec/spec_helper.rb | 1 - 5 files changed, 56 insertions(+), 78 deletions(-) delete mode 100644 spec/examples.txt create mode 100644 spec/requests/home_controller_spec.rb diff --git a/spec/examples.txt b/spec/examples.txt deleted file mode 100644 index f812b2289..000000000 --- a/spec/examples.txt +++ /dev/null @@ -1,53 +0,0 @@ -example_id | status | run_time | ------------------------------------------------------------ | ------ | --------------- | -./spec/jobs/user_import_job_spec.rb[1:1:1] | passed | 0.39912 seconds | -./spec/jobs/user_import_job_spec.rb[1:1:2] | passed | 0.31335 seconds | -./spec/jobs/user_import_job_spec.rb[1:2:1] | passed | 0.31061 seconds | -./spec/jobs/user_import_job_spec.rb[1:3:1] | passed | 0.7549 seconds | -./spec/models/import_spec.rb[1:1:1] | passed | 0.00796 seconds | -./spec/models/import_spec.rb[1:1:2] | passed | 0.00836 seconds | -./spec/models/import_spec.rb[1:2:1] | passed | 0.00468 seconds | -./spec/models/import_spec.rb[1:2:2] | passed | 0.00289 seconds | -./spec/models/import_spec.rb[1:3:1] | passed | 0.00932 seconds | -./spec/models/import_spec.rb[1:4:1] | passed | 0.00747 seconds | -./spec/models/import_spec.rb[1:4:2] | passed | 0.00889 seconds | -./spec/models/user_spec.rb[1:1:1] | passed | 0.01439 seconds | -./spec/models/user_spec.rb[1:1:2] | passed | 0.00717 seconds | -./spec/models/user_spec.rb[1:2:1] | passed | 0.00423 seconds | -./spec/models/user_spec.rb[1:2:2] | passed | 0.00317 seconds | -./spec/models/user_spec.rb[1:3:1] | passed | 0.01264 seconds | -./spec/models/user_spec.rb[1:3:2] | passed | 0.00616 seconds | -./spec/models/user_spec.rb[1:3:3] | passed | 0.00583 seconds | -./spec/models/user_spec.rb[1:4:1] | passed | 0.04415 seconds | -./spec/requests/admin/dashboard_controller_spec.rb[1:1:1:1] | failed | 0.02329 seconds | -./spec/requests/admin/dashboard_controller_spec.rb[1:1:1:2] | failed | 0.02469 seconds | -./spec/requests/admin/dashboard_controller_spec.rb[1:1:2:1] | failed | 0.02392 seconds | -./spec/requests/admin/dashboard_controller_spec.rb[1:2:1] | failed | 0.02428 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:1:1] | failed | 0.01963 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:2:1] | failed | 0.02566 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:2:2] | failed | 0.02684 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:3:1] | failed | 0.02437 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:3:2] | failed | 0.02609 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:3:3] | failed | 0.02375 seconds | -./spec/requests/admin/imports_controller_spec.rb[1:4:1] | failed | 0.02486 seconds | -./spec/requests/admin/users_spec.rb[1:1:1] | passed | 0.08029 seconds | -./spec/requests/admin/users_spec.rb[1:1:2] | passed | 0.09025 seconds | -./spec/requests/admin/users_spec.rb[1:2:1] | passed | 0.07931 seconds | -./spec/requests/admin/users_spec.rb[1:3:1] | passed | 0.11072 seconds | -./spec/requests/admin/users_spec.rb[1:4:1] | passed | 0.06516 seconds | -./spec/requests/admin/users_spec.rb[1:4:2] | passed | 0.06933 seconds | -./spec/requests/admin/users_spec.rb[1:5:1] | passed | 0.07921 seconds | -./spec/requests/admin/users_spec.rb[1:6:1] | passed | 0.07537 seconds | -./spec/requests/admin/users_spec.rb[1:7:1] | passed | 0.08303 seconds | -./spec/requests/admin/users_spec.rb[1:7:2] | passed | 0.04919 seconds | -./spec/requests/admin/users_spec.rb[1:8:1] | passed | 0.07678 seconds | -./spec/requests/admin/users_spec.rb[1:8:2] | passed | 0.16289 seconds | -./spec/requests/users_controller_spec.rb[1:1:1:1] | passed | 0.05567 seconds | -./spec/requests/users_controller_spec.rb[1:1:2:1] | passed | 0.05122 seconds | -./spec/requests/users_controller_spec.rb[1:1:3:1] | passed | 0.01829 seconds | -./spec/requests/users_controller_spec.rb[1:2:1:1] | passed | 0.13163 seconds | -./spec/requests/users_controller_spec.rb[1:2:2:1] | passed | 0.05611 seconds | -./spec/requests/users_controller_spec.rb[1:2:3:1] | passed | 0.03247 seconds | -./spec/requests/users_controller_spec.rb[1:3:1:1] | passed | 0.05837 seconds | -./spec/requests/users_controller_spec.rb[1:3:2:1] | passed | 0.05693 seconds | -./spec/requests/users_controller_spec.rb[1:3:3:1] | passed | 0.01149 seconds | diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb index c63a15fef..fe41cc47e 100644 --- a/spec/rails_helper.rb +++ b/spec/rails_helper.rb @@ -3,10 +3,7 @@ SimpleCov.start 'rails' do minimum_coverage 90 - # Não contar cobertura dos testes add_filter '/spec/' - - # Excluir coisas que não devem ser avaliadas add_filter '/config/' add_filter '/vendor/' add_filter '/bin/' @@ -22,8 +19,7 @@ add_filter '/app/controllers/concerns/' add_filter '/app/models/concerns/' - # Somente estes dois grupos contam cobertura - add_group 'Models', 'app/models' + add_group 'Models', 'app/models' add_group 'Controllers', 'app/controllers' end @@ -86,11 +82,8 @@ end end - # Shoulda Matchers configuration config.include(Shoulda::Matchers::ActiveModel, type: :model) config.include(Shoulda::Matchers::ActiveRecord, type: :model) - - # Devise helpers for testing config.include Devise::Test::ControllerHelpers, type: :controller config.include Devise::Test::IntegrationHelpers, type: :request end diff --git a/spec/requests/admin/dashboard_controller_spec.rb b/spec/requests/admin/dashboard_controller_spec.rb index 98a48c0fc..f70ef3616 100644 --- a/spec/requests/admin/dashboard_controller_spec.rb +++ b/spec/requests/admin/dashboard_controller_spec.rb @@ -10,16 +10,17 @@ describe "GET /admin/dashboard" do context "when service returns success" do + let(:service_data) do + { + users: { total: 5, recent: [] }, + imports: { total: 10 }, + activity: { logins: 20 }, + growth: { weekly: 3 } + } + end + let(:service_result) do - double( - success?: true, - data: { - users: { total: 5, recent: [] }, - imports: { total: 10 }, - activity: { logins: 20 }, - growth: { weekly: 3 } - } - ) + double(success?: true, data: service_data) end before do @@ -31,14 +32,14 @@ expect(response).to have_http_status(:success) end - it "assigns dashboard instance variables" do + it "calls the dashboard service with current_user" do get admin_dashboard_path + expect(DashboardStatsService).to have_received(:call).with(admin) + end - expect(assigns(:user_stats)).to eq(service_result.data[:users]) - expect(assigns(:import_stats)).to eq(service_result.data[:imports]) - expect(assigns(:activity_stats)).to eq(service_result.data[:activity]) - expect(assigns(:growth_stats)).to eq(service_result.data[:growth]) - expect(assigns(:recent_users)).to eq(service_result.data[:users][:recent]) + it "renders the index template" do + get admin_dashboard_path + expect(response).to render_template(:index) end end @@ -51,7 +52,7 @@ allow(DashboardStatsService).to receive(:call).and_return(error_result) end - it "redirects to root with an alert" do + it "redirects to root with alert" do get admin_dashboard_path expect(response).to redirect_to(root_path) expect(flash[:alert]).to eq("Something went wrong") diff --git a/spec/requests/home_controller_spec.rb b/spec/requests/home_controller_spec.rb new file mode 100644 index 000000000..4310d2c1e --- /dev/null +++ b/spec/requests/home_controller_spec.rb @@ -0,0 +1,38 @@ +require "rails_helper" + +RSpec.describe "HomeController", type: :request do + describe "GET /" do + context "when not signed in" do + it "renders index successfully" do + get root_path + expect(response).to have_http_status(:success) + end + end + + context "when signed in as regular user" do + let(:user) { create(:user) } + + before do + sign_in user + end + + it "redirects to profile page" do + get root_path + expect(response).to redirect_to(profile_path) + end + end + + context "when signed in as admin" do + let(:admin) { create(:user, :admin) } + + before do + sign_in admin + end + + it "redirects to admin dashboard" do + get root_path + expect(response).to redirect_to(admin_dashboard_path) + end + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 3d0340b93..311e8d583 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -50,7 +50,6 @@ # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. - 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: From e1b99598c466da515a53a3469d770a58ef95fa72 Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 20:11:20 -0300 Subject: [PATCH 18/20] adjust readme --- README.md | 73 ------------------------------------------------------- 1 file changed, 73 deletions(-) diff --git a/README.md b/README.md index bb3799ccd..767b5cb97 100644 --- a/README.md +++ b/README.md @@ -111,77 +111,4 @@ Maria,Santos,maria@example.com,manager - Altere senha - Visualize histórico de login -## 🏗️ Arquitetura - -### Estrutura de Diretórios - -``` -app/ -├── controllers/ -│ ├── application_controller.rb -│ ├── home_controller.rb -│ ├── users_controller.rb -│ └── admin/ -│ ├── dashboard_controller.rb -│ ├── users_controller.rb -│ └── imports_controller.rb -├── models/ -│ ├── user.rb -│ ├── import.rb -│ └── concerns/ -│ └── dashboard_broadcaster.rb -├── services/ -│ ├── application_service.rb -│ ├── user_management_service.rb -│ ├── user_search_service.rb -│ └── dashboard_stats_service.rb -├── jobs/ -│ └── user_import_job.rb -├── channels/ -│ ├── dashboard_channel.rb -│ └── import_progress_channel.rb -└── views/ - ├── layouts/ - ├── shared/ - ├── home/ - ├── users/ - └── admin/ -``` - -## 🛡️ Segurança - -### Implementações de Segurança - -- **Strong Parameters** para mass assignment protection -- **Authorization checks** em todos os controllers -- **Role-based access control** (RBAC) -- **File upload validation** com whitelist de tipos -- **CSRF protection** habilitada -- **SQL injection protection** via ActiveRecord -- **XSS protection** com sanitização automática - -### Auditoria - -- **Trackable fields** para monitoramento de login -- **Logs de atividade** para ações administrativas -- **Histórico de importações** com timestamps - -## 📡 API - -### Endpoints Principais - -| Método | Endpoint | Descrição | Auth | -|--------|----------|-----------|------| -| `GET` | `/` | Página inicial | - | -| `POST` | `/users/sign_in` | Login | - | -| `GET` | `/admin/dashboard` | Dashboard admin | Admin | -| `GET` | `/admin/users` | Lista usuários | Admin | -| `POST` | `/admin/imports` | Upload CSV | Admin | -| `GET` | `/users/profile` | Perfil do usuário | User | - -### WebSocket Channels - -- **DashboardChannel** - Métricas em tempo real -- **ImportProgressChannel** - Status de importação - ⭐ **Se este projeto foi útil, considere dar uma estrela!** From 1e608c3145deeb4418d60fe26fa2e79e457eba5b Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 20:18:31 -0300 Subject: [PATCH 19/20] add user in readme --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 767b5cb97..eea010084 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,9 @@ docker compose up ``` http://localhost:3000 ``` +5. **Entre com:** +admin@example.com +password123 ## 📖 Como Usar From e48c9893f1cf4dfebcf717b5b70977412705241e Mon Sep 17 00:00:00 2001 From: lucasleandro1 Date: Tue, 11 Nov 2025 20:20:23 -0300 Subject: [PATCH 20/20] add user in readme --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index eea010084..863a9f991 100644 --- a/README.md +++ b/README.md @@ -75,9 +75,11 @@ docker compose up ``` http://localhost:3000 ``` -5. **Entre com:** +6. **Entre com:** +``` admin@example.com password123 +``` ## 📖 Como Usar