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/.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/.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/.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/.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/.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/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 new file mode 100644 index 000000000..b1a7d64d4 --- /dev/null +++ b/Gemfile @@ -0,0 +1,111 @@ +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, :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" +# 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", "~> 6.5" +gem "redis", "~> 4.8" + +# 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..edd57044f --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,537 @@ +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 (2.2.21) + rack-session (1.0.2) + rack (< 3) + rack-test (2.2.0) + rack (>= 1.3) + rackup (1.0.1) + rack (< 3) + webrick + 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 (4.8.1) + 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 (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) + 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) + webrick (1.9.1) + 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) + redis (~> 4.8) + roo (~> 2.9) + rspec-rails (~> 7.0) + rubocop-rails-omakase + selenium-webdriver + shoulda-matchers + sidekiq (~> 6.5) + 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/README.md b/README.md index e18f57431..863a9f991 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,119 @@ -# 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. + +## ✨ 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) +- **Devise** (autenticação) + +### 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 + +### Setup Local + +1. **Clone o repositório:** +```bash +git clone https://github.com/lucasleandro1/Fullstack-Developer.git +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 +``` +6. **Entre com:** +``` +admin@example.com +password123 +``` + +## šŸ“– 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 + +⭐ **Se este projeto foi Ćŗtil, considere dar uma estrela!** 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/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..952758d73 --- /dev/null +++ b/app/assets/stylesheets/_custom.scss @@ -0,0 +1,68 @@ +// 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; +} + +// 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..e872be099 --- /dev/null +++ b/app/assets/stylesheets/application.scss @@ -0,0 +1,11 @@ +// Custom styles (Bootstrap loaded via CDN in layout) +@use "custom"; +@use "components/navbar"; +@use "components/forms"; +@use "components/cards"; +@use "components/tables"; +@use "components/flash_messages"; + +// 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/_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/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..50bed5279 --- /dev/null +++ b/app/assets/stylesheets/layouts/_authentication.scss @@ -0,0 +1,150 @@ +// 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; + position: relative; + + // Add padding for flash messages when they are present + .flash-messages-container.auth-page + & { + padding-top: 120px; + } +} + +.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-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; + 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/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/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..748559e39 --- /dev/null +++ b/app/controllers/admin/imports_controller.rb @@ -0,0 +1,63 @@ +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 + 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..89965a4f8 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,34 @@ +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 + + before_action :authenticate_user! + before_action :configure_permitted_parameters, if: :devise_controller? + + def after_sign_in_path_for(resource) + if resource.admin? + admin_dashboard_path + else + profile_path + end + end + + def after_sign_out_path_for(resource_or_scope) + 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 + + 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 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/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..07ee758ad --- /dev/null +++ b/app/jobs/user_import_job.rb @@ -0,0 +1,149 @@ +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) + + spreadsheet = open_spreadsheet(file_path, import.file_name) + headers = spreadsheet.row(1) + + validate_headers(headers, import) + + 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) + + if (index + 1) % 10 == 0 || (index + 1) == total_rows + import.update_progress! + broadcast_progress(import) + end + end + + 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 + user.update!(user_data.except(:email)) + import.increment!(:successful_rows) + else + 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/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..a46104466 --- /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, + 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..1506c2ff0 --- /dev/null +++ b/app/models/import.rb @@ -0,0 +1,79 @@ +class Import < ApplicationRecord + belongs_to :user + has_one_attached :file + + 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 } + + 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 + + def pending? + status == "pending" + end + + def processing? + status == "processing" + end + + def completed? + status == "completed" + end + + def failed? + status == "failed" + end + + 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 + + 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 + + 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..275fe0332 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,60 @@ +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 + + has_one_attached :avatar_image + has_many :imports, dependent: :destroy + + 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 + + enum :role, { user: "user", admin: "admin" } + + scope :admins, -> { where(role: "admin") } + scope :users, -> { where(role: "user") } + + 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 + + def self.total_count + count + end + + def self.admin_count + admins.count + end + + def self.user_count + users.count + end +end 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..865c05319 --- /dev/null +++ b/app/services/dashboard_stats_service.rb @@ -0,0 +1,79 @@ +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, + 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 + } + 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 + 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..7799aee3d --- /dev/null +++ b/app/services/user_management_service.rb @@ -0,0 +1,66 @@ +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 + params_with_password = filtered_params.merge( + password: generate_secure_password, + password_confirmation: nil + ) + + user = User.new(params_with_password) + + if user.save + 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 diff --git a/app/views/admin/dashboard/index.html.erb b/app/views/admin/dashboard/index.html.erb new file mode 100644 index 000000000..14be0c274 --- /dev/null +++ b/app/views/admin/dashboard/index.html.erb @@ -0,0 +1,214 @@ +<% 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[: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 %> +
+
+
+
+
+
+
+
+ + diff --git a/app/views/admin/imports/create.html.erb b/app/views/admin/imports/create.html.erb new file mode 100644 index 000000000..a60211cb4 --- /dev/null +++ b/app/views/admin/imports/create.html.erb @@ -0,0 +1,327 @@ +<% 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..5366ebc40 --- /dev/null +++ b/app/views/admin/imports/index.html.erb @@ -0,0 +1,218 @@ +<% 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..a743adeb2 --- /dev/null +++ b/app/views/admin/imports/show.html.erb @@ -0,0 +1,229 @@ +<% 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 %> + <% if @import.file.attached? %> + <%= link_to @import.file, + class: "btn btn-outline-primary", + download: @import.file_name do %> + Download Original File + <% end %> + <% 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..cc6801eb3 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,316 @@ +<% 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..587a6c1d3 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,192 @@ +<% content_for :title, "User Management" %> + +
+
+
+

User Management

+
+ <%= 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 %> +
+
+
+
+ <% 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 %> +
+
+
diff --git a/app/views/admin/users/new.html.erb b/app/views/admin/users/new.html.erb new file mode 100644 index 000000000..1be701134 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,313 @@ +<% 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 %> +
+
+ +
+ +
+ <%= 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 +
+
+
+ +
+ <%= 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..f1017b444 --- /dev/null +++ b/app/views/admin/users/show.html.erb @@ -0,0 +1,215 @@ +<% content_for :title, "User Details - #{@user.display_name}" %> + +
+
+
+

User Details

+
+
+ <%= 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 %> + <%= 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 %> + 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/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..ba7e61c33 --- /dev/null +++ b/app/views/devise/passwords/edit.html.erb @@ -0,0 +1,108 @@ +<% 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 +
+ + +
+
+
+
+
+ + diff --git a/app/views/devise/passwords/new.html.erb b/app/views/devise/passwords/new.html.erb new file mode 100644 index 000000000..e9efd1d76 --- /dev/null +++ b/app/views/devise/passwords/new.html.erb @@ -0,0 +1,73 @@ +<% content_for :title, "Forgot Password" %> + +
+
+
+
+
+
+
+ +
+

Forgot Password?

+

Enter your email to reset your password

+
+ + <%= 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 +
+ + +
+
+
+
+
+ + 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..4edf285ed --- /dev/null +++ b/app/views/devise/registrations/new.html.erb @@ -0,0 +1,175 @@ +<% content_for :title, "Create Account" %> + +
+
+
+
+
+
+
+ +
+

Create Account

+

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), + local: true, + html: { + class: "auth-form needs-validation", + novalidate: true, + multipart: true + } do |f| %> + +
+ <%= 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..54cc1504a --- /dev/null +++ b/app/views/devise/sessions/new.html.erb @@ -0,0 +1,89 @@ +<% content_for :title, "Sign In" %> + +
+
+
+
+
+
+
+ +
+

Welcome Back

+

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), + 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..f4894566b --- /dev/null +++ b/app/views/devise/shared/_error_messages.html.erb @@ -0,0 +1,18 @@ +<% if resource.errors.any? %> + +<% end %> 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/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..307716412 --- /dev/null +++ b/app/views/home/index.html.erb @@ -0,0 +1,18 @@ +<% 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" %> +
+
+
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..30f7786da --- /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? %> + + <% unless params[:controller]&.include?('devise') %> + <%= render 'shared/flash_messages' %> + <% end %> + +
+ <%= yield %> +
+ + + + 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/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/shared/_flash_messages.html.erb b/app/views/shared/_flash_messages.html.erb new file mode 100644 index 000000000..48b6bde05 --- /dev/null +++ b/app/views/shared/_flash_messages.html.erb @@ -0,0 +1,70 @@ +<% if notice || alert || flash.any? %> + <% + # 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/app/views/shared/_navbar.html.erb b/app/views/shared/_navbar.html.erb new file mode 100644 index 000000000..8709415a7 --- /dev/null +++ b/app/views/shared/_navbar.html.erb @@ -0,0 +1,46 @@ + \ No newline at end of file diff --git a/app/views/users/edit.html.erb b/app/views/users/edit.html.erb new file mode 100644 index 000000000..9caba46fa --- /dev/null +++ b/app/views/users/edit.html.erb @@ -0,0 +1,207 @@ +<% 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..ca789b2b3 --- /dev/null +++ b/app/views/users/show.html.erb @@ -0,0 +1,84 @@ +<% 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 %> +
+
+ +
+ +
+
+
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 %> +
+
+
+
+
+
+
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/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/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/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/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/database.yml b/config/database.yml new file mode 100644 index 000000000..b3e918161 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,69 @@ +# 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: <%= 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 + 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/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/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..3ed998833 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,75 @@ +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 + + # Configure ActiveJob to use Sidekiq + config.active_job.queue_adapter = :sidekiq + + # 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..44b0bc0c7 --- /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 = :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. + # 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/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/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/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/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/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/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/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/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 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 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/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/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/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..b964c159a --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,83 @@ +# 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_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 + 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" + 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.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 + + 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/docker-compose.yml b/docker-compose.yml new file mode 100644 index 000000000..2117c17c1 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,79 @@ +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 + - RAILS_MASTER_KEY=${RAILS_MASTER_KEY} + volumes: + - .:/rails + - bundle_cache:/usr/local/bundle + - /rails/tmp + - /rails/log + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + stdin_open: true + tty: true + + # 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 + - RAILS_MASTER_KEY=${RAILS_MASTER_KEY} + volumes: + - .:/rails + - bundle_cache:/usr/local/bundle + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + web: + condition: service_started + command: ["bundle", "exec", "sidekiq"] + +volumes: + postgres_data: + bundle_cache: \ No newline at end of file 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/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/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 000000000..c4c9dbfbb Binary files /dev/null and b/public/icon.png differ 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/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/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..8046881a9 --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +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/files/users_valid.csv b/spec/fixtures/files/users_valid.csv new file mode 100644 index 000000000..9a04cb377 --- /dev/null +++ b/spec/fixtures/files/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/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 new file mode 100644 index 000000000..f017dde43 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,53 @@ +require 'rails_helper' + +RSpec.describe User, type: :model do + let(:user) { build(:user) } + let(:admin) { build(:user, :admin) } + + describe 'validations' do + it 'validates presence of required fields' do + expect(user).to be_valid + + user.full_name = '' + expect(user).not_to be_valid + + user.email = '' + expect(user).not_to be_valid + end + + it 'validates role inclusion' do + expect { user.role = 'invalid' }.to raise_error(ArgumentError) + end + end + + describe 'associations' do + it { should have_one_attached(:avatar_image) } + it { should have_many(:imports) } + end + + describe 'methods' do + it 'checks admin role' do + expect(user.admin?).to be false + expect(admin.admin?).to be true + end + + it 'returns display name' do + expect(user.display_name).to eq(user.full_name) + end + + it 'returns initials' do + user.full_name = 'John Doe' + expect(user.initials).to eq('JD') + end + end + + describe 'scopes' do + it 'filters by role' do + create(:user) + create(:user, :admin) + + 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 new file mode 100644 index 000000000..fe41cc47e --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,89 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'simplecov' +SimpleCov.start 'rails' do + minimum_coverage 90 + + add_filter '/spec/' + 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/' + + add_group 'Models', 'app/models' + add_group 'Controllers', 'app/controllers' +end + + +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 + + config.include(Shoulda::Matchers::ActiveModel, type: :model) + config.include(Shoulda::Matchers::ActiveRecord, type: :model) + 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 new file mode 100644 index 000000000..f70ef3616 --- /dev/null +++ b/spec/requests/admin/dashboard_controller_spec.rb @@ -0,0 +1,74 @@ +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_data) do + { + users: { total: 5, recent: [] }, + imports: { total: 10 }, + activity: { logins: 20 }, + growth: { weekly: 3 } + } + end + + let(:service_result) do + double(success?: true, data: service_data) + 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 "calls the dashboard service with current_user" do + get admin_dashboard_path + expect(DashboardStatsService).to have_received(:call).with(admin) + end + + it "renders the index template" do + get admin_dashboard_path + expect(response).to render_template(:index) + 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 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/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 new file mode 100644 index 000000000..226dae096 --- /dev/null +++ b/spec/requests/admin/users_spec.rb @@ -0,0 +1,119 @@ +require 'rails_helper' + +RSpec.describe "Admin::Users", type: :request 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_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 /admin/users/:id" do + it "returns http success" do + user = create(:user) + get admin_user_path(user) + expect(response).to have_http_status(:success) + end + end + + describe "GET /admin/users/new" do + it "returns http success" do + get new_admin_user_path + expect(response).to have_http_status(:success) + end + end + + 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 /admin/users/:id/edit" do + it "returns http success" do + user = create(:user) + get edit_admin_user_path(user) + expect(response).to have_http_status(:success) + end + end + + 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 "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 "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_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/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/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..311e8d583 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,85 @@ +# 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. + + # 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 diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/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