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/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..83610cfa4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: +- package-ecosystem: bundler + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..b1041f81c --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,124 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +permissions: + contents: read + +jobs: + security_scan: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Scan for common Rails security vulnerabilities using static analysis + run: bin/brakeman --no-pager + + - name: Scan for known security vulnerabilities in gems used + run: bin/bundler-audit + + - name: Scan for security vulnerabilities in JavaScript dependencies + run: bin/importmap audit + + lint: + runs-on: ubuntu-latest + env: + RUBOCOP_CACHE_ROOT: tmp/rubocop + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Prepare RuboCop cache + uses: actions/cache@v4 + env: + DEPENDENCIES_HASH: ${{ hashFiles('.ruby-version', '**/.rubocop.yml', '**/.rubocop_todo.yml', 'Gemfile.lock') }} + with: + path: ${{ env.RUBOCOP_CACHE_ROOT }} + key: rubocop-${{ runner.os }}-${{ env.DEPENDENCIES_HASH }}-${{ github.ref_name == github.event.repository.default_branch && github.run_id || 'default' }} + restore-keys: | + rubocop-${{ runner.os }}-${{ env.DEPENDENCIES_HASH }}- + + - name: Lint code for consistent style + run: bin/rubocop -f github + + test: + runs-on: ubuntu-latest + env: + RAILS_ENV: test + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Set up Node + uses: actions/setup-node@v4 + with: + node-version: 22 + + - name: Determine the Playwright version to install (for Capybara system specs) + run: | + echo "PLAYWRIGHT_CLI_VERSION=$(bundle exec ruby -e 'require "playwright"; puts Playwright::COMPATIBLE_PLAYWRIGHT_VERSION.strip')" >> "$GITHUB_ENV" + + - name: Cache the Playwright npm package + id: playwright-npm-cache + uses: actions/cache@v4 + with: + path: node_modules + key: playwright-npm-${{ runner.os }}-${{ env.PLAYWRIGHT_CLI_VERSION }} + + - name: Install the Playwright npm package + if: steps.playwright-npm-cache.outputs.cache-hit != 'true' + run: npm install playwright@${{ env.PLAYWRIGHT_CLI_VERSION }} + + - name: Cache Playwright browser binaries + id: playwright-cache + uses: actions/cache@v4 + with: + path: ~/.cache/ms-playwright + key: playwright-${{ runner.os }}-${{ env.PLAYWRIGHT_CLI_VERSION }} + + # Only the browser binary itself is cacheable — its OS-level dependencies are + # installed system-wide via apt and never persist on this ephemeral runner, but + # installing just those (no browser download) is fast, unlike --with-deps. + - name: Install Chromium and its OS dependencies (cache miss) + if: steps.playwright-cache.outputs.cache-hit != 'true' + run: ./node_modules/.bin/playwright install --with-deps chromium + + - name: Install Chromium's OS dependencies only (cache hit) + if: steps.playwright-cache.outputs.cache-hit == 'true' + run: ./node_modules/.bin/playwright install-deps chromium + + - name: Build Tailwind CSS + run: bin/rails tailwindcss:build + + - name: Prepare test databases in parallel + run: bin/rails parallel:create parallel:load_schema + + - name: Run test suite in parallel + run: bundle exec parallel_rspec spec/ + + - name: Upload coverage report + uses: actions/upload-artifact@v4 + with: + name: coverage-report + path: coverage/ + diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 4b950cc66..1ae8eabb0 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -8,44 +8,20 @@ on: jobs: CodeQL-Build: - runs-on: ubuntu-latest + permissions: + security-events: write + contents: read steps: - name: Checkout repository - uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 + uses: actions/checkout@v4 - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - - # Initializes the CodeQL tools for scanning. + # Autodetects languages present in the repo (Ruby, JavaScript). No Autobuild + # step: that's only needed for compiled languages (C/C++, C#, Java), and this + # is a Ruby/Rails app with no compilation step. - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - # Override language selection by uncommenting this and choosing your languages - # with: - # languages: go, javascript, csharp, python, cpp, java - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release + uses: github/codeql-action/init@v3 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + uses: github/codeql-action/analyze@v3 diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..9963139e5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,61 @@ +# Bundler +/.bundle +/vendor/bundle + +# Environment secrets +.env +.env.* +!.env.example +/config/master.key +/config/credentials/*.key + +# SQLite databases +/storage/*.sqlite3 +/storage/*.sqlite3-* + +# Logs +/log/* +!/log/.keep + +# Temp files +/tmp/* +!/tmp/.keep + +# Uploaded files (local dev) +/storage/[^.]*/ + +# Assets build output +/public/assets +/public/packs + +# Node (if ever needed) +/node_modules +yarn-error.log + +# macOS +.DS_Store + +# IDE +.idea/ +.vscode/ +*.swp +*.swo + +# Coverage +/coverage + +# Aider Chat +.aider* + +# Ruby LSP +.ruby-lsp/ + +# RSpec persisted run status (--only-failures / --next-failure) +/spec/examples.txt + +# Ignore key files for decrypting credentials and more. +/config/*.key + + +/app/assets/builds/* +!/app/assets/builds/.keep diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 000000000..a0b053784 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env 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..7d2a13db2 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env 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..17b0567a5 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/usr/bin/env 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..84548ed04 --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env 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..1f9fe844c --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env 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..d53d28cf7 --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/usr/bin/env 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..93e11991d --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.kamal/secrets b/.kamal/secrets new file mode 100644 index 000000000..3a1d81b33 --- /dev/null +++ b/.kamal/secrets @@ -0,0 +1,30 @@ +# Secrets defined here are available for reference under registry/password, env/secret, builder/secrets, +# and accessories/*/env/secret in config/deploy.yml. All secrets should be pulled from either +# password manager, ENV, or a file. DO NOT ENTER RAW CREDENTIALS HERE! This file needs to be safe for git. + +# Example of extracting secrets from 1password (or another compatible pw manager) +# SECRETS=$(kamal secrets fetch --adapter 1password --account your-account --from Vault/Item KAMAL_REGISTRY_PASSWORD RAILS_MASTER_KEY) +# KAMAL_REGISTRY_PASSWORD=$(kamal secrets extract KAMAL_REGISTRY_PASSWORD ${SECRETS}) +# RAILS_MASTER_KEY=$(kamal secrets extract RAILS_MASTER_KEY ${SECRETS}) + +# Example of extracting secrets from Rails credentials +# KAMAL_REGISTRY_PASSWORD=$(rails credentials:fetch kamal.registry_password) + +# Use a GITHUB_TOKEN if private repositories are needed for the image +# GITHUB_TOKEN=$(gh config get -h github.com oauth_token) + +# Grab the registry password from ENV (a GitHub personal access token with `write:packages` +# scope, for the ghcr.io registry configured in config/deploy.yml) +KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# Signs sessions and cookies in production. This app stores no encrypted Rails +# credentials, so secret_key_base is supplied directly via ENV rather than decrypted +# from config/credentials.yml.enc. Keep the value stable across deploys — changing it +# invalidates every existing session and signed cookie. +SECRET_KEY_BASE=$SECRET_KEY_BASE + +# If you'd rather use your own Rails credentials (bin/rails credentials:edit generates +# config/master.key + config/credentials.yml.enc), swap the line above for the one +# below and change env/secret in config/deploy.yml to match. +# Improve security by using a password manager. Never check config/master.key into git! +# RAILS_MASTER_KEY=$(cat config/master.key) diff --git a/.rspec b/.rspec new file mode 100644 index 000000000..c99d2e739 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper 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..2f9dd5fd1 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-4.0.0 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..135f46c9e --- /dev/null +++ b/Dockerfile @@ -0,0 +1,80 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t fullstack_developer . +# docker run -d -p 80:80 -e SECRET_KEY_BASE="$(openssl rand -hex 64)" --name fullstack_developer fullstack_developer + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=4.0.0 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips sqlite3 && \ + ln -s /usr/lib/$(uname -m)-linux-gnu/libjemalloc.so.2 /usr/local/lib/libjemalloc.so && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Set production environment variables and enable jemalloc for reduced memory usage and latency. +# RUBYOPT enables Ruby 4's ZJIT for extra runtime performance; it's a silent no-op (just a startup +# warning) on any Ruby build without ZJIT support, so it's safe to leave on unconditionally. +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" \ + LD_PRELOAD="/usr/local/lib/libjemalloc.so" \ + RUBYOPT="--zjit" + +# Throw-away build stage to reduce size of final image +FROM base AS build + +# Install packages needed to build gems +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libvips libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY vendor/* ./vendor/ +COPY Gemfile Gemfile.lock ./ + +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + # -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 + bundle exec bootsnap precompile -j 1 --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times. +# -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 +RUN bundle exec bootsnap precompile -j 1 app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + + + + +# Final stage for app image +FROM base + +# Run and own only the runtime files as a non-root user for security +RUN groupadd --system --gid 1000 rails && \ + useradd rails --uid 1000 --gid 1000 --create-home --shell /bin/bash +USER 1000:1000 + +# Copy built artifacts: gems, application +COPY --chown=rails:rails --from=build "${BUNDLE_PATH}" "${BUNDLE_PATH}" +COPY --chown=rails:rails --from=build /rails /rails + +# Entrypoint prepares the database. +ENTRYPOINT ["/rails/bin/docker-entrypoint"] + +# Start server via Thruster by default, this can be overwritten at runtime +EXPOSE 80 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..49e32b0e2 --- /dev/null +++ b/Gemfile @@ -0,0 +1,100 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.3", ">= 8.1.3.1" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.1" +# 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 Tailwind CSS [https://github.com/rails/tailwindcss-rails] +gem "tailwindcss-rails" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +gem "bcrypt", "~> 3.1.7" + +# 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" + +# Object-oriented authorization for Rails applications [https://github.com/varvet/pundit] +gem "pundit" + +# Reads CSV and XLSX spreadsheets through a single uniform API [https://github.com/roo-rb/roo] +gem "roo" + +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" + + # Audits gems for known security defects (use config/bundler-audit.yml to ignore issues) + gem "bundler-audit", require: false + + # 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 + + # Testing framework [https://github.com/rspec/rspec-rails] + gem "rspec-rails" + + # Test data factories [https://github.com/thoughtbot/factory_bot_rails] + gem "factory_bot_rails" + + # Fake data generator for factories [https://github.com/faker-ruby/faker] + gem "faker" + + # One-liner matchers for common Rails functionality [https://github.com/thoughtbot/shoulda-matchers] + gem "shoulda-matchers" + + # Splits the test suite across parallel processes [https://github.com/grosser/parallel_tests] + gem "parallel_tests" +end + +group :test do + # Code coverage reporting [https://github.com/simplecov-ruby/simplecov] + gem "simplecov", require: false + + # Acceptance test framework [https://github.com/teamcapybara/capybara] + gem "capybara" + + # Playwright driver for Capybara system tests [https://github.com/YusukeIwaki/capybara-playwright-driver] + gem "capybara-playwright-driver" + + # RSpec matchers for testing Pundit policies [https://github.com/pundit-community/pundit-matchers] + gem "pundit-matchers" + + # Stubs HTTP requests for testing outbound calls like AvatarFetcher [https://github.com/bblimke/webmock] + gem "webmock" +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +gem "rails-i18n", "~> 8.1" diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..2d28a0d16 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,660 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + actionmailer (8.1.3.1) + actionpack (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.3.1) + actionview (= 8.1.3.1) + activesupport (= 8.1.3.1) + 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.1.3.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.3.1) + activesupport (= 8.1.3.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.3.6) + activemodel (8.1.3.1) + activesupport (= 8.1.3.1) + activerecord (8.1.3.1) + activemodel (= 8.1.3.1) + activesupport (= 8.1.3.1) + timeout (>= 0.4.0) + activestorage (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activesupport (= 8.1.3.1) + marcel (~> 1.0) + activesupport (8.1.3.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.9.0) + public_suffix (>= 2.0.2, < 8.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.22) + bcrypt_pbkdf (1.1.2) + bigdecimal (4.1.2) + bindex (0.8.1) + bootsnap (1.25.0) + msgpack (~> 1.5) + brakeman (8.0.6) + racc + builder (3.3.0) + bundler-audit (0.9.3) + bundler (>= 1.2.0) + thor (~> 1.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + capybara-playwright-driver (0.5.10) + addressable + capybara + playwright-ruby-client (>= 1.16.0) + concurrent-ruby (1.3.8) + connection_pool (3.0.2) + crack (1.0.1) + bigdecimal + rexml + crass (1.0.7) + csv (3.3.6) + date (3.5.1) + debug (1.11.1) + irb (~> 1.10) + reline (>= 0.3.8) + diff-lcs (1.6.2) + dotenv (3.2.0) + drb (2.2.3) + ed25519 (1.4.0) + erb (6.0.7) + erubi (1.13.1) + et-orbi (1.4.2) + tzinfo + factory_bot (6.6.0) + activesupport (>= 6.1.0) + factory_bot_rails (6.5.1) + factory_bot (~> 6.5) + railties (>= 6.1.0) + faker (3.8.0) + i18n (>= 1.8.11, < 2) + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fugit (1.13.0) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.4.0) + activesupport (>= 6.1) + hashdiff (1.2.1) + i18n (1.15.2) + 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.3) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.9.2) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + json (2.21.2) + kamal (2.12.0) + 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) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.2) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.1) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + matrix (0.4.3) + mime-types (3.7.0) + logger + mime-types-data (~> 3.2025, >= 3.2025.0507) + mime-types-data (3.2026.0701) + mini_magick (5.4.0) + logger + mini_mime (1.1.5) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + msgpack (1.8.4) + net-imap (0.6.6) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.3.0) + 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.3) + nio4r (2.7.5) + nokogiri (1.19.4-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (2.1.0) + parallel_tests (5.7.0) + parallel + parser (3.3.12.0) + ast (~> 2.4.1) + racc + playwright-ruby-client (1.62.0) + base64 + concurrent-ruby (>= 1.1.6) + mime-types (>= 3.0) + pp (0.6.4) + prettyprint + prettyprint (0.2.0) + prism (1.9.0) + propshaft (1.3.2) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + public_suffix (7.0.5) + puma (8.0.2) + nio4r (~> 2.0) + pundit (2.5.2) + activesupport (>= 3.0.0) + pundit-matchers (4.0.0) + rspec-core (~> 3.12) + rspec-expectations (~> 3.12) + rspec-mocks (~> 3.12) + rspec-support (~> 3.12) + raabro (1.5.0) + racc (1.8.1) + rack (3.2.7) + rack-session (2.1.2) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.3.1) + actioncable (= 8.1.3.1) + actionmailbox (= 8.1.3.1) + actionmailer (= 8.1.3.1) + actionpack (= 8.1.3.1) + actiontext (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activemodel (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + bundler (>= 1.15.0) + railties (= 8.1.3.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.1) + loofah (~> 2.25, >= 2.25.2) + 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) + rails-i18n (8.1.0) + i18n (>= 0.7, < 2) + railties (>= 8.0.0, < 9) + railties (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + 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.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.0.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + regexp_parser (2.12.0) + reline (0.7.0) + io-console (~> 0.5) + rexml (3.4.4) + roo (3.0.0) + base64 (~> 0.2) + csv (~> 3) + logger (~> 1) + nokogiri (~> 1) + rubyzip (>= 3.0.0, < 4.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.8) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-rails (8.0.4) + actionpack (>= 7.2) + activesupport (>= 7.2) + railties (>= 7.2) + rspec-core (>= 3.13.0, < 5.0.0) + rspec-expectations (>= 3.13.0, < 5.0.0) + rspec-mocks (>= 3.13.0, < 5.0.0) + rspec-support (>= 3.13.0, < 5.0.0) + rspec-support (3.13.7) + rubocop (1.90.0) + 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.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.50.0) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-performance (1.27.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.37.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.89.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.3.0) + ffi (~> 1.12) + logger + rubyzip (3.6.0) + securerandom (0.4.1) + shoulda-matchers (8.0.1) + activesupport (>= 7.2) + simplecov (1.1.1) + solid_cable (4.0.2) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.10) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.7.0) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sqlite3 (2.9.6-aarch64-linux-gnu) + sqlite3 (2.9.6-aarch64-linux-musl) + sqlite3 (2.9.6-arm-linux-gnu) + sqlite3 (2.9.6-arm-linux-musl) + sqlite3 (2.9.6-x86_64-linux-gnu) + sqlite3 (2.9.6-x86_64-linux-musl) + sshkit (1.25.1) + 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) + tailwindcss-rails (4.6.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.3.3) + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) + tailwindcss-ruby (4.3.3-aarch64-linux-musl) + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) + tailwindcss-ruby (4.3.3-x86_64-linux-musl) + thor (1.5.0) + thruster (0.1.26) + thruster (0.1.26-aarch64-linux) + thruster (0.1.26-x86_64-linux) + timeout (0.6.1) + tsort (0.2.0) + turbo-rails (2.0.23) + 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.2.0) + uri (1.1.1) + useragent (0.16.11) + web-console (4.3.0) + actionview (>= 8.0.0) + bindex (>= 0.4.0) + railties (>= 8.0.0) + webmock (3.26.4) + addressable (>= 2.8.0) + crack (>= 0.3.2) + hashdiff (>= 0.4.0, < 2.0.0) + websocket-driver (0.8.2) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.8.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bcrypt (~> 3.1.7) + bootsnap + brakeman + bundler-audit + capybara + capybara-playwright-driver + debug + factory_bot_rails + faker + image_processing (~> 1.2) + importmap-rails + kamal + parallel_tests + propshaft + puma (>= 5.0) + pundit + pundit-matchers + rails (~> 8.1.3, >= 8.1.3.1) + rails-i18n (~> 8.1) + roo + rspec-rails + rubocop-rails-omakase + shoulda-matchers + simplecov + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + tailwindcss-rails + thruster + turbo-rails + tzinfo-data + web-console + webmock + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.3.1) sha256=e318528295c878a3efdfe25f0f2267c80cb7a76eba41bb5f64d44aa380a3d91b + actionmailbox (8.1.3.1) sha256=5f704972097d843ade8e435e93694a1dac732b926df1717aceba1f3840082b1c + actionmailer (8.1.3.1) sha256=88ea441b28ff02a0c6c006468892642a3d9942affce9d294e81a74504aa5c43c + actionpack (8.1.3.1) sha256=974cb7154548e81f470b1b0f247b99cb38e87825899dca58610596e2817723d0 + actiontext (8.1.3.1) sha256=5da729d833d1a29cddb1eee938878e55e503d2613e00e735f5daf58c2ba98af2 + actionview (8.1.3.1) sha256=2da68b8414c47b43bfbed1ce69c5afe1c04f78c267aacb5660a4cab5ca12cfb6 + activejob (8.1.3.1) sha256=1c8dd275df930df40deecffec63d913a550a33fd94bd298f69721dd96939954a + activemodel (8.1.3.1) sha256=99cc02ce2faec371d14440949d85787ebd23a907c9baef0a9d4bcd4d21888f88 + activerecord (8.1.3.1) sha256=0a2fb6c28f4938f6b013a3a549bec0a7e37d535f3dc8990e804bcc3258c0403b + activestorage (8.1.3.1) sha256=f555254f387b1cffa499d2fd3115d12635eadc5b15206a8534316a67036163ef + activesupport (8.1.3.1) sha256=85458765f25ea48b9019c46b6bb3fa5683197bf4280d9f06710a6e8d7a831376 + addressable (2.9.0) sha256=7fdf6ac3660f7f4e867a0838be3f6cf722ace541dd97767fa42bc6cfa980c7af + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b + bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032 + bcrypt_pbkdf (1.1.2) sha256=c2414c23ce66869b3eb9f643d6a3374d8322dfb5078125c82792304c10b94cf6 + bigdecimal (4.1.2) sha256=53d217666027eab4280346fba98e7d5b66baaae1b9c3c1c0ffe89d48188a3fbd + bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e + bootsnap (1.25.0) sha256=41059e7d0f9cb4023a33465d095f64b913fc9d1b808d6524c307da945fbcffcf + brakeman (8.0.6) sha256=759cc69341115e6c2dcd47b6fd8649a0b9bd540e3585ac8a0a94e31c66fee386 + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + bundler-audit (0.9.3) sha256=81c8766c71e47d0d28a0f98c7eed028539f21a6ea3cd8f685eb6f42333c9b4e9 + capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef + capybara-playwright-driver (0.5.10) sha256=e48e572d72bc1043c644fab44985be0a1e75d7d6917dc298355581848982a2c3 + concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 + connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a + crack (1.0.1) sha256=ff4a10390cd31d66440b7524eb1841874db86201d5b70032028553130b6d4c7e + crass (1.0.7) sha256=94868719948664c89ddcaf0a37c65048413dfcb1c869470a5f7a7ceb5390b295 + csv (3.3.6) sha256=aba61e7e507a66f03d45cb1f3c4b6359861c3504038b422962875dce099e4456 + date (3.5.1) sha256=750d06384d7b9c15d562c76291407d89e368dda4d4fff957eb94962d325a0dc0 + debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6 + diff-lcs (1.6.2) sha256=9ae0d2cba7d4df3075fe8cd8602a8604993efc0dfa934cff568969efb1909962 + dotenv (3.2.0) sha256=e375b83121ea7ca4ce20f214740076129ab8514cd81378161f11c03853fe619d + drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 + ed25519 (1.4.0) sha256=16e97f5198689a154247169f3453ef4cfd3f7a47481fde0ae33206cdfdcac506 + erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c + factory_bot (6.6.0) sha256=1fc1b3b5620ec980a6a27aec1b6ec8c250ca82962e970e8a40f93e8d388d4b89 + factory_bot_rails (6.5.1) sha256=d3cc4851eae4dea8a665ec4a4516895045e710554d2b5ac9e68b94d351bc6d68 + faker (3.8.0) sha256=c147b308df73a90f27a4fc84f18d4c22ef0ad9c2a64b2b61c86fd0ca71753efc + ffi (1.17.4-aarch64-linux-gnu) sha256=b208f06f91ffd8f5e1193da3cae3d2ccfc27fc36fba577baf698d26d91c080df + ffi (1.17.4-aarch64-linux-musl) sha256=9286b7a615f2676245283aef0a0a3b475ae3aae2bb5448baace630bb77b91f39 + ffi (1.17.4-arm-linux-gnu) sha256=d6dbddf7cb77bf955411af5f187a65b8cd378cb003c15c05697f5feee1cb1564 + ffi (1.17.4-arm-linux-musl) sha256=9d4838ded0465bef6e2426935f6bcc93134b6616785a84ffd2a3d82bc3cf6f95 + ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d + ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e + fugit (1.13.0) sha256=a4f093fce740da52f216740a5041e2a594ea763cdb89e8b2754ca4399634ab18 + globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 + hashdiff (1.2.1) sha256=9c079dbc513dfc8833ab59c0c2d8f230fa28499cc5efb4b8dd276cf931457cd1 + i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 + image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb + importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a + io-console (0.9.2) sha256=efa74f891dd03c0939a931dfc6e74c2813d904763d456ea9762b0525e748db08 + irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 + json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa + language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.2) sha256=2007f746959ac65552456e04b433e83deb22759ab38c838b4445c70e43425918 + mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b + mime-types (3.7.0) sha256=dcebf61c246f08e15a4de34e386ebe8233791e868564a470c3fe77c00eed5e56 + mime-types-data (3.2026.0701) sha256=cd8811e1fb89d836499ba0582368a10ee74cef929ba956d1d5ddca045e6a730f + mini_magick (5.4.0) sha256=f120af581d9ed4ec52c57f35a67a605d112bb1d8f582d1415b147fda42d11d78 + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + msgpack (1.8.4) sha256=4411c22d350dd1c20250f7eada3cca2695438c2f769cf0782f0cd065d90a3e7b + net-imap (0.6.6) sha256=96aa4ee50df3060203e649efc341f53480b791d49e150f2fdebf68beb141a8df + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.3.0) sha256=ba310c3d4f1cad46bb1ab20336b06669b1ff8f7c568d9cb9342b32a718547472 + net-scp (4.1.0) sha256=a99b0b92a1e5d360b0de4ffbf2dc0c91531502d3d4f56c28b0139a7c093d1a5d + net-sftp (4.0.0) sha256=65bb91c859c2f93b09826757af11b69af931a3a9155050f50d1b06d384526364 + net-smtp (0.5.1) sha256=ed96a0af63c524fceb4b29b0d352195c30d82dd916a42f03c62a3a70e5b70736 + net-ssh (7.3.3) sha256=831def58b2c51dcef66ec00d29397d4f210de89c19fe78f95873ca30f386e86a + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.4-aarch64-linux-gnu) sha256=1269fb644a6de405057a53dd5c762b1209b43ca7424f839454d3dbc677c31a8f + nokogiri (1.19.4-aarch64-linux-musl) sha256=35c65b9ce72b3bb03207bdbe7067915019dc18c1b9b59139684bd6690fdd01af + nokogiri (1.19.4-arm-linux-gnu) sha256=a301313e38bb065d68239e79734bcd6f56fb6efaacebde29e9abf2a4735340ca + nokogiri (1.19.4-arm-linux-musl) sha256=588923c101bcfa78869734d247d25b598674323e7f22474fc468f6e5647311eb + nokogiri (1.19.4-x86_64-linux-gnu) sha256=379fae440b28915e3f19d752ce2dcf8465ed2b2fbefd2a7ca0dd497bc981a06a + nokogiri (1.19.4-x86_64-linux-musl) sha256=17dfb7c1fa194ae02fbf7c51a7afc8d278045ab3fdacfd86f91d02d7b274470b + ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 + parallel (2.1.0) sha256=b35258865c2e31134c5ecb708beaaf6772adf9d5efae28e93e99260877b09356 + parallel_tests (5.7.0) sha256=3f1762c46ca2c223b8af8ef877217f9d76974e191bfa934f2580b58bcf1d005c + parser (3.3.12.0) sha256=21a6d7f755d5a24dfbdc6e6b772e4e879a52e7631a88bc5a3a134606052c9828 + playwright-ruby-client (1.62.0) sha256=44eb6051ab7987f68a1288a7db7892403e59680116739987729c5fecfdb55715 + pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570 + prettyprint (0.2.0) sha256=2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e + public_suffix (7.0.5) sha256=1a8bb08f1bbea19228d3bed6e5ed908d1cb4f7c2726d18bd9cadf60bc676f623 + puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb + pundit (2.5.2) sha256=e374152baa24f90b630428293faf4b4c5468fc3cc010165f7d8fcb44ce108bbd + pundit-matchers (4.0.0) sha256=59d6077a1d575ea7cceca3ed73df5257488ee1a111ec707b2a797e76908cffd5 + raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7 + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.3.1) sha256=ccd11a36bfc171bf9c66d585d14c0ece91c0c9dde840aae60c0118d6f5c9c52a + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.1) sha256=e797a7c9b01e567307e317c576b49ab4168017e63eea4dba9ce3cb587e2f22c2 + rails-i18n (8.1.0) sha256=52d5fd6c0abef28d84223cc05647f6ae0fd552637a1ede92deee9545755b6cf3 + railties (8.1.3.1) sha256=2388a232579a00cefea4487de66c8553c3408c1300abdc6cf1799d86ffb04487 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674 + rdoc (8.0.0) sha256=03bf8c08a9639658855a0cfd77c0abca8325c227693f7f33f82957811348c469 + regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb + reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d + rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 + roo (3.0.0) sha256=6fdd7a9158d657c69768b4168754ff2110cc21fdc01a1bec1010820cb05c91b1 + rspec-core (3.13.6) sha256=a8823c6411667b60a8bca135364351dda34cd55e44ff94c4be4633b37d828b2d + rspec-expectations (3.13.5) sha256=33a4d3a1d95060aea4c94e9f237030a8f9eae5615e9bd85718fe3a09e4b58836 + rspec-mocks (3.13.8) sha256=086ad3d3d17533f4237643de0b5c42f04b66348c28bf6b9c2d3f4a3b01af1d47 + rspec-rails (8.0.4) sha256=06235692fc0892683d3d34977e081db867434b3a24ae0dd0c6f3516bad4e22df + rspec-support (3.13.7) sha256=0640e5570872aafefd79867901deeeeb40b0c9875a36b983d85f54fb7381c47c + rubocop (1.90.0) sha256=9eb4c065b5c5154e4ef554c547972f3905a9eb6b53e657e580b6796b54bf8242 + rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db + rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce + rubocop-rails (2.37.0) sha256=6e1645add5060e0328f8ddda0d820f55697c591394398bf14bb9dccb62f14b7e + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374 + rubyzip (3.6.0) sha256=268994d44d62282d1cfd99bf10eae48d7267199158ad7ea3e1fee2da9458b695 + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + shoulda-matchers (8.0.1) sha256=5dbb46e5765b9da225111b085e0819e8c8a121ff94bba430a153eb1ea2c60288 + simplecov (1.1.1) sha256=25825ef13f0b2e74694d769817dad6ab8e90131dabdaa666e522fea105521e78 + solid_cable (4.0.2) sha256=084636a67679ad00d23088b33c84047e614bcf41ee559db24b414d83cdc42d03 + solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 + solid_queue (1.7.0) sha256=6566b70b801d1c317c81bba7bcdd5677c019afac584a30374b4164002ca356d3 + sqlite3 (2.9.6-aarch64-linux-gnu) sha256=d8b1f7d23efd7abac285775a9566562fc7debfef79d594e3a20354406fb7907c + sqlite3 (2.9.6-aarch64-linux-musl) sha256=3579e1c98cdc7ff5c3722847bb63ed4e1efb7ff675cb5e1e48ef2d4da5fb3bc9 + sqlite3 (2.9.6-arm-linux-gnu) sha256=33541500e3615da02afe54a9cc38b17a6985d3cf9d8b76d6d0a83002f114e7ec + sqlite3 (2.9.6-arm-linux-musl) sha256=c5490af48bb228fefa54314e9541375c3907e70f8109f3881b5ff97e1c93ae33 + sqlite3 (2.9.6-x86_64-linux-gnu) sha256=613188ce02f614126ddbc38c5e217ccffd6306d0dcd9adca9764547aa890a634 + sqlite3 (2.9.6-x86_64-linux-musl) sha256=d493b11818a3573387a1d56e1ee8fa00da23a683a7a1cc063e7a0feeed843abf + sshkit (1.25.1) sha256=be3f10b9d6eb0b44d5eaba3f7cbe41bc6bb894bce4339688ac20124391455b78 + stimulus-rails (1.3.4) sha256=765676ffa1f33af64ce026d26b48e8ffb2e0b94e0f50e9119e11d6107d67cb06 + tailwindcss-rails (4.6.0) sha256=d99512867173d55c5ef8890427682299d8539f550cec1408b3d8667a538bd365 + tailwindcss-ruby (4.3.3) sha256=ee0a64030749862deb501acab4c4aaf5adbee13865746a33299d46d7b5d0952a + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) sha256=c86d6dd3eccc85fe0d792a832b06f2bf3c0a7a83b399308aeb9d8f5725f42a6a + tailwindcss-ruby (4.3.3-aarch64-linux-musl) sha256=72b77ca9edea82383dd09510ab520a122e3cb9f9864ca5b38e27698098d2b899 + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) sha256=2337017ff8b02698480eae1e9637cf01faa0e4824db89d067a13c5a5ee38c9b2 + tailwindcss-ruby (4.3.3-x86_64-linux-musl) sha256=27d478c417bcf73828e5b544744c5bdfd5b5cb54f1a266fc4f185281c32efe6c + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + thruster (0.1.26) sha256=6e45e807086b29d51404841bd1ad493b67cd95892fd65dc5afcdd32e82e94ce8 + thruster (0.1.26-aarch64-linux) sha256=2171cb34928c0250830008f535c4ab2ee57846cc3f5d3e96c3475f7b3de7a541 + thruster (0.1.26-x86_64-linux) sha256=3117a6ee430663f845a0457699fe9a05232dcc6c396e2cc83504de5a223c60e8 + timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb + tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f + turbo-rails (2.0.23) sha256=ee0d90733aafff056cf51ff11e803d65e43cae258cc55f6492020ec1f9f9315f + tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b + unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42 + unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f + uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6 + useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 + webmock (3.26.4) sha256=8d8da206d217ebe6968cfb09c77f4533c23074e1432bad865f3994eacbaad50d + websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 + websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 + xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e + zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 + +BUNDLED WITH + 4.0.3 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..da151fee9 --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,2 @@ +web: bin/rails server +css: bin/rails tailwindcss:watch diff --git a/README.md b/README.md index 7829f14ff..8dd57cebe 100644 --- a/README.md +++ b/README.md @@ -1,87 +1,296 @@ -# Modern Fullstack Developer Test (Rails 8 / Ruby 4) - -- 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: -- Target Stack: **Ruby 4.0+** and **Rails 8.0+** -- Database: PostgreSQL, MySQL, or SQLite (configured for production-ready WAL mode) -- Write robust unit, integration, and system tests using parallel testing features -- Deliver with a working multi-stage Dockerfile utilizing Thruster/Kamal-ready defaults -- Show senior best practices (e.g., proper design patterns, solid architecture, strict linter configuration) - -# Our AI Policy -At Umanni, we value efficiency and the modern developer workflow. **You are allowed to use AI coding assistants (ChatGPT, Claude, Copilot, etc.) during this test.** However, transparency is part of our culture. If you use any LLM to generate, refactor, or structure your code, **you must explicitly state which model you used** in a dedicated section at the top of your submission's README.md. Failing to disclose AI usage while using it will invalidate your submission. - -# 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 modern, responsive application to manage users. -- A user must have: - 1. full_name - 2. email - 3. avatar_image (ActiveStorage file upload or remote 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 the Dashboard (updated via real-time streams/frontend state): - - Total number of Users - - Total number of Users grouped by Role -- As an Admin, I must be redirected to the 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 (.csv/.xlsx) into the system in order to asynchronously create new Users. -- As an Admin, I must be able to see the live progress/status of the spreadsheet import process. - -## User Use Cases -- As a User, I must be redirected to my Profile after login. -- As a 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 (Strict Compliance) -These are mandatory. Failing any of them will invalidate your submission. -- **Documentation**: You must write down a detailed README.md in English explaining how to build, seed, and run your app, including your AI disclosure if applicable. -- **Frontend Stack**: You have two choices for the modern monolithic approach: - - **Option A (Classic Modern):** Hotwire (Turbo 8+ / Stimulus) with smooth, reactive UI states. - - **Option B (Modern SPA Monolith):** **React integrated via Inertia.js** (using Vite or the official Rails 8 asset pipeline integration). -- **Styling**: The Frontend must use a modern CSS framework (Tailwind CSS, Bootstrap, or any utility-first library). Keep it beautiful, responsive, and clean. -- **Real-time & Background Processing**: You must leverage native Rails 8 tools (**Solid Cable** for live dashboard counters/import bars and **Solid Queue** for the background import processing). No Redis installation should be required. -- **Authentication**: You must use the new built-in Rails 8 Authentication system (`bin/rails generate authentication`), customized to fit the role constraints. Avoid legacy heavy gems (like Devise). -- **Git Hygiene**: Clean git history with atomic commits, proper descriptions, and a Pull Request-based workflow. - -# What we're expecting to see: -- Modern asset management using **Propshaft** or **Vite Rails** (if choosing Inertia/React). -- .gitignore, .dockerignore configured correctly. -- Clean application configuration using Rails credentials. -- Comprehensive cross-browser support considerations. -- Strict form validations (Frontend interactive feedback + Backend structural validation). -- Parallel testing with at least 90% coverage (using Minitest, RSpec, and Playwright/Capybara for frontend integration). - -# Extra points -- Delivery via a clean **Kamal 2** deployment configuration (`deploy.yml`). -- Advanced SSR (Server-Side Rendering) setup if using **Inertia.js + React**. -- Use of **Thruster** as a zero-config proxy for asset caching and compression in Docker. -- Advanced performance profiling leveraging Ruby 4's **ZJIT** compilation optimizations. - -# What will be assessed -- Code's Semantics, Cleanness, and Maintainability (Senior-level object-oriented design and clean React/Stimulus component lifecycle). -- Modern Rails 8 idiom usage (e.g., Strict structural params handling, Solid architecture separation). -- Basic Security testing against traditional vectors (SQLi, XSS, XSRF) and proper encryption of sensitive DB columns where applicable. +# Fullstack Developer Test — User Management App + +A user management application built for Umanni's Modern Fullstack Developer Test: +role-based authentication, an admin dashboard with real-time counters, full user +CRUD, and asynchronous CSV/XLSX spreadsheet import with a live progress bar. + +### AI Usage Disclosure + +Per Umanni's AI Policy, this is an honest account of the AI assistance actually used: + +- **Claude Code** (Anthropic, powered by Claude models — current session running + **Claude Sonnet 5**) was used throughout the project for code generation, + refactoring, test writing, and this documentation. +- **Aider** with **Claude 3.7 Sonnet** was tried very early on as an initial, + exploratory test of the tool. It did not produce any code that remains in the + current codebase — all application code was written via Claude Code. +- **Gemini** was used to help draft a visual/design redesign roadmap. + +## Tech Stack + +- **Ruby 4.0** / **Rails 8.1** (Ruby 4's ZJIT enabled in production, see + [Architecture Decisions](#architecture-decisions)) +- **Hotwire** (Turbo 8 + Stimulus) — no React/Inertia, see rationale below +- **Tailwind CSS v4** +- **SQLite** (multi-database: primary/cache/queue/cable, native WAL mode) +- **Solid Cache / Solid Queue / Solid Cable** — no Redis required +- **Pundit** for authorization +- **Rails 8 built-in authentication** (`bin/rails generate authentication`) — no Devise +- **RSpec** + FactoryBot + Faker + Shoulda Matchers + SimpleCov + Capybara/Playwright + + `parallel_tests` +- **Propshaft** + importmap for asset management +- **Kamal 2** + **Thruster** for deployment, multi-stage **Docker** build + +## Requirements + +- Ruby 4.0+ (see `.ruby-version`) +- Node.js (only for Playwright's CLI and browser binaries used by system specs — CI + uses Node 22; see [Setup](#setup) for the install order that matters) +- SQLite 3.8+ +- Docker (optional, for containerized run/deploy) +- **libvips** (Required for ActiveStorage image processing) + +> **⚠️ Important Note on Image Processing:** +> Starting with Rails 7, ActiveStorage defaults to using the `vips` variant processor instead of `ImageMagick`. You must have the `libvips` system library installed on your machine to upload and process avatars successfully (e.g., `sudo apt-get install libvips` on Debian/Ubuntu or `brew install vips` on macOS). If this package is missing, ActiveStorage will fail to load the variant processor silently and throw a `NoMethodError (undefined method 'new' for nil)` when attempting to generate image thumbnails. + +## Setup + +```bash +bundle install +npm install # installs the exact Playwright CLI pinned in package.json +npx playwright install chromium # downloads the Chromium binary into ~/.cache/ms-playwright +bin/rails db:prepare # creates all 4 databases and loads the schema +bin/rails db:seed # creates the bootstrap admin user (see below) +``` + +On Linux you may also need Chromium's OS-level libraries, which Playwright installs +with `sudo npx playwright install-deps chromium` (this is what CI does via +`playwright install --with-deps chromium`). + +> **⚠️ Run `npm install` *before* `npx playwright install`.** The `playwright` Ruby +> gem drives a Node Playwright CLI whose version must match the gem's +> `Playwright::COMPATIBLE_PLAYWRIGHT_VERSION` (currently **1.62.1**, pinned exactly +> — no `^` — in `package.json`, so `npm install`/`npm update` can't drift off it). +> With no local `node_modules`, `npx` silently fetches the +> *latest* Playwright instead, which expects a different browser build number than +> the one on disk — so system specs fail with `Executable doesn't exist at +> ~/.cache/ms-playwright/chromium_headless_shell-/...` even right after you +> ran `playwright install`. Installing the pinned CLI first keeps the CLI, the gem, +> and the downloaded browser on the same version. You can verify the two agree with: +> +> ```bash +> bundle exec ruby -e 'require "playwright"; puts Playwright::COMPATIBLE_PLAYWRIGHT_VERSION' +> node -e "console.log(require('./node_modules/playwright/package.json').version)" +> ``` + +## Seeding + +Public registration always creates a `no_admin` user (enforced server-side in +`RegistrationsController`, ignoring any injected `role` param), so there is no way +to reach an admin account from the UI alone. `db/seeds.rb` creates two users, +idempotently, so the app is usable immediately after setup: + +| Role | Email | Password | +|----------|---------------------|----------------| +| Admin | `admin@example.com` | `password123` | +| Regular | `user@example.com` | `password123` | + +```bash +bin/rails db:seed +``` + +Change these default passwords before deploying anywhere reachable by others. + +## Running in development + +```bash +bin/dev # runs `bin/rails server` + `bin/rails tailwindcss:watch` via Procfile.dev +``` + +Visit `http://localhost:3000`, sign in with the seeded admin (or register a new +regular user), and Solid Queue/Solid Cable both run in-process — no extra services to +start. Outgoing mail (password reset / "set your password" for imported users) is +logged to the Rails console (`ApplicationMailer#log_to_console_in_development`, +look for `[Mailer]` lines) and also written to `tmp/mails` — nothing opens +automatically, since a bulk spreadsheet import can send thousands of e-mails at +once. + +## Running the test suite + +```bash +bin/rails db:test:prepare # after any new migration +bundle exec rspec # full suite, sequential +bundle exec rspec spec/path/to_spec.rb # a single file +bundle exec parallel_rspec spec/ # parallel, same as CI + +# System specs (Playwright) — needs the browser installed first, see Setup above. +# Set this if the Playwright CLI isn't otherwise resolvable: +PLAYWRIGHT_CLI_EXECUTABLE_PATH=./node_modules/.bin/playwright bundle exec rspec spec/system +``` + +Quality gates: + +```bash +bundle exec rubocop +bundle exec brakeman -q --no-pager +bundle exec bundler-audit check +``` + +Current state: 0 failures, ≥90% SimpleCov line coverage (enforced via +`SimpleCov.minimum_coverage` — the suite itself fails if coverage regresses below +that bar), 0 RuboCop offenses, 0 Brakeman warnings, 0 bundler-audit vulnerabilities. + +## Running with Docker + +```bash +docker build -t fullstack_developer . +docker run -d -p 3000:80 \ + -e SECRET_KEY_BASE="$(openssl rand -hex 64)" \ + -e SOLID_QUEUE_IN_PUMA=true \ + --name fullstack_developer \ + fullstack_developer +``` + +**No secret to obtain.** This app stores no encrypted Rails credentials (nothing in +`app/`, `lib/`, or `config/` reads `Rails.application.credentials`), so it needs +`secret_key_base` and nothing else — any freshly generated value works, and a clone of +this repo can run the image without being handed a key. `SECRET_KEY_BASE` is read +before credentials are ever touched, so no `config/master.key` is involved. The one +thing the value affects is session and signed-cookie continuity: a new value on every +`docker run` signs everyone out across restarts, which is fine for evaluation but not +for a real deployment — see [Deploying with Kamal 2](#deploying-with-kamal-2). If you +prefer the standard Rails flow, `bin/rails credentials:edit` generates your own +`config/master.key` + `config/credentials.yml.enc` pair, and `-e RAILS_MASTER_KEY=...` +then works instead. + +The image is a non-root, multi-stage build served by **Thruster** (zero-config +asset caching/compression/HTTP proxy) on port 80. `SOLID_QUEUE_IN_PUMA=true` runs +the Solid Queue supervisor inside the same Puma process, so no separate worker +container is needed for this single-server setup. Run `bin/rails db:seed` inside the +container (`docker exec -it fullstack_developer bin/rails db:seed`) to create the +bootstrap admin. + +## Deploying with Kamal 2 + +`config/deploy.yml` is parsed as ERB before YAML, so both the target host and the +container registry are read from environment variables rather than hardcoded — +there is no real production server for this test, so a deploy attempted without +these sane, safe defaults fails fast instead of silently targeting an unrelated +machine: + +```bash +KAMAL_WEB_HOST= \ +KAMAL_REGISTRY_USERNAME= \ +KAMAL_REGISTRY_PASSWORD= \ +SECRET_KEY_BASE= \ +bin/kamal deploy +``` + +`.kamal/secrets` reads `SECRET_KEY_BASE` from the deploying shell's environment and +`config/deploy.yml` declares it under `env.secret` — the two must name the same +secret or Kamal aborts. Unlike the throwaway value used for a local Docker run, this +one must stay **stable across deploys**: changing it invalidates every existing +session and signed cookie. Generate it once with `openssl rand -hex 64` and keep it in +a password manager or your CI's secret store. To use Rails credentials instead, swap +both references to `RAILS_MASTER_KEY` (the alternative is commented in +`.kamal/secrets`). + +You can render the full config without contacting a server, which validates the ERB +and resolves the secrets: + +```bash +SECRET_KEY_BASE=test KAMAL_REGISTRY_USERNAME=x KAMAL_REGISTRY_PASSWORD=y \ + KAMAL_WEB_HOST=198.51.100.10 bin/kamal config +``` + +## Environment Variables + +| Variable | Used by | Purpose | Default | +|---------------------------|--------------------------------|-------------------------------------------------------------------------|----------------------------------| +| `SECRET_KEY_BASE` | Rails, Kamal | Signs sessions and signed cookies in production | — (required in production) | +| `RAILS_MASTER_KEY` | Rails credentials, Kamal | Optional alternative to `SECRET_KEY_BASE`, only if you generate your own credentials via `bin/rails credentials:edit` | — (unused by default) | +| `RAILS_MAX_THREADS` | Puma, `database.yml` | Puma thread pool size / SQLite connection pool size | `3` (Puma) / `5` (DB pool) | +| `PORT` | Puma | Server port | `3000` | +| `SOLID_QUEUE_IN_PUMA` | `config/puma.rb`, Kamal | Runs the Solid Queue supervisor inside the Puma process | unset (off) | +| `JOB_CONCURRENCY` | `config/queue.yml` | Number of Solid Queue worker processes | `1` | +| `RAILS_LOG_LEVEL` | `config/environments/production.rb` | Production log verbosity | `info` | +| `KAMAL_WEB_HOST` | `config/deploy.yml` | Deploy target host/IP | `203.0.113.10` (RFC 5737, fails fast) | +| `KAMAL_REGISTRY_USERNAME` | `config/deploy.yml` | GHCR username / image namespace | `your-github-username` | +| `KAMAL_REGISTRY_PASSWORD` | `.kamal/secrets` | GHCR auth (GitHub PAT, `write:packages` scope) | — (required to deploy) | + +## Architecture Decisions + +- **Hotwire over React/Inertia** — chosen explicitly for this project to keep a + classic-modern monolith: Turbo Streams over Solid Cable cover every real-time + requirement (dashboard counters, import progress) without a client-side JS build + or state-management layer, and Stimulus covers the handful of purely + client-side interactions (mobile nav toggle, live password-confirmation + validation). +- **SQLite in production, multi-database** — `primary`/`cache`/`queue`/`cable`, each + its own SQLite file under `storage/`, mounted as a single Kamal volume. WAL mode + is the Rails 8 SQLite adapter's default, so no extra configuration is needed for + concurrent readers/writers. No Redis, Postgres, or MySQL to provision. +- **Rails 8 built-in authentication**, not Devise — generated via + `bin/rails generate authentication`, then customized: the generator's + `email_address` field was renamed to `email` (matching this project's + requirements), and a `role` enum (`no_admin`/`admin`, default `no_admin`) was + added. Public registration always forces `no_admin` server-side, even if a `role` + param is injected in the request. +- **Pundit for authorization** — `ApplicationController#pundit_user` maps to + `Current.user` (the app uses `Current.user` throughout, not the Devise-style + `current_user`). `after_action :verify_authorized` is enforced globally, with a + narrow `skip_after_action` only on the three pre-authentication controllers + (sessions, passwords, registrations). +- **Spreadsheet import via a single gem (`roo`)** — reads both CSV and XLSX through + the same API (`Roo::Spreadsheet.open`), avoiding a second gem + (`roo-xlsx`/`caxlsx`) purely for one format. An admin can mark whether the file + has a header row; either way, column mapping is purely **positional** (1st column + = full name, 2nd = email) and a header's text is never used to map columns. Each + row is validated and processed independently in a dedicated + `SpreadsheetParser`/`SpreadsheetImportRowImporter` pair of services (the job + itself only orchestrates: parse, loop, track progress, set final status). A bad + row is recorded as a `SpreadsheetImportRowError` (row number + message + raw + data) without aborting the rest of the import. Progress broadcasts are throttled + to once every 10 rows rather than firing on every single row, to keep large + imports from flooding Turbo Streams with broadcasts — the final state is always + covered separately by the status transition at the end of the import, which + already reflects the finished row count on its own. Imported users get an + unusable random password and a "set your password" e-mail reusing the existing + password-reset token mechanism, since they never chose one themselves. +- **Avatar via remote URL** (`app/services/avatar_fetcher.rb`) — fetched with + `Net::HTTP` (never `URI.open`/`open-uri` on a user-supplied URL) behind an SSRF + guard: resolves the host and rejects private/loopback/link-local IPs, limits + redirects, validates `content_type` against an allowlist, and streams the body + with a size cutoff enforced during download rather than after. +- **Ruby 4 ZJIT in production** — enabled via `RUBYOPT="--zjit"` in the Dockerfile. + Rails 8.1 enables YJIT by default in production (`config.yjit = !Rails.env.local?`); + since only one JIT can run per process, `config.yjit = false` is set explicitly in + `config/environments/production.rb` so ZJIT wins cleanly instead of both JITs + fighting for the slot and Ruby printing a boot-time conflict warning. +- **Solid Cache for dashboard counts** — `User.dashboard_counts` caches the + dashboard's total/by-role numbers, written through by the same hook that already + knew when they changed, rather than recomputing on every render. +- **Playwright over a lighter Capybara driver** — every real-time system spec + (Turbo Stream/Action Cable delivery, multi-session dashboard updates) needs a + real JS-executing, WebSocket-capable browser; a lighter driver like Cuprite would + technically cover the same ground, but Playwright/Capybara is the combination + this test's own brief names as the expected frontend-testing stack, so it was + kept as-is rather than swapped for a marginally lighter alternative. + +## Security + +Covered by `spec/requests/security_spec.rb` and verified manually against a real +running server: parameterized queries via ActiveRecord (no raw SQL, immune to the +classic `' OR '1'='1` injection), ERB auto-escaping everywhere (no `html_safe`/`raw`/ +`sanitize` in the codebase — untrusted data, including full names and spreadsheet +row error messages, is always rendered escaped), CSRF protection +(`protect_from_forgery with: :exception`, Rails 8.1's default) rejecting +state-changing requests without a valid authenticity token, rate-limited +authentication endpoints (sign-in, password reset, and registration), strong params +on every controller (no `params.permit!`), and an SSRF-hardened remote avatar +fetcher. `bundle exec brakeman` and `bundle exec bundler-audit check` are both +clean. + +Untrusted external input (spreadsheet cell contents during import, remote avatar +URLs) is always treated as inert data, never as instructions to follow — the same +principle applies to any text sourced from outside the application's own code. + +## Project Structure Highlights + +- `app/models/user.rb` — role enum, avatar validations, dashboard-count broadcast +- `app/services/avatar_fetcher.rb` — SSRF-hardened remote avatar download +- `app/services/spreadsheet_parser.rb` / `spreadsheet_import_row_importer.rb` — + spreadsheet parsing and per-row user creation, orchestrated by + `app/jobs/spreadsheet_import_job.rb` +- `app/policies/` — Pundit authorization policies +- `spec/` — RSpec suite (models, requests, jobs, services, policies, system specs) 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/images/.keep b/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb 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/tailwind/application.css b/app/assets/tailwind/application.css new file mode 100644 index 000000000..9d4b9bdc2 --- /dev/null +++ b/app/assets/tailwind/application.css @@ -0,0 +1,44 @@ +@import "tailwindcss"; + +@layer components { + .form-label { + @apply block text-sm font-semibold text-gray-700 mb-1; + } + + .form-input { + @apply mt-1 block w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-gray-900 shadow-sm transition-colors + focus:border-emerald-500 focus:outline-none focus:ring-2 focus:ring-emerald-500/20 + [&:user-invalid]:border-red-500 [&:user-invalid]:focus:ring-red-500/20; + } + + .form-file { + @apply mt-1 block w-full text-sm text-gray-500 + file:mr-4 file:py-2 file:px-4 + file:rounded-md file:border-0 + file:text-sm file:font-semibold + file:bg-emerald-50 file:text-emerald-700 + hover:file:bg-emerald-100 transition-colors cursor-pointer; + } + + .btn-primary { + @apply inline-flex justify-center items-center rounded-md bg-emerald-600 px-4 py-2 text-sm font-semibold text-white shadow-sm transition-all + hover:bg-emerald-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-emerald-600 + active:scale-[0.98]; + } + + .btn-link { + @apply cursor-pointer bg-transparent p-0 text-sm font-medium text-emerald-600 hover:text-emerald-500 transition-colors; + } + + .link-action { + @apply text-sm font-medium text-emerald-600 hover:text-emerald-500 transition-colors px-1; + } + + .link-danger { + @apply text-sm font-medium text-red-600 hover:text-red-500 transition-colors px-1; + } + + .link-muted { + @apply text-sm font-medium text-gray-500 hover:text-gray-700 transition-colors; + } +} diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..4264c745c --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,16 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + identified_by :current_user + + def connect + set_current_user || reject_unauthorized_connection + end + + private + def set_current_user + if session = Session.find_by(id: cookies.signed[:session_id]) + self.current_user = session.user + end + end + end +end diff --git a/app/controllers/admin/dashboards_controller.rb b/app/controllers/admin/dashboards_controller.rb new file mode 100644 index 000000000..758d28227 --- /dev/null +++ b/app/controllers/admin/dashboards_controller.rb @@ -0,0 +1,8 @@ +class Admin::DashboardsController < ApplicationController + def show + authorize User, :index? + counts = User.dashboard_counts + @total_users = counts[:total_users] + @users_by_role = counts[:users_by_role] + end +end diff --git a/app/controllers/admin/spreadsheet_imports_controller.rb b/app/controllers/admin/spreadsheet_imports_controller.rb new file mode 100644 index 000000000..395253b93 --- /dev/null +++ b/app/controllers/admin/spreadsheet_imports_controller.rb @@ -0,0 +1,42 @@ +class Admin::SpreadsheetImportsController < ApplicationController + after_action :verify_policy_scoped, only: :index + + before_action :set_spreadsheet_import, only: :show + + def index + authorize SpreadsheetImport, :index? + @spreadsheet_imports = policy_scope(SpreadsheetImport) + .includes(:user, :spreadsheet_import_row_errors, file_attachment: :blob) + .order(created_at: :desc) + end + + def new + @spreadsheet_import = SpreadsheetImport.new + authorize @spreadsheet_import + end + + def create + @spreadsheet_import = SpreadsheetImport.new(spreadsheet_import_params) + @spreadsheet_import.user = Current.user + authorize @spreadsheet_import + + if @spreadsheet_import.save + redirect_to admin_spreadsheet_import_path(@spreadsheet_import), notice: "Planilha enviada. A importação está sendo processada em segundo plano." + else + render :new, status: :unprocessable_entity + end + end + + def show + end + + private + def set_spreadsheet_import + @spreadsheet_import = SpreadsheetImport.find(params[:id]) + authorize @spreadsheet_import + end + + def spreadsheet_import_params + params.expect(spreadsheet_import: [ :file, :has_header ]) + end +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..37af5484c --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,63 @@ +class Admin::UsersController < ApplicationController + after_action :verify_policy_scoped, only: :index + + before_action :set_user, only: %i[ edit update destroy toggle_role ] + + def index + authorize User, :index? + @users = policy_scope(User).with_attached_avatar.order(:full_name) + end + + def new + @user = User.new + authorize @user + end + + def create + @user = User.new(user_params) + authorize @user + + if @user.save + redirect_to admin_users_path, notice: "Usuário criado com sucesso." + else + render :new, status: :unprocessable_entity + end + end + + def edit + end + + def update + if @user.update(user_params) + redirect_to admin_users_path, notice: "Usuário atualizado com sucesso." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @user.destroy + redirect_to admin_users_path, notice: "Usuário excluído com sucesso.", status: :see_other + end + + def toggle_role + if @user == Current.user + redirect_to admin_users_path, alert: "Você não pode alterar seu próprio papel (role)." + else + @user.update!(role: @user.admin? ? :no_admin : :admin) + redirect_to admin_users_path, notice: "Papel atualizado com sucesso." + end + end + + private + def set_user + @user = User.find(params[:id]) + authorize @user + end + + def user_params + attrs = params.expect(user: [ :full_name, :email, :password, :password_confirmation, :role, :avatar, :avatar_url ]) + attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? + attrs + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..1df1ac5ee --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,22 @@ +class ApplicationController < ActionController::Base + include Authentication + include Pundit::Authorization + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern + + # Changes to the importmap will invalidate the etag for HTML responses + stale_when_importmap_changes + + after_action :verify_authorized + + rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized + + private + def pundit_user + Current.user + end + + def user_not_authorized + redirect_to profile_path, alert: "Você não tem permissão para realizar esta ação." + 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/concerns/authentication.rb b/app/controllers/concerns/authentication.rb new file mode 100644 index 000000000..c03bad25d --- /dev/null +++ b/app/controllers/concerns/authentication.rb @@ -0,0 +1,52 @@ +module Authentication + extend ActiveSupport::Concern + + included do + before_action :require_authentication + helper_method :authenticated? + end + + class_methods do + def allow_unauthenticated_access(**options) + skip_before_action :require_authentication, **options + end + end + + private + def authenticated? + resume_session + end + + def require_authentication + resume_session || request_authentication + end + + def resume_session + Current.session ||= find_session_by_cookie + end + + def find_session_by_cookie + Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + end + + def request_authentication + session[:return_to_after_authenticating] = request.url + redirect_to new_session_path + end + + def after_authentication_url + session.delete(:return_to_after_authenticating) || (Current.user.admin? ? admin_dashboard_url : profile_url) + end + + def start_new_session_for(user) + user.sessions.create!(user_agent: request.user_agent, ip_address: request.remote_ip).tap do |session| + Current.session = session + cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax } + end + end + + def terminate_session + Current.session.destroy + cookies.delete(:session_id) + end +end diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb new file mode 100644 index 000000000..4b96a40c2 --- /dev/null +++ b/app/controllers/passwords_controller.rb @@ -0,0 +1,40 @@ +class PasswordsController < ApplicationController + allow_unauthenticated_access + skip_after_action :verify_authorized + before_action :set_user_by_token, only: %i[ edit update ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_password_path, alert: "Tente novamente mais tarde." } + + def new + end + + def create + if user = User.find_by(email: params[:email]) + PasswordsMailer.reset(user).deliver_later + end + + redirect_to new_session_path, notice: "Instruções de redefinição enviadas (caso o e-mail exista)." + end + + def edit + end + + def update + if @user.update(password_params) + @user.sessions.destroy_all + redirect_to new_session_path, notice: "Sua senha foi redefinida." + else + redirect_to edit_password_path(params[:token]), alert: "As senhas não coincidem." + end + end + + private + def set_user_by_token + @user = User.find_by_password_reset_token!(params[:token]) + rescue ActiveSupport::MessageVerifier::InvalidSignature + redirect_to new_password_path, alert: "O link de redefinição é inválido ou expirou." + end + + def password_params + params.expect(user: [ :password, :password_confirmation ]) + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..20636ecdb --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,35 @@ +class ProfilesController < ApplicationController + before_action :set_user + + def show + end + + def edit + end + + def update + if @user.update(user_params) + redirect_to profile_path, notice: "Perfil atualizado com sucesso." + else + render :edit, status: :unprocessable_entity + end + end + + def destroy + @user.destroy + cookies.delete(:session_id) + redirect_to new_session_path, notice: "Sua conta foi excluída.", status: :see_other + end + + private + def set_user + @user = Current.user + authorize @user + end + + def user_params + attrs = params.expect(user: [ :full_name, :email, :password, :password_confirmation, :avatar, :avatar_url ]) + attrs = attrs.except(:password, :password_confirmation) if attrs[:password].blank? + attrs + end +end diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb new file mode 100644 index 000000000..470729947 --- /dev/null +++ b/app/controllers/registrations_controller.rb @@ -0,0 +1,26 @@ +class RegistrationsController < ApplicationController + allow_unauthenticated_access + skip_after_action :verify_authorized + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_registration_path, alert: "Tente novamente mais tarde." } + + def new + @user = User.new + end + + def create + @user = User.new(registration_params) + @user.role = :no_admin + + if @user.save + start_new_session_for @user + redirect_to after_authentication_url, notice: "Bem-vindo! Sua conta foi criada." + else + render :new, status: :unprocessable_entity + end + end + + private + def registration_params + params.expect(user: [ :full_name, :email, :password, :password_confirmation ]) + end +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 000000000..0d8045cca --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,22 @@ +class SessionsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + skip_after_action :verify_authorized + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Tente novamente mais tarde." } + + def new + end + + def create + if user = User.authenticate_by(params.permit(:email, :password)) + start_new_session_for user + redirect_to after_authentication_url + else + redirect_to new_session_path, alert: "E-mail ou senha incorretos." + end + end + + def destroy + terminate_session + redirect_to new_session_path, status: :see_other + end +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/javascript/application.js b/app/javascript/application.js new file mode 100644 index 000000000..0d7b49404 --- /dev/null +++ b/app/javascript/application.js @@ -0,0 +1,3 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" 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/highlight_on_update_controller.js b/app/javascript/controllers/highlight_on_update_controller.js new file mode 100644 index 000000000..0a1e30421 --- /dev/null +++ b/app/javascript/controllers/highlight_on_update_controller.js @@ -0,0 +1,19 @@ +import { Controller } from "@hotwired/stimulus" + +// Briefly highlights an element whenever it is replaced by a Turbo Stream +// broadcast, so a "real-time" update (dashboard counts, import progress) is +// actually noticeable. +export default class extends Controller { + static classes = ["highlight"] + + connect() { + this.element.classList.add(...this.highlightClasses) + this.timeout = setTimeout(() => { + this.element.classList.remove(...this.highlightClasses) + }, 700) + } + + disconnect() { + clearTimeout(this.timeout) + } +} 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/javascript/controllers/password_confirmation_controller.js b/app/javascript/controllers/password_confirmation_controller.js new file mode 100644 index 000000000..6a3f17dec --- /dev/null +++ b/app/javascript/controllers/password_confirmation_controller.js @@ -0,0 +1,12 @@ +import { Controller } from "@hotwired/stimulus" + +// Gives immediate feedback when the confirmation field doesn't match the +// password field yet, since HTML5 has no built-in cross-field validation. +export default class extends Controller { + static targets = ["password", "confirmation"] + + validate() { + const mismatch = this.confirmationTarget.value.length > 0 && this.confirmationTarget.value !== this.passwordTarget.value + this.confirmationTarget.setCustomValidity(mismatch ? "As senhas não coincidem" : "") + } +} diff --git a/app/javascript/controllers/sidebar_toggle_controller.js b/app/javascript/controllers/sidebar_toggle_controller.js new file mode 100644 index 000000000..edb5ace60 --- /dev/null +++ b/app/javascript/controllers/sidebar_toggle_controller.js @@ -0,0 +1,15 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["menu", "overlay"] + + toggle() { + this.menuTarget.classList.toggle("-translate-x-full") + this.overlayTarget.classList.toggle("hidden") + } + + close() { + this.menuTarget.classList.add("-translate-x-full") + this.overlayTarget.classList.add("hidden") + } +} 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/avatar_download_job.rb b/app/jobs/avatar_download_job.rb new file mode 100644 index 000000000..e49813fd6 --- /dev/null +++ b/app/jobs/avatar_download_job.rb @@ -0,0 +1,20 @@ +class AvatarDownloadJob < ApplicationJob + queue_as :default + + # AvatarFetcher::FetchError covers permanent failures (bad/blocked URL, unsupported + # content type, oversized file) that a retry wouldn't fix, so it's discarded rather + # than retried — Solid Queue still records the discard instead of it being silently + # swallowed by an ad hoc rescue. + discard_on AvatarFetcher::FetchError do |job, error| + user_id, url = job.arguments + Rails.logger.warn("AvatarDownloadJob: failed to fetch avatar for user #{user_id} from #{url}: #{error.message}") + end + + def perform(user_id, url) + user = User.find_by(id: user_id) + return unless user + + result = AvatarFetcher.new(url).fetch + user.avatar.attach(io: result.io, filename: result.filename, content_type: result.content_type) + end +end diff --git a/app/jobs/spreadsheet_import_job.rb b/app/jobs/spreadsheet_import_job.rb new file mode 100644 index 000000000..e6ecbda2f --- /dev/null +++ b/app/jobs/spreadsheet_import_job.rb @@ -0,0 +1,36 @@ +class SpreadsheetImportJob < ApplicationJob + queue_as :default + + # Broadcasting progress on every single row floods Turbo Streams/Solid Cable on + # large imports (one full partial render + DB write per row); broadcast at most + # every Nth row instead. The final state is always covered separately by the + # status: :completed/:failed transition below (a regular update!, so it + # broadcasts on its own) — forcing an extra broadcast on the very last row here + # too would just double up with that one, back to back. + PROGRESS_BROADCAST_INTERVAL = 10 + + def perform(spreadsheet_import_id) + import = SpreadsheetImport.find_by(id: spreadsheet_import_id) + return unless import&.pending? + + import.update!(status: :processing) + + rows = SpreadsheetParser.new(import).rows + import.update!(total_rows: rows.size) + + row_importer = SpreadsheetImportRowImporter.new(import) + users_created = 0 + + rows.each_with_index do |(row_number, data), index| + users_created += 1 if row_importer.import(row_number, data) + import.update_columns(processed_rows: index + 1) + import.broadcast_progress if ((index + 1) % PROGRESS_BROADCAST_INTERVAL).zero? + end + + User.broadcast_dashboard_counts! if users_created.positive? + import.update!(status: :completed) + rescue => e + Rails.logger.warn("SpreadsheetImportJob: failed to process import #{spreadsheet_import_id}: #{e.message}") + import&.update!(status: :failed) + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..8bc199625 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,18 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" + + after_deliver :log_to_console_in_development + + private + # Development has no real delivery configured (see config/environments/ + # development.rb) so this is how you actually see an outgoing e-mail's link — + # logging is safe at any volume, unlike letter_opener's per-email browser tab. + def log_to_console_in_development + return unless Rails.env.development? + # message.body.to_s is empty for a multipart message (html + text parts) — + # the readable content lives in the parts themselves, not the top-level body. + body = message.multipart? ? message.text_part&.body : message.body + Rails.logger.info("[Mailer] To: #{message.to&.join(', ')} — #{message.subject}\n#{body}") + end +end diff --git a/app/mailers/passwords_mailer.rb b/app/mailers/passwords_mailer.rb new file mode 100644 index 000000000..afb0c999e --- /dev/null +++ b/app/mailers/passwords_mailer.rb @@ -0,0 +1,11 @@ +class PasswordsMailer < ApplicationMailer + def reset(user) + @user = user + mail subject: "Redefinição de senha", to: user.email + end + + def welcome(user) + @user = user + mail subject: "Defina sua senha", to: user.email + end +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/current.rb b/app/models/current.rb new file mode 100644 index 000000000..2bef56dad --- /dev/null +++ b/app/models/current.rb @@ -0,0 +1,4 @@ +class Current < ActiveSupport::CurrentAttributes + attribute :session + delegate :user, to: :session, allow_nil: true +end diff --git a/app/models/session.rb b/app/models/session.rb new file mode 100644 index 000000000..cf376fb28 --- /dev/null +++ b/app/models/session.rb @@ -0,0 +1,3 @@ +class Session < ApplicationRecord + belongs_to :user +end diff --git a/app/models/spreadsheet_import.rb b/app/models/spreadsheet_import.rb new file mode 100644 index 000000000..252d80275 --- /dev/null +++ b/app/models/spreadsheet_import.rb @@ -0,0 +1,47 @@ +class SpreadsheetImport < ApplicationRecord + ALLOWED_EXTENSIONS = %w[.csv .xlsx].freeze + MAX_BYTES = 10.megabytes + + belongs_to :user + has_one_attached :file + has_many :spreadsheet_import_row_errors, dependent: :destroy + + enum :status, { pending: 0, processing: 1, completed: 2, failed: 3 } + + validate :file_must_be_a_supported_spreadsheet, on: :create + + after_commit :enqueue_import_job, on: :create + after_commit :broadcast_progress, if: -> { saved_change_to_status? || saved_change_to_total_rows? } + + def progress_percent + return 0 if total_rows.zero? + ((processed_rows.to_f / total_rows) * 100).round + end + + # Per-row progress ticks bypass callbacks entirely (see SpreadsheetImportJob, + # which uses update_columns for those) so this is called explicitly, throttled, + # instead of firing on every single row. + def broadcast_progress + Turbo::StreamsChannel.broadcast_replace_to( + "spreadsheet_import_#{id}", + target: "spreadsheet_import_progress", + partial: "admin/spreadsheet_imports/progress", + locals: { spreadsheet_import: self } + ) + end + + private + def file_must_be_a_supported_spreadsheet + unless file.attached? + errors.add(:file, "precisa ser enviada") + return + end + + errors.add(:file, "deve ser um arquivo CSV ou XLSX") unless File.extname(file.filename.to_s).downcase.in?(ALLOWED_EXTENSIONS) + errors.add(:file, "é muito grande (máx #{MAX_BYTES / 1.megabyte}MB)") if file.byte_size > MAX_BYTES + end + + def enqueue_import_job + SpreadsheetImportJob.perform_later(id) + end +end diff --git a/app/models/spreadsheet_import_row_error.rb b/app/models/spreadsheet_import_row_error.rb new file mode 100644 index 000000000..05c2883a8 --- /dev/null +++ b/app/models/spreadsheet_import_row_error.rb @@ -0,0 +1,22 @@ +class SpreadsheetImportRowError < ApplicationRecord + include ActionView::RecordIdentifier + + belongs_to :spreadsheet_import + + validates :row_number, presence: true + validates :message, presence: true + + after_create_commit :broadcast_append + + private + # Appends just this row instead of the whole progress partial re-rendering + # every error every time — O(1) per error instead of O(errors so far). + def broadcast_append + Turbo::StreamsChannel.broadcast_append_to( + "spreadsheet_import_#{spreadsheet_import_id}", + target: dom_id(spreadsheet_import, :row_errors), + partial: "admin/spreadsheet_imports/row_error", + locals: { row_error: self } + ) + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..4085d5189 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,65 @@ +class User < ApplicationRecord + AVATAR_CONTENT_TYPES = %w[image/png image/jpeg image/webp].freeze + AVATAR_MAX_BYTES = 5.megabytes + DASHBOARD_COUNTS_CACHE_KEY = "admin_dashboard_counts" + + has_secure_password + has_many :sessions, dependent: :destroy + has_one_attached :avatar + + enum :role, { no_admin: 0, admin: 1 } + + attribute :avatar_url, :string + attr_accessor :skip_dashboard_broadcast + + normalizes :email, with: -> { it.strip.downcase } + + validates :full_name, presence: true + validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } + validates :password, length: { minimum: 8 }, allow_blank: true + validate :avatar_must_be_a_supported_image, if: -> { avatar.attached? } + validate :avatar_url_must_be_http, if: -> { avatar_url.present? } + + after_commit :enqueue_avatar_download, if: -> { avatar_url.present? } + after_commit :broadcast_dashboard_counts, if: -> { !skip_dashboard_broadcast && (destroyed? || previously_new_record? || saved_change_to_role?) } + + def self.dashboard_counts + Rails.cache.fetch(DASHBOARD_COUNTS_CACHE_KEY) { { total_users: count, users_by_role: group(:role).count } } + end + + # Used by SpreadsheetImportJob to broadcast once after a bulk import instead of + # once per created user (each of which skips its own broadcast via + # skip_dashboard_broadcast). + def self.broadcast_dashboard_counts! + Rails.cache.delete(DASHBOARD_COUNTS_CACHE_KEY) + counts = dashboard_counts + + Turbo::StreamsChannel.broadcast_replace_to( + "admin_dashboard", + target: "dashboard_counts", + partial: "admin/dashboards/counts", + locals: counts + ) + end + + private + def avatar_must_be_a_supported_image + errors.add(:avatar, "deve ser uma imagem PNG, JPEG ou WEBP") unless avatar.content_type.in?(AVATAR_CONTENT_TYPES) + errors.add(:avatar, "é muito grande (máx #{AVATAR_MAX_BYTES / 1.megabyte}MB)") if avatar.byte_size > AVATAR_MAX_BYTES + end + + def avatar_url_must_be_http + uri = URI.parse(avatar_url) + errors.add(:avatar_url, "deve ser uma URL http(s) válida") unless uri.is_a?(URI::HTTP) && uri.host.present? + rescue URI::InvalidURIError + errors.add(:avatar_url, "deve ser uma URL http(s) válida") + end + + def enqueue_avatar_download + AvatarDownloadJob.perform_later(id, avatar_url) + end + + def broadcast_dashboard_counts + self.class.broadcast_dashboard_counts! + end +end diff --git a/app/policies/application_policy.rb b/app/policies/application_policy.rb new file mode 100644 index 000000000..be644fe34 --- /dev/null +++ b/app/policies/application_policy.rb @@ -0,0 +1,53 @@ +# frozen_string_literal: true + +class ApplicationPolicy + attr_reader :user, :record + + def initialize(user, record) + @user = user + @record = record + end + + def index? + false + end + + def show? + false + end + + def create? + false + end + + def new? + create? + end + + def update? + false + end + + def edit? + update? + end + + def destroy? + false + end + + class Scope + def initialize(user, scope) + @user = user + @scope = scope + end + + def resolve + raise NoMethodError, "You must define #resolve in #{self.class}" + end + + private + + attr_reader :user, :scope + end +end diff --git a/app/policies/spreadsheet_import_policy.rb b/app/policies/spreadsheet_import_policy.rb new file mode 100644 index 000000000..421f66c50 --- /dev/null +++ b/app/policies/spreadsheet_import_policy.rb @@ -0,0 +1,19 @@ +class SpreadsheetImportPolicy < ApplicationPolicy + def index? + user.admin? + end + + def show? + user.admin? + end + + def create? + user.admin? + end + + class Scope < Scope + def resolve + user.admin? ? scope.all : scope.none + end + end +end diff --git a/app/policies/user_policy.rb b/app/policies/user_policy.rb new file mode 100644 index 000000000..0fd5029d9 --- /dev/null +++ b/app/policies/user_policy.rb @@ -0,0 +1,36 @@ +class UserPolicy < ApplicationPolicy + def index? + user.admin? + end + + def show? + user.admin? || own_record? + end + + def create? + user.admin? + end + + def update? + user.admin? || own_record? + end + + def destroy? + user.admin? || own_record? + end + + def toggle_role? + user.admin? + end + + class Scope < Scope + def resolve + user.admin? ? scope.all : scope.where(id: user.id) + end + end + + private + def own_record? + record == user + end +end diff --git a/app/services/avatar_fetcher.rb b/app/services/avatar_fetcher.rb new file mode 100644 index 000000000..ec58820e4 --- /dev/null +++ b/app/services/avatar_fetcher.rb @@ -0,0 +1,96 @@ +require "net/http" +require "resolv" +require "ipaddr" + +# Downloads a remote image over HTTP(S) to be attached as a User's avatar. +# +# Hardened against SSRF: only plain http(s) URLs are accepted, the resolved +# IP address must be public (no loopback/private/link-local ranges), redirects +# are capped, and the response body is streamed with an early size cutoff so a +# malicious server cannot exhaust memory before we notice it is too large. +class AvatarFetcher + class FetchError < StandardError; end + + ALLOWED_CONTENT_TYPES = %w[image/png image/jpeg image/webp].freeze + MAX_BYTES = 5.megabytes + MAX_REDIRECTS = 3 + OPEN_TIMEOUT = 5 + READ_TIMEOUT = 10 + + Result = Data.define(:io, :content_type, :filename) + + def initialize(url) + @url = url + end + + def fetch + uri = parse_http_uri!(@url) + + MAX_REDIRECTS.downto(0) do |redirects_left| + guard_against_ssrf!(uri) + + outcome = request_once(uri) + return outcome.fetch(:success) if outcome.key?(:success) + + raise FetchError, "too many redirects" if redirects_left.zero? + uri = parse_http_uri!(outcome.fetch(:redirect)) + end + end + + private + + def parse_http_uri!(url) + uri = URI.parse(url) + raise FetchError, "invalid URL" unless uri.is_a?(URI::HTTP) && uri.host.present? + uri + rescue URI::InvalidURIError + raise FetchError, "invalid URL" + end + + def guard_against_ssrf!(uri) + addresses = Resolv.getaddresses(uri.host) + raise FetchError, "could not resolve host" if addresses.empty? + + addresses.each do |address| + ip = IPAddr.new(address) + if ip.private? || ip.loopback? || ip.link_local? + raise FetchError, "URL resolves to a disallowed address" + end + end + end + + def request_once(uri) + http = Net::HTTP.new(uri.host, uri.port) + http.use_ssl = uri.scheme == "https" + http.open_timeout = OPEN_TIMEOUT + http.read_timeout = READ_TIMEOUT + + http.start do |client| + client.request_get(uri) do |response| + return { redirect: response["location"] } if response.is_a?(Net::HTTPRedirection) + + unless response.is_a?(Net::HTTPSuccess) + raise FetchError, "unexpected response #{response.code}" + end + + content_type = response.content_type + unless ALLOWED_CONTENT_TYPES.include?(content_type) + raise FetchError, "unsupported content type #{content_type.inspect}" + end + + buffer = +"" + response.read_body do |chunk| + buffer << chunk + raise FetchError, "file too large" if buffer.bytesize > MAX_BYTES + end + + return { success: Result.new(io: StringIO.new(buffer), content_type: content_type, filename: filename_for(uri)) } + end + end + end + + def filename_for(uri) + name = File.basename(uri.path.to_s) + name.presence || "avatar" + end +end diff --git a/app/services/spreadsheet_import_row_importer.rb b/app/services/spreadsheet_import_row_importer.rb new file mode 100644 index 000000000..a4bbd1fa6 --- /dev/null +++ b/app/services/spreadsheet_import_row_importer.rb @@ -0,0 +1,43 @@ +# Creates (or records the failure of) a single spreadsheet import row as a User. +# +# Imported users get an unguessable random password (never communicated) since +# they never chose one themselves; a "set your password" e-mail lets them pick a +# real one via the same token mechanism used for password resets. +class SpreadsheetImportRowImporter + def initialize(spreadsheet_import) + @spreadsheet_import = spreadsheet_import + end + + # Returns true if the row created a user, false if it was recorded as an error. + def import(row_number, data) + user = User.new( + email: data["email"], + full_name: data["nome"], + password: SecureRandom.hex(16), + role: :no_admin, + skip_dashboard_broadcast: true + ) + + return record_success(user) if user.save + + record_failure(row_number, data, user) + end + + private + + attr_reader :spreadsheet_import + + def record_success(user) + PasswordsMailer.welcome(user).deliver_later + true + end + + def record_failure(row_number, data, user) + spreadsheet_import.spreadsheet_import_row_errors.create!( + row_number: row_number, + message: user.errors.full_messages.to_sentence, + raw_data: data.to_json + ) + false + end +end diff --git a/app/services/spreadsheet_parser.rb b/app/services/spreadsheet_parser.rb new file mode 100644 index 000000000..819a8f0da --- /dev/null +++ b/app/services/spreadsheet_parser.rb @@ -0,0 +1,37 @@ +# Parses a SpreadsheetImport's attached CSV/XLSX file into (row_number, data) pairs. +# +# Spreadsheet data is untrusted external input: every cell is treated as plain +# data (never evaluated or interpreted). Column mapping is always positional (1st +# column is the full name, 2nd is the email) — a header row's own text, if present, +# is never read to decide the mapping; when has_header? is true, that row is simply +# skipped, never parsed as data. +class SpreadsheetParser + class ParseError < StandardError; end + + def initialize(spreadsheet_import) + @spreadsheet_import = spreadsheet_import + end + + def rows + spreadsheet_import.file.open do |tempfile| + sheet = Roo::Spreadsheet.open(tempfile.path, extension: extension).sheet(0) + first_data_row = spreadsheet_import.has_header? ? 2 : 1 + + (first_data_row..sheet.last_row).filter_map do |row_number| + values = sheet.row(row_number) + next if values.all? { |value| value.to_s.strip.blank? } + [ row_number, { "nome" => values[0].to_s.strip, "email" => values[1].to_s.strip } ] + end + end + rescue => e + raise ParseError, e.message + end + + private + + attr_reader :spreadsheet_import + + def extension + File.extname(spreadsheet_import.file.filename.to_s).delete(".").downcase.to_sym + end +end diff --git a/app/views/admin/dashboards/_counts.html.erb b/app/views/admin/dashboards/_counts.html.erb new file mode 100644 index 000000000..15849c74b --- /dev/null +++ b/app/views/admin/dashboards/_counts.html.erb @@ -0,0 +1,33 @@ +
+
+

Total de Usuários

+

<%= total_users %>

+
+ + <% User.roles.keys.each_with_index do |role, index| %> +
+

+ <%= role == "admin" ? "Administrador" : "Usuário Normal" %> +

+ +

+ <%= users_by_role[role] || 0 %> +

+
+ <% end %> +
diff --git a/app/views/admin/dashboards/show.html.erb b/app/views/admin/dashboards/show.html.erb new file mode 100644 index 000000000..85433ddd3 --- /dev/null +++ b/app/views/admin/dashboards/show.html.erb @@ -0,0 +1,13 @@ +
+
+

Painel Administrativo

+ +

+ Conectado como <%= Current.user.full_name %> + (<%= Current.user.role == 'admin' ? 'Administrador' : 'Usuário Normal' %>). +

+
+
+ +<%= turbo_stream_from "admin_dashboard" %> +<%= render "counts", total_users: @total_users, users_by_role: @users_by_role %> diff --git a/app/views/admin/spreadsheet_imports/_progress.html.erb b/app/views/admin/spreadsheet_imports/_progress.html.erb new file mode 100644 index 000000000..e83e73416 --- /dev/null +++ b/app/views/admin/spreadsheet_imports/_progress.html.erb @@ -0,0 +1,28 @@ +
+
+
+

Status:

+ + + <%= spreadsheet_import.status == "processing" ? "Processando" : spreadsheet_import.status == "completed" ? "Concluída" : spreadsheet_import.status == "failed" ? "Falhou" : "Pendente" %> + +
+ +
+
+
+ +

+ <%= spreadsheet_import.processed_rows %> / + <%= spreadsheet_import.total_rows %> linhas processadas +

+
+
diff --git a/app/views/admin/spreadsheet_imports/_row_error.html.erb b/app/views/admin/spreadsheet_imports/_row_error.html.erb new file mode 100644 index 000000000..2aee286ff --- /dev/null +++ b/app/views/admin/spreadsheet_imports/_row_error.html.erb @@ -0,0 +1,7 @@ + + + <%= row_error.row_number %> + + + <%= row_error.message %> + diff --git a/app/views/admin/spreadsheet_imports/_row_errors.html.erb b/app/views/admin/spreadsheet_imports/_row_errors.html.erb new file mode 100644 index 000000000..ee0a45654 --- /dev/null +++ b/app/views/admin/spreadsheet_imports/_row_errors.html.erb @@ -0,0 +1,36 @@ +

Erros nas Linhas

+ +
+ + + + + + + + + + + <%= render partial: "admin/spreadsheet_imports/row_error", + collection: spreadsheet_import.spreadsheet_import_row_errors.order(:row_number), + as: :row_error %> + +
+ Linha + + Motivo +
+
diff --git a/app/views/admin/spreadsheet_imports/index.html.erb b/app/views/admin/spreadsheet_imports/index.html.erb new file mode 100644 index 000000000..c1a2d7212 --- /dev/null +++ b/app/views/admin/spreadsheet_imports/index.html.erb @@ -0,0 +1,120 @@ +
+

Importações de Planilha

+ <%= link_to "Nova Importação", new_admin_spreadsheet_import_path, class: "btn-primary" %> +
+ +
+ + + + + + + + + + + + + + + + + + + <% @spreadsheet_imports.each do |spreadsheet_import| %> + + + + + + + + + + + + + + <% end %> + +
+ Arquivo + + Enviado por + + Status + + Progresso + + Erros +
+ <%= spreadsheet_import.file.filename %> + + <%= spreadsheet_import.user.full_name %> + + + <%= spreadsheet_import.status == "processing" ? "Processando" : spreadsheet_import.status == "completed" ? "Concluída" : spreadsheet_import.status == "failed" ? "Falhou" : "Pendente" %> + + + <%= spreadsheet_import.processed_rows %>/<%= spreadsheet_import.total_rows %> + + <%= spreadsheet_import.spreadsheet_import_row_errors.size %> + + <%= link_to admin_spreadsheet_import_path(spreadsheet_import), title: "Ver Detalhes", class: "p-2 rounded-md text-gray-400 hover:text-emerald-600 hover:bg-emerald-50 transition-colors inline-block" do %> + + + + + + <% end %> +
+
diff --git a/app/views/admin/spreadsheet_imports/new.html.erb b/app/views/admin/spreadsheet_imports/new.html.erb new file mode 100644 index 000000000..6f4437ebd --- /dev/null +++ b/app/views/admin/spreadsheet_imports/new.html.erb @@ -0,0 +1,36 @@ +
+

+ Nova Importação +

+ + <%= form_with model: [ :admin, @spreadsheet_import ], class: "contents" do |form| %> + <%= render "shared/form_errors", record: @spreadsheet_import %> + +
+ <%= form.label :file, "Planilha (CSV ou XLSX)", class: "form-label" %> + +

+ A 1ª coluna é sempre tratada como Nome completo e a 2ª + como E-mail, pela posição — o texto do cabeçalho (se + houver) não é lido nem validado. +

+ + <%= form.file_field :file, accept: ".csv,.xlsx", required: true, class: "form-file" %> + +
+ <%= form.check_box :has_header, class: "h-4 w-4 rounded border-gray-300 text-emerald-600 focus:ring-emerald-500" %> + <%= form.label :has_header, "Este arquivo tem uma linha de cabeçalho", class: "text-sm font-medium text-gray-700" %> +
+ +

+ Se marcado, a primeira linha é ignorada por completo (nem seu conteúdo é + lido). +

+
+ +
+ <%= form.submit "Enviar Planilha", class: "btn-primary w-full sm:w-auto text-center cursor-pointer text-lg" %> + <%= link_to "Cancelar", admin_spreadsheet_imports_path, class: "link-muted" %> +
+ <% end %> +
diff --git a/app/views/admin/spreadsheet_imports/show.html.erb b/app/views/admin/spreadsheet_imports/show.html.erb new file mode 100644 index 000000000..91ae6300c --- /dev/null +++ b/app/views/admin/spreadsheet_imports/show.html.erb @@ -0,0 +1,21 @@ +
+
+

Importação de Planilha

+ +

+ <%= @spreadsheet_import.file.filename %> + — enviado por <%= @spreadsheet_import.user.full_name %> +

+
+ + <%= turbo_stream_from "spreadsheet_import_#{@spreadsheet_import.id}" %> + <%= render "progress", spreadsheet_import: @spreadsheet_import %> + <%= render "row_errors", spreadsheet_import: @spreadsheet_import %> + +
+ <%= link_to "Voltar para importações", admin_spreadsheet_imports_path, class: "link-muted font-medium" %> +
+
diff --git a/app/views/admin/users/_form.html.erb b/app/views/admin/users/_form.html.erb new file mode 100644 index 000000000..1b66ac15c --- /dev/null +++ b/app/views/admin/users/_form.html.erb @@ -0,0 +1,58 @@ +<%= form_with model: [ :admin, user ], class: "contents", data: { turbo_frame: "_top" } do |form| %> + <%= render "shared/form_errors", record: user %> + +
+ <%= form.label :full_name, "Nome", class: "form-label" %> + <%= form.text_field :full_name, required: true, class: "form-input" %> +
+ +
+ <%= form.label :email, "E-mail", class: "form-label" %> + <%= form.email_field :email, required: true, autocomplete: "username", class: "form-input" %> +
+ +
+ <%= form.label :role, "Papel", class: "form-label" %> + <%= form.select :role, User.roles.keys.map { |role| [ role == "admin" ? "Administrador" : "Usuário Normal", role ] }, {}, class: "form-input" %> +
+ +
+

+ <%= user.new_record? ? "Senha" : "Mudar Senha" %> +

+ +
+ <%= form.label :password, (user.new_record? ? "Senha" : "Nova senha"), class: "form-label" %> + <%= form.password_field :password, required: user.new_record?, autocomplete: "new-password", placeholder: user.new_record? ? nil : "Deixe em branco para manter a senha atual", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "password", action: "input->password-confirmation#validate" } %> +
+ +
+ <%= form.label :password_confirmation, "Confirmar senha", class: "form-label" %> + <%= form.password_field :password_confirmation, required: user.new_record?, autocomplete: "new-password", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "confirmation", action: "input->password-confirmation#validate" } %> +
+
+ +
+

+ Avatar +

+ +
+ <%= form.label :avatar, "Imagem de Avatar", class: "form-label" %> + <%= form.file_field :avatar, accept: "image/png,image/jpeg,image/webp", class: "form-file" %> +
+ +
+ <%= form.label :avatar_url, "…ou URL da imagem do avatar", class: "form-label" %> + <%= form.url_field :avatar_url, placeholder: "https://example.com/avatar.png", class: "form-input" %> +
+
+ +
+ <%= form.submit (user.new_record? ? "Criar Usuário" : "Atualizar Usuário"), class: "btn-primary w-full sm:w-auto text-center cursor-pointer text-lg" %> + <%= link_to "Cancelar", admin_users_path, class: "link-muted", data: { turbo_frame: "_top" } %> +
+<% 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..1d0734398 --- /dev/null +++ b/app/views/admin/users/edit.html.erb @@ -0,0 +1,14 @@ +<%= turbo_frame_tag "admin_user_form" do %> +
+

+ Editar Usuário +

+ + <%= render "form", user: @user %> +
+<% 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..84fa44fe5 --- /dev/null +++ b/app/views/admin/users/index.html.erb @@ -0,0 +1,157 @@ +
+

Usuários

+ <%= link_to "Novo Usuário", new_admin_user_path, class: "btn-primary", data: { turbo_frame: "admin_user_form" } %> +
+ +<%= turbo_frame_tag "admin_user_form" %> + +
+ + + + + + + + + + + + + + + + + <% @users.each do |user| %> + + + + + + + + + + + + <% end %> + +
+ Avatar + + Nome + + E-mail + + Papel + + Ações +
+ <% if user.avatar.attached? %> + <%= image_tag user.avatar.variant(resize_to_limit: [ 40, 40 ]), alt: user.full_name, class: "size-10 object-cover rounded-full shadow-sm" %> + <% else %> +
+ + + +
+ <% end %> +
+ <%= user.full_name %> + <%= user.email %> + + <%= user.role == "admin" ? "Administrador" : "Usuário Normal" %> + + +
+ <%= link_to edit_admin_user_path(user), title: "Editar", class: "p-2 rounded-md text-gray-400 hover:text-emerald-600 hover:bg-emerald-50 transition-colors", data: { turbo_frame: "admin_user_form" } do %> + + + + <% end %> + + <%= button_to toggle_role_admin_user_path(user), method: :patch, title: "Alterar papel", class: "p-2 rounded-md text-gray-400 hover:text-emerald-600 hover:bg-emerald-50 transition-colors flex items-center justify-center cursor-pointer" do %> + + + + <% end %> + + <%= button_to admin_user_path(user), method: :delete, title: "Excluir", class: "p-2 rounded-md text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors flex items-center justify-center cursor-pointer", form: { data: { turbo_confirm: "Tem certeza?" } } do %> + + + + <% 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..408a5e230 --- /dev/null +++ b/app/views/admin/users/new.html.erb @@ -0,0 +1,14 @@ +<%= turbo_frame_tag "admin_user_form" do %> +
+

+ Novo Usuário +

+ + <%= render "form", user: @user %> +
+<% end %> diff --git a/app/views/layouts/_flash.html.erb b/app/views/layouts/_flash.html.erb new file mode 100644 index 000000000..f757897dc --- /dev/null +++ b/app/views/layouts/_flash.html.erb @@ -0,0 +1,61 @@ +<% if alert = flash[:alert] %> +
+
+
+ +
+ +
+

<%= alert %>

+
+
+
+<% end %> + +<% if notice = flash[:notice] %> +
+
+
+ +
+ +
+

<%= notice %>

+
+
+
+<% end %> diff --git a/app/views/layouts/_sidebar.html.erb b/app/views/layouts/_sidebar.html.erb new file mode 100644 index 000000000..8bba7cb44 --- /dev/null +++ b/app/views/layouts/_sidebar.html.erb @@ -0,0 +1,123 @@ +
+ +
+
+ Fullstack Developer +
+ + +
+ + + + + + +
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..04349520d --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,46 @@ + + + + + <%= content_for(:title) || "Fullstack Developer" %> + + + + + + + <%= 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) %> + + + + + + <%# Includes all stylesheet files in app/assets/stylesheets %> + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + <% if Current.user %> + <%= render "layouts/sidebar" %> + <% end %> + +
+
+ <%= render "layouts/flash" %> + <%= yield %> +
+
+ + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..bc021e689 --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,15 @@ + + + + + + + + + + + <%= 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/passwords/edit.html.erb b/app/views/passwords/edit.html.erb new file mode 100644 index 000000000..c5fa3a805 --- /dev/null +++ b/app/views/passwords/edit.html.erb @@ -0,0 +1,23 @@ +
+

+ Atualizar Senha +

+ + <%= form_with url: password_path(params[:token]), scope: :user, method: :put, class: "contents" do |form| %> +
+
+ <%= form.label :password, "Nova senha", class: "form-label" %> + <%= form.password_field :password, required: true, autocomplete: "new-password", placeholder: "Digite a nova senha", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "password", action: "input->password-confirmation#validate" } %> +
+ +
+ <%= form.label :password_confirmation, "Confirmar nova senha", class: "form-label" %> + <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password", placeholder: "Repita a nova senha", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "confirmation", action: "input->password-confirmation#validate" } %> +
+
+ +
+ <%= form.submit "Salvar", class: "btn-primary w-full text-center cursor-pointer text-xl" %> +
+ <% end %> +
diff --git a/app/views/passwords/new.html.erb b/app/views/passwords/new.html.erb new file mode 100644 index 000000000..e8c27ab12 --- /dev/null +++ b/app/views/passwords/new.html.erb @@ -0,0 +1,20 @@ +
+

+ Esqueceu a senha? +

+ + <%= form_with url: passwords_path, class: "contents" do |form| %> +
+ <%= form.label :email, "E-mail", class: "form-label" %> + <%= form.email_field :email, required: true, autofocus: true, autocomplete: "username", placeholder: "Digite seu e-mail", value: params[:email], class: "form-input" %> +
+ +
+ <%= form.submit "Enviar instruções", class: "btn-primary w-full text-center cursor-pointer text-xl" %> +
+ +
+ <%= link_to "Voltar para o login", new_session_path, class: "link-muted" %> +
+ <% end %> +
diff --git a/app/views/passwords_mailer/reset.html.erb b/app/views/passwords_mailer/reset.html.erb new file mode 100644 index 000000000..2679fff25 --- /dev/null +++ b/app/views/passwords_mailer/reset.html.erb @@ -0,0 +1,6 @@ +

+ Você pode redefinir sua senha + <%= link_to "nesta página de redefinição de senha", edit_password_url(@user.password_reset_token) %>. + Este link expira em + <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. +

diff --git a/app/views/passwords_mailer/reset.text.erb b/app/views/passwords_mailer/reset.text.erb new file mode 100644 index 000000000..08725775d --- /dev/null +++ b/app/views/passwords_mailer/reset.text.erb @@ -0,0 +1,4 @@ +Você pode redefinir sua senha em +<%= edit_password_url(@user.password_reset_token) %> + +Este link expira em <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. diff --git a/app/views/passwords_mailer/welcome.html.erb b/app/views/passwords_mailer/welcome.html.erb new file mode 100644 index 000000000..1ddb3933c --- /dev/null +++ b/app/views/passwords_mailer/welcome.html.erb @@ -0,0 +1,6 @@ +

+ Sua conta foi criada. Defina sua senha + <%= link_to "nesta página", edit_password_url(@user.password_reset_token) %> + para acessar o sistema. Este link expira em + <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. +

diff --git a/app/views/passwords_mailer/welcome.text.erb b/app/views/passwords_mailer/welcome.text.erb new file mode 100644 index 000000000..9112784bc --- /dev/null +++ b/app/views/passwords_mailer/welcome.text.erb @@ -0,0 +1,4 @@ +Sua conta foi criada. Defina sua senha para acessar o sistema em +<%= edit_password_url(@user.password_reset_token) %> + +Este link expira em <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. diff --git a/app/views/profiles/edit.html.erb b/app/views/profiles/edit.html.erb new file mode 100644 index 000000000..88a515496 --- /dev/null +++ b/app/views/profiles/edit.html.erb @@ -0,0 +1,69 @@ +
+

+ Editar Perfil +

+ + <%= form_with model: @user, url: profile_path, class: "contents" do |form| %> + <%= render "shared/form_errors", record: @user %> + +
+ <%= form.label :full_name, "Nome", class: "form-label" %> + <%= form.text_field :full_name, required: true, class: "form-input" %> +
+ +
+ <%= form.label :email, "E-mail", class: "form-label" %> + <%= form.email_field :email, required: true, autocomplete: "username", class: "form-input" %> +
+ +
+

+ Mudar Senha +

+ +
+ <%= form.label :password, "Nova senha", class: "form-label" %> + <%= form.password_field :password, autocomplete: "new-password", placeholder: "Deixe em branco para manter a senha atual", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "password", action: "input->password-confirmation#validate" } %> +
+ +
+ <%= form.label :password_confirmation, "Confirmar senha", class: "form-label" %> + <%= form.password_field :password_confirmation, autocomplete: "new-password", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "confirmation", action: "input->password-confirmation#validate" } %> +
+
+ +
+

+ Avatar +

+ +
+ <%= form.label :avatar, "Imagem de Avatar", class: "form-label" %> + <%= form.file_field :avatar, accept: "image/png,image/jpeg,image/webp", class: "form-file" %> +
+ +
+ <%= form.label :avatar_url, "…ou URL da imagem", class: "form-label" %> + <%= form.url_field :avatar_url, placeholder: "https://example.com/avatar.png", class: "form-input" %> +
+
+ +
+ <%= form.submit "Salvar Perfil", class: "btn-primary w-full sm:w-auto text-center cursor-pointer" %> + <%= link_to "Cancelar", profile_path, class: "link-muted" %> +
+ <% end %> +
diff --git a/app/views/profiles/show.html.erb b/app/views/profiles/show.html.erb new file mode 100644 index 000000000..0c31a138b --- /dev/null +++ b/app/views/profiles/show.html.erb @@ -0,0 +1,48 @@ +
+

+ Meu Perfil +

+ +
+ <% if @user.avatar.attached? %> +
+ <%= image_tag @user.avatar.variant(resize_to_limit: [ 128, 128 ]), alt: @user.full_name, class: "size-32 object-cover block" %> +
+ <% end %> + +
+
+
Nome
+
<%= @user.full_name %>
+
+ +
+
E-mail
+ +
+ <%= @user.email %> +
+
+ +
+
Papel
+ +
+ + <%= @user.role == "admin" ? "Administrador" : "Usuário Normal" %> + +
+
+
+
+ +
+ <%= link_to "Editar perfil", edit_profile_path, class: "btn-primary" %> + <%= button_to "Excluir conta", profile_path, method: :delete, class: "inline-flex justify-center items-center rounded-md bg-white px-4 py-2 text-sm font-semibold text-red-600 shadow-sm border border-red-200 hover:bg-red-50 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-red-600 transition-colors", form: { data: { turbo_confirm: "Tem certeza? Esta ação não pode ser desfeita." } } %> +
+
diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..13a7b4eff --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "FullstackDeveloper", + "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": "FullstackDeveloper.", + "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/registrations/new.html.erb b/app/views/registrations/new.html.erb new file mode 100644 index 000000000..a500b6f7b --- /dev/null +++ b/app/views/registrations/new.html.erb @@ -0,0 +1,44 @@ +
+

+ Criar Conta +

+ + <%= form_with model: @user, url: registration_path, class: "contents" do |form| %> + <%= render "shared/form_errors", record: @user %> + +
+ <%= form.label :full_name, "Nome", class: "form-label" %> + <%= form.text_field :full_name, required: true, autofocus: true, placeholder: "Nome", class: "form-input" %> +
+ +
+ <%= form.label :email, "E-mail", class: "form-label" %> + <%= form.email_field :email, required: true, autocomplete: "username", placeholder: "Digite seu e-mail", class: "form-input" %> +
+ +
+
+ <%= form.label :password, "Senha", class: "form-label" %> + <%= form.password_field :password, required: true, autocomplete: "new-password", placeholder: "Senha", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "password", action: "input->password-confirmation#validate" } %> +
+ +
+ <%= form.label :password_confirmation, "Confirmar Senha", class: "form-label" %> + <%= form.password_field :password_confirmation, required: true, autocomplete: "new-password", placeholder: "Confirmar senha", minlength: 8, maxlength: 72, class: "form-input", data: { password_confirmation_target: "confirmation", action: "input->password-confirmation#validate" } %> +
+
+ +
+ <%= form.submit "Criar Conta", class: "btn-primary w-full text-center cursor-pointer text-xl" %> + +
+ <%= link_to "Já tem uma conta? Entrar", new_session_path, class: "link-action" %> +
+
+ <% end %> +
diff --git a/app/views/sessions/new.html.erb b/app/views/sessions/new.html.erb new file mode 100644 index 000000000..961e61aab --- /dev/null +++ b/app/views/sessions/new.html.erb @@ -0,0 +1,31 @@ +
+

+ Entrar +

+ + <%= form_with url: session_url, class: "contents" do |form| %> +
+ <%= form.label :email, "E-mail", class: "form-label" %> + <%= form.email_field :email, required: true, autofocus: true, autocomplete: "username", placeholder: "Digite seu e-mail", value: params[:email], class: "form-input" %> +
+ +
+ <%= form.label :password, "Senha", class: "form-label" %> + <%= form.password_field :password, required: true, autocomplete: "current-password", placeholder: "Digite sua senha", maxlength: 72, class: "form-input" %> +
+ +
+ <%= form.submit "Entrar", class: "btn-primary w-full text-center cursor-pointer text-xl" %> + +
+ <%= link_to "Esqueceu a senha?", new_password_path, class: "link-muted" %> + <%= link_to "Criar uma conta", new_registration_path, class: "link-action" %> +
+
+ <% end %> +
diff --git a/app/views/shared/_form_errors.html.erb b/app/views/shared/_form_errors.html.erb new file mode 100644 index 000000000..8a48b5075 --- /dev/null +++ b/app/views/shared/_form_errors.html.erb @@ -0,0 +1,9 @@ +<% if record.errors.any? %> +
+
    + <% record.errors.full_messages.each do |message| %> +
  • <%= message %>
  • + <% end %> +
+
+<% 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/bundler-audit b/bin/bundler-audit new file mode 100755 index 000000000..e2ef22690 --- /dev/null +++ b/bin/bundler-audit @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "bundler/audit/cli" + +ARGV.concat %w[ --config config/bundler-audit.yml ] if ARGV.empty? || ARGV.include?("check") +Bundler::Audit::CLI.start diff --git a/bin/ci b/bin/ci new file mode 100755 index 000000000..4137ad5bb --- /dev/null +++ b/bin/ci @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "active_support/continuous_integration" + +CI = ActiveSupport::ContinuousIntegration +require_relative "../config/ci.rb" diff --git a/bin/dev b/bin/dev new file mode 100755 index 000000000..ad72c7d53 --- /dev/null +++ b/bin/dev @@ -0,0 +1,16 @@ +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +# Let the debug gem allow remote connections, +# but avoid loading until `debugger` is called +export RUBY_DEBUG_OPEN="true" +export RUBY_DEBUG_LAZY="true" + +exec foreman start -f Procfile.dev "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..ed31659f4 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,8 @@ +#!/bin/bash -e + +# 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..d9ba27670 --- /dev/null +++ b/bin/kamal @@ -0,0 +1,16 @@ +#!/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__) + +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..5a2050471 --- /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..81be011e8 --- /dev/null +++ b/bin/setup @@ -0,0 +1,35 @@ +#!/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" + system! "bin/rails db:reset" if ARGV.include?("--reset") + + 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..f85818d01 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,43 @@ +require_relative "boot" + +require "rails" +# Pick the frameworks you want: +require "active_model/railtie" +require "active_job/railtie" +require "active_record/railtie" +require "active_storage/engine" +require "action_controller/railtie" +require "action_mailer/railtie" +require "action_mailbox/engine" +require "action_text/engine" +require "action_view/railtie" +require "action_cable/engine" +# require "rails/test_unit/railtie" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module FullstackDeveloper + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.1 + + # 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") + config.i18n.default_locale = :"pt-BR" + + # Don't generate system test files. + config.generators.system_tests = nil + 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/bundler-audit.yml b/config/bundler-audit.yml new file mode 100644 index 000000000..e74b3af94 --- /dev/null +++ b/config/bundler-audit.yml @@ -0,0 +1,5 @@ +# Audit all gems listed in the Gemfile for known security problems by running bin/bundler-audit. +# CVEs that are not relevant to the application can be enumerated on the ignore list below. + +ignore: + - CVE-THAT-DOES-NOT-APPLY diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..661433b3f --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,21 @@ +# 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 + # Autotrim (the default) runs a synchronous DELETE attempt on every single + # broadcast, which adds up fast under high-frequency writes (e.g. per-row + # import progress). Trim on a schedule instead (see config/recurring.yml). + autotrim: false 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/ci.rb b/config/ci.rb new file mode 100644 index 000000000..239b34398 --- /dev/null +++ b/config/ci.rb @@ -0,0 +1,20 @@ +# Run using bin/ci + +CI.run do + step "Setup", "bin/setup --skip-server" + + step "Style: Ruby", "bin/rubocop" + + step "Security: Gem audit", "bin/bundler-audit" + step "Security: Importmap vulnerability audit", "bin/importmap audit" + step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error" + + + # Optional: set a green GitHub commit status to unblock PR merge. + # Requires the `gh` CLI and `gh extension install basecamp/gh-signoff`. + # if success? + # step "Signoff: All systems go. Ready for merge and deploy.", "gh signoff" + # else + # failure "Signoff: CI failed. Do not merge or deploy.", "Fix the issues and try again." + # end +end diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..da9864dcc --- /dev/null +++ b/config/database.yml @@ -0,0 +1,40 @@ +# SQLite. Versions 3.8.0 and up are supported. +# gem install sqlite3 +# +# Ensure the SQLite 3 gem is defined in your Gemfile +# gem "sqlite3" +# +default: &default + adapter: sqlite3 + max_connections: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %> + timeout: 5000 + +development: + <<: *default + database: storage/development.sqlite3 + +# Warning: The database defined as "test" will be erased and +# re-generated from your development database when you run "rake". +# Do not set this db to the same as development or production. +test: + <<: *default + database: storage/test<%= ENV["TEST_ENV_NUMBER"] %>.sqlite3 + +# Store production database in the storage/ directory, which by default +# is mounted as a persistent Docker volume in config/deploy.yml. +production: + primary: + <<: *default + database: storage/production.sqlite3 + cache: + <<: *default + database: storage/production_cache.sqlite3 + migrations_paths: db/cache_migrate + queue: + <<: *default + database: storage/production_queue.sqlite3 + migrations_paths: db/queue_migrate + cable: + <<: *default + database: storage/production_cable.sqlite3 + migrations_paths: db/cable_migrate diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 000000000..2933400db --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,127 @@ +# Name of your application. Used to uniquely configure containers. +service: fullstack_developer + +# Name of the container image. GHCR (see registry below) expects the / form. +image: <%= ENV.fetch("KAMAL_REGISTRY_USERNAME", "your-github-username") %>/fullstack_developer + +# Deploy to these servers. +# +# deploy.yml is parsed as ERB before YAML, so the actual host is read from an env var at deploy +# time (`KAMAL_WEB_HOST= bin/kamal deploy`) instead of being hardcoded here. +# The fallback below (203.0.113.10) is a TEST-NET-3 address reserved for documentation by RFC 5737 — +# it deliberately can't resolve to a real host, so a deploy attempted without setting KAMAL_WEB_HOST +# fails fast instead of silently targeting someone else's machine. +servers: + web: + - <%= ENV.fetch("KAMAL_WEB_HOST", "203.0.113.10") %> + # job: + # hosts: + # - <%= ENV.fetch("KAMAL_WEB_HOST", "203.0.113.10") %> + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# If used with Cloudflare, set encryption mode in SSL/TLS setting to "Full" to enable CF-to-app encryption. +# +# Using an SSL proxy like this requires turning on config.assume_ssl and config.force_ssl in production.rb! +# +# Don't use this when deploying to multiple web servers (then you have to terminate SSL at your load balancer). +# +# proxy: +# ssl: true +# host: app.example.com + +# Where you keep your container images. +# +# ghcr.io needs no extra infrastructure (unlike e.g. a self-hosted registry on localhost:5555) and +# authenticates with a GitHub personal access token, kept out of this file via .kamal/secrets. +registry: + server: ghcr.io + username: <%= ENV.fetch("KAMAL_REGISTRY_USERNAME", "your-github-username") %> + + # 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: + # Must match what .kamal/secrets actually provides, or Kamal aborts on an + # undeclared secret. Swap this for RAILS_MASTER_KEY if you generate your own + # Rails credentials — see the commented alternative in .kamal/secrets. + - SECRET_KEY_BASE + 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 fullstack_developer-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 --include-password" + +# 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: + - "fullstack_developer_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: 4.0.0 + # secrets: + # - GITHUB_TOKEN + +# 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: valkey/valkey:8 +# 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..17884ab16 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,86 @@ +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 + + # Write sent e-mails to tmp/mails instead of trying (and silently failing) to + # deliver them over SMTP with no server configured. Deliberately not + # letter_opener: it opens a new browser tab per delivery, which would open + # thousands of tabs for a bulk spreadsheet import (see ApplicationMailer's + # after_deliver, which logs each one instead). + config.action_mailer.delivery_method = :file + config.action_mailer.perform_deliveries = true + + # 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 + + # Highlight code that triggered redirect in logs. + config.action_dispatch.verbose_redirect_logs = true + + # Suppress logger output for asset requests. + config.assets.quiet = true + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + config.action_view.annotate_rendered_view_with_filenames = true + + # Uncomment if you wish to allow Action Cable access from any origin. + # config.action_cable.disable_request_forgery_protection = true + + # 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..f82ade1bc --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,96 @@ +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 + + # Rails 8.1's default (`self.yjit = !Rails.env.local?`, set in config/application.rb) auto-enables + # YJIT in production. This container instead enables Ruby 4's newer ZJIT via RUBYOPT (Dockerfile) - + # only one JIT can be active per process, and leaving both on prints a boot-time conflict warning + # and silently drops the Rails-side enable. Disabled here so ZJIT is the one actually running. + config.yjit = false + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!). + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via bin/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..909dfc542 --- /dev/null +++ b/config/importmap.rb @@ -0,0 +1,7 @@ +# 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" 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..d51d71397 --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,29 @@ +# 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) +# +# # Automatically add `nonce` to `javascript_tag`, `javascript_include_tag`, and `stylesheet_link_tag` +# # if the corresponding directives are specified in `content_security_policy_nonce_directives`. +# # config.content_security_policy_nonce_auto = true +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..c0b717f7e --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..3860f659e --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/config/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/pt-BR.yml b/config/locales/pt-BR.yml new file mode 100644 index 000000000..d7d666831 --- /dev/null +++ b/config/locales/pt-BR.yml @@ -0,0 +1,13 @@ +pt-BR: + activerecord: + attributes: + spreadsheet_import: + file: "Planilha" + user: + avatar: "Avatar" + avatar_url: "URL do Avatar" + full_name: "Nome" + email: "E-mail" + role: "Papel" + password: "Senha" + password_confirmation: "Confirmação de senha" diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..38c4b8659 --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,42 @@ +# 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. You can set it to `auto` to automatically start a worker +# for each available processor. +# +# 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..6b1436086 --- /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: 1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 000000000..a34a0cf2a --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,19 @@ +# 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 + + trim_solid_cable_messages: + class: SolidCable::TrimJob + schedule: every 5 minutes diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..d1529997d --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,25 @@ +Rails.application.routes.draw do + resource :session + resources :passwords, param: :token + resource :registration, only: %i[ new create ] + resource :profile, only: %i[ show edit update destroy ] + namespace :admin do + resource :dashboard, only: :show + resources :users do + patch :toggle_role, on: :member + end + resources :spreadsheet_imports, only: %i[ index new create show ] + end + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # 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 + + # Defines the root path route ("/") + root "sessions#new" +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..927dc537c --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,27 @@ +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 %> + +# 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..81a410d18 --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,12 @@ +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/20260903005315_create_users.rb b/db/migrate/20260903005315_create_users.rb new file mode 100644 index 000000000..20870ca31 --- /dev/null +++ b/db/migrate/20260903005315_create_users.rb @@ -0,0 +1,13 @@ +class CreateUsers < ActiveRecord::Migration[8.1] + def change + create_table :users do |t| + t.string :full_name, null: false + t.string :email, null: false + t.string :password_digest, null: false + t.integer :role, null: false, default: 0 + + t.timestamps + end + add_index :users, :email, unique: true + end +end diff --git a/db/migrate/20260903005316_create_sessions.rb b/db/migrate/20260903005316_create_sessions.rb new file mode 100644 index 000000000..ec9efdbaa --- /dev/null +++ b/db/migrate/20260903005316_create_sessions.rb @@ -0,0 +1,11 @@ +class CreateSessions < ActiveRecord::Migration[8.1] + def change + create_table :sessions do |t| + t.references :user, null: false, foreign_key: true + t.string :ip_address + t.string :user_agent + + t.timestamps + end + end +end diff --git a/db/migrate/20260903013348_create_active_storage_tables.active_storage.rb b/db/migrate/20260903013348_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..6bd8bd082 --- /dev/null +++ b/db/migrate/20260903013348_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/20260903171020_create_spreadsheet_imports.rb b/db/migrate/20260903171020_create_spreadsheet_imports.rb new file mode 100644 index 000000000..bae79d0cd --- /dev/null +++ b/db/migrate/20260903171020_create_spreadsheet_imports.rb @@ -0,0 +1,12 @@ +class CreateSpreadsheetImports < ActiveRecord::Migration[8.1] + def change + create_table :spreadsheet_imports do |t| + t.references :user, null: false, foreign_key: true + t.integer :status, null: false, default: 0 + t.integer :total_rows, null: false, default: 0 + t.integer :processed_rows, null: false, default: 0 + + t.timestamps + end + end +end diff --git a/db/migrate/20260903171025_create_spreadsheet_import_row_errors.rb b/db/migrate/20260903171025_create_spreadsheet_import_row_errors.rb new file mode 100644 index 000000000..daab6de2f --- /dev/null +++ b/db/migrate/20260903171025_create_spreadsheet_import_row_errors.rb @@ -0,0 +1,12 @@ +class CreateSpreadsheetImportRowErrors < ActiveRecord::Migration[8.1] + def change + create_table :spreadsheet_import_row_errors do |t| + t.references :spreadsheet_import, null: false, foreign_key: true + t.integer :row_number, null: false + t.string :message, null: false + t.text :raw_data + + t.timestamps + end + end +end diff --git a/db/migrate/20260903230822_add_has_header_to_spreadsheet_imports.rb b/db/migrate/20260903230822_add_has_header_to_spreadsheet_imports.rb new file mode 100644 index 000000000..2d61e1620 --- /dev/null +++ b/db/migrate/20260903230822_add_has_header_to_spreadsheet_imports.rb @@ -0,0 +1,5 @@ +class AddHasHeaderToSpreadsheetImports < ActiveRecord::Migration[8.1] + def change + add_column :spreadsheet_imports, :has_header, :boolean, default: true, null: false + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 000000000..f9a71dabb --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,160 @@ +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.bigint "batch_id" + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "batch_id" ], name: "index_solid_queue_jobs_on_batch_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 + + create_table "solid_queue_batches", force: :cascade do |t| + t.string "active_job_batch_id" + t.string "description" + t.text "on_finish" + t.text "on_success" + t.text "on_failure" + t.text "metadata" + t.integer "total_jobs", default: 0, null: false + t.integer "completed_jobs", default: 0, null: false + t.integer "failed_jobs", default: 0, null: false + t.datetime "enqueued_at" + t.datetime "finished_at" + t.datetime "failed_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_batch_id" ], name: "index_solid_queue_batches_on_active_job_batch_id", unique: true + t.index [ "finished_at" ], name: "index_solid_queue_batches_on_finished_at" + end + + create_table "solid_queue_batch_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "batch_id", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_batch_executions_on_job_id", unique: true + t.index [ "batch_id" ], name: "index_solid_queue_batch_executions_on_batch_id" + end + + add_foreign_key "solid_queue_batch_executions", "solid_queue_batches", column: "batch_id", on_delete: :cascade + add_foreign_key "solid_queue_batch_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + 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..eef28a9ab --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,87 @@ +# 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.1].define(version: 2026_09_03_230822) do + create_table "active_storage_attachments", force: :cascade do |t| + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.string "name", null: false + t.bigint "record_id", null: false + t.string "record_type", 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.bigint "byte_size", null: false + t.string "checksum" + t.string "content_type" + t.datetime "created_at", null: false + t.string "filename", null: false + t.string "key", null: false + t.text "metadata" + t.string "service_name", 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 "sessions", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "ip_address" + t.datetime "updated_at", null: false + t.string "user_agent" + t.integer "user_id", null: false + t.index ["user_id"], name: "index_sessions_on_user_id" + end + + create_table "spreadsheet_import_row_errors", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "message", null: false + t.text "raw_data" + t.integer "row_number", null: false + t.integer "spreadsheet_import_id", null: false + t.datetime "updated_at", null: false + t.index ["spreadsheet_import_id"], name: "index_spreadsheet_import_row_errors_on_spreadsheet_import_id" + end + + create_table "spreadsheet_imports", force: :cascade do |t| + t.datetime "created_at", null: false + t.boolean "has_header", default: true, null: false + t.integer "processed_rows", default: 0, null: false + t.integer "status", default: 0, null: false + t.integer "total_rows", default: 0, null: false + t.datetime "updated_at", null: false + t.integer "user_id", null: false + t.index ["user_id"], name: "index_spreadsheet_imports_on_user_id" + end + + create_table "users", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "email", null: false + t.string "full_name", null: false + t.string "password_digest", null: false + t.integer "role", default: 0, null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", 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 "sessions", "users" + add_foreign_key "spreadsheet_import_row_errors", "spreadsheet_imports" + add_foreign_key "spreadsheet_imports", "users" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..f71a3b58b --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,20 @@ +# 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). + +# Registration always forces role: no_admin (see RegistrationsController), so there is no way to +# reach an admin account from the UI alone. Seed one bootstrap admin so the app is usable right +# after setup. +User.find_or_create_by!(email: "admin@example.com") do |user| + user.full_name = "Admin" + user.password = "password123" + user.role = :admin +end + +# A regular (non-admin) user, seeded for convenience so the app has something to +# sign in as beyond the admin account right after setup. +User.find_or_create_by!(email: "user@example.com") do |user| + user.full_name = "User" + user.password = "password123" + user.role = :no_admin +end diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..ad6ec8901 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,56 @@ +{ + "name": "Fullstack-Developer", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "playwright": "1.62.1" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/playwright": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", + "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.62.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.62.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", + "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..eba599f48 --- /dev/null +++ b/package.json @@ -0,0 +1,5 @@ +{ + "dependencies": { + "playwright": "1.62.1" + } +} diff --git a/public/400.html b/public/400.html new file mode 100644 index 000000000..640de0339 --- /dev/null +++ b/public/400.html @@ -0,0 +1,135 @@ + + + + + + + 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..d7f0f1422 --- /dev/null +++ b/public/404.html @@ -0,0 +1,135 @@ + + + + + + + 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..43d2811e8 --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,135 @@ + + + + + + + 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..f12fb4aa1 --- /dev/null +++ b/public/422.html @@ -0,0 +1,135 @@ + + + + + + + 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..e4eb18a75 --- /dev/null +++ b/public/500.html @@ -0,0 +1,135 @@ + + + + + + + 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/boot_spec.rb b/spec/boot_spec.rb new file mode 100644 index 000000000..397db8c70 --- /dev/null +++ b/spec/boot_spec.rb @@ -0,0 +1,23 @@ +require "rails_helper" + +RSpec.describe "Application boot" do + it "loads the Rails environment without raising" do + expect(Rails.application).to be_initialized + end + + it "runs migrations with SQLite in WAL journal mode" do + result = ActiveRecord::Base.lease_connection.execute("PRAGMA journal_mode").first["journal_mode"] + + expect(result).to eq("wal") + end + + it "loads the required testing and infrastructure gems" do + %w[FactoryBot Faker Shoulda::Matchers Capybara SolidQueue SolidCache SolidCable].each do |const_name| + expect(const_name.safe_constantize).not_to be_nil, "expected #{const_name} to be loaded" + end + end + + it "uses the ActiveJob test adapter in the test environment" do + expect(ActiveJob::Base.queue_adapter).to be_a(ActiveJob::QueueAdapters::TestAdapter) + end +end diff --git a/spec/factories/spreadsheet_imports.rb b/spec/factories/spreadsheet_imports.rb new file mode 100644 index 000000000..b79cdb6c2 --- /dev/null +++ b/spec/factories/spreadsheet_imports.rb @@ -0,0 +1,21 @@ +FactoryBot.define do + factory :spreadsheet_import do + association :user, factory: [ :user, :admin ] + status { :pending } + + after(:build) do |spreadsheet_import| + spreadsheet_import.file.attach( + io: StringIO.new("nome,email\nFixture User,fixture@example.com\n"), + filename: "import.csv", + content_type: "text/csv" + ) + end + end + + factory :spreadsheet_import_row_error do + association :spreadsheet_import + sequence(:row_number) { |n| n + 1 } + message { "E-mail não pode ficar em branco" } + raw_data { { "nome" => "Missing E-mail", "email" => "" }.to_json } + end +end diff --git a/spec/factories/users.rb b/spec/factories/users.rb new file mode 100644 index 000000000..6b0c2c548 --- /dev/null +++ b/spec/factories/users.rb @@ -0,0 +1,22 @@ +FactoryBot.define do + factory :user do + sequence(:full_name) { |n| "#{Faker::Name.name} #{n}" } + sequence(:email) { |n| "user#{n}@example.com" } + password { "password123" } + role { :no_admin } + + trait :admin do + role { :admin } + end + + trait :with_avatar do + after(:build) do |user| + user.avatar.attach( + io: StringIO.new("fake-image-bytes"), + filename: "avatar.png", + content_type: "image/png" + ) + end + end + end +end diff --git a/spec/fixtures/files/header_labels_mismatch_import.csv b/spec/fixtures/files/header_labels_mismatch_import.csv new file mode 100644 index 000000000..bfe49c369 --- /dev/null +++ b/spec/fixtures/files/header_labels_mismatch_import.csv @@ -0,0 +1,2 @@ +coluna_a,coluna_b +Henry Example,henry@example.com diff --git a/spec/fixtures/files/malformed_import.csv b/spec/fixtures/files/malformed_import.csv new file mode 100644 index 000000000..32a98544b Binary files /dev/null and b/spec/fixtures/files/malformed_import.csv differ diff --git a/spec/fixtures/files/mixed_import.csv b/spec/fixtures/files/mixed_import.csv new file mode 100644 index 000000000..1fa55b1bf --- /dev/null +++ b/spec/fixtures/files/mixed_import.csv @@ -0,0 +1,6 @@ +nome,email +Dave Example,dave@example.com +Missing Email, +Bad Email Format,not-an-email +Duplicate Email,existing@example.com +Erin Example,erin@example.com diff --git a/spec/fixtures/files/mixed_import.xlsx b/spec/fixtures/files/mixed_import.xlsx new file mode 100644 index 000000000..c3a9d5666 Binary files /dev/null and b/spec/fixtures/files/mixed_import.xlsx differ diff --git a/spec/fixtures/files/valid_import.csv b/spec/fixtures/files/valid_import.csv new file mode 100644 index 000000000..304bc5773 --- /dev/null +++ b/spec/fixtures/files/valid_import.csv @@ -0,0 +1,4 @@ +nome,email +Alice Example,alice@example.com +Bob Example,bob@example.com +Carol Example,carol@example.com diff --git a/spec/fixtures/files/valid_import.xlsx b/spec/fixtures/files/valid_import.xlsx new file mode 100644 index 000000000..175711525 Binary files /dev/null and b/spec/fixtures/files/valid_import.xlsx differ diff --git a/spec/fixtures/files/valid_import_no_header.csv b/spec/fixtures/files/valid_import_no_header.csv new file mode 100644 index 000000000..deeff97a5 --- /dev/null +++ b/spec/fixtures/files/valid_import_no_header.csv @@ -0,0 +1,2 @@ +Frank Example,frank@example.com +Grace Example,grace@example.com diff --git a/spec/jobs/avatar_download_job_spec.rb b/spec/jobs/avatar_download_job_spec.rb new file mode 100644 index 000000000..726e32f8b --- /dev/null +++ b/spec/jobs/avatar_download_job_spec.rb @@ -0,0 +1,36 @@ +require "rails_helper" + +RSpec.describe AvatarDownloadJob, type: :job do + let(:user) { create(:user) } + + it "attaches the fetched image to the user's avatar" do + fetched = AvatarFetcher::Result.new(io: StringIO.new("bytes"), content_type: "image/png", filename: "avatar.png") + allow(AvatarFetcher).to receive(:new).with("http://example.com/avatar.png").and_return(instance_double(AvatarFetcher, fetch: fetched)) + + described_class.perform_now(user.id, "http://example.com/avatar.png") + user.reload + + expect(user.avatar).to be_attached + expect(user.avatar.content_type).to eq("image/png") + end + + it "does nothing when the user no longer exists" do + expect { + described_class.perform_now(0, "http://example.com/avatar.png") + }.not_to raise_error + end + + it "logs and swallows fetch failures instead of raising" do + failing_fetcher = instance_double(AvatarFetcher) + allow(failing_fetcher).to receive(:fetch).and_raise(AvatarFetcher::FetchError, "boom") + allow(AvatarFetcher).to receive(:new).with("http://example.com/avatar.png").and_return(failing_fetcher) + + expect(Rails.logger).to receive(:warn).with(/boom/) + + expect { + described_class.perform_now(user.id, "http://example.com/avatar.png") + }.not_to raise_error + + expect(user.avatar).not_to be_attached + end +end diff --git a/spec/jobs/spreadsheet_import_job_spec.rb b/spec/jobs/spreadsheet_import_job_spec.rb new file mode 100644 index 000000000..bbc3238af --- /dev/null +++ b/spec/jobs/spreadsheet_import_job_spec.rb @@ -0,0 +1,116 @@ +require "rails_helper" + +RSpec.describe SpreadsheetImportJob, type: :job do + def spreadsheet_import_with(fixture_name, content_type) + spreadsheet_import = create(:spreadsheet_import) + spreadsheet_import.file.attach( + io: File.open(Rails.root.join("spec/fixtures/files", fixture_name)), + filename: fixture_name, + content_type: content_type + ) + spreadsheet_import + end + + shared_examples "a mixed spreadsheet import" do |fixture_name, content_type| + it "creates a user per valid row and a SpreadsheetImportRowError per invalid row, without aborting" do + create(:user, email: "existing@example.com") + spreadsheet_import = spreadsheet_import_with(fixture_name, content_type) + + expect { + described_class.perform_now(spreadsheet_import.id) + }.to change(User, :count).by(2) # dave@example.com and erin@example.com (or heidi/ivan for xlsx) + + spreadsheet_import.reload + expect(spreadsheet_import).to be_completed + expect(spreadsheet_import.total_rows).to eq(5) + expect(spreadsheet_import.processed_rows).to eq(5) + + errors = spreadsheet_import.spreadsheet_import_row_errors.order(:row_number) + expect(errors.pluck(:row_number)).to eq([ 3, 4, 5 ]) + expect(errors[0].message).to match(/e-mail não pode ficar em branco/i) + expect(errors[1].message).to match(/e-mail não é válido/i) + expect(errors[2].message).to match(/e-mail já está em uso/i) + end + + it "gives imported users an unguessable random password" do + create(:user, email: "existing@example.com") + spreadsheet_import = spreadsheet_import_with(fixture_name, content_type) + + described_class.perform_now(spreadsheet_import.id) + + imported_user = User.where.not(email: [ "existing@example.com", spreadsheet_import.user.email ]).first + expect(imported_user.authenticate("password123")).to be false + end + end + + include_examples "a mixed spreadsheet import", "mixed_import.csv", "text/csv" + include_examples "a mixed spreadsheet import", "mixed_import.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" + + it "marks the import as failed and logs a warning when the spreadsheet cannot be parsed" do + spreadsheet_import = spreadsheet_import_with("malformed_import.csv", "text/csv") + + expect(Rails.logger).to receive(:warn).with(/failed to process import/) + + expect { + described_class.perform_now(spreadsheet_import.id) + }.not_to change(User, :count) + + expect(spreadsheet_import.reload).to be_failed + expect(spreadsheet_import.spreadsheet_import_row_errors).to be_empty + end + + it "does nothing when the import no longer exists" do + expect { + described_class.perform_now(0) + }.not_to raise_error + end + + it "does nothing when the import is not pending" do + spreadsheet_import = create(:spreadsheet_import, status: :completed) + + expect { + described_class.perform_now(spreadsheet_import.id) + }.not_to change(User, :count) + end + + describe "progress broadcast throttling" do + include ActionCable::TestHelper + + it "throttles progress broadcasts instead of firing on every row" do + spreadsheet_import = create(:spreadsheet_import) + rows = 25.times.map { |i| "Person #{i},person#{i}@example.com" } + spreadsheet_import.file.attach( + io: StringIO.new("nome,email\n#{rows.join("\n")}\n"), + filename: "many_rows.csv", + content_type: "text/csv" + ) + + # status:processing (1) + total_rows set (1) + throttled progress every 10 rows + # (rows 10 and 20, for 25 rows) + status:completed (1, which already reflects + # the final count) = 5. A per-row broadcast would have produced 25+ instead. + expect { + described_class.perform_now(spreadsheet_import.id) + }.to have_broadcasted_to("spreadsheet_import_#{spreadsheet_import.id}").exactly(5).times + end + end + + describe "dashboard broadcast" do + include ActionCable::TestHelper + + it "broadcasts dashboard counts once after the import, not once per created user" do + spreadsheet_import = spreadsheet_import_with("valid_import.csv", "text/csv") + + expect { + described_class.perform_now(spreadsheet_import.id) + }.to have_broadcasted_to("admin_dashboard").exactly(1).times + end + + it "does not broadcast dashboard counts when no user was created" do + spreadsheet_import = spreadsheet_import_with("malformed_import.csv", "text/csv") + + expect { + described_class.perform_now(spreadsheet_import.id) + }.not_to have_broadcasted_to("admin_dashboard") + end + end +end diff --git a/spec/mailers/passwords_mailer_spec.rb b/spec/mailers/passwords_mailer_spec.rb new file mode 100644 index 000000000..eaa263184 --- /dev/null +++ b/spec/mailers/passwords_mailer_spec.rb @@ -0,0 +1,31 @@ +require "rails_helper" + +RSpec.describe PasswordsMailer, type: :mailer do + let(:user) { create(:user) } + + def token_from(mail) + mail.text_part.body.to_s[%r{/passwords/([^/]+)/edit}, 1] + end + + describe "#reset" do + let(:mail) { described_class.reset(user) } + + it "renders in Portuguese, addressed to the user, with a valid reset link" do + expect(mail.subject).to eq("Redefinição de senha") + expect(mail.to).to eq([ user.email ]) + expect(mail.text_part.body.to_s).to include("redefinir sua senha") + expect(User.find_by_password_reset_token!(token_from(mail))).to eq(user) + end + end + + describe "#welcome" do + let(:mail) { described_class.welcome(user) } + + it "renders in Portuguese, addressed to the user, with a valid set-password link" do + expect(mail.subject).to eq("Defina sua senha") + expect(mail.to).to eq([ user.email ]) + expect(mail.text_part.body.to_s).to include("Defina sua senha") + expect(User.find_by_password_reset_token!(token_from(mail))).to eq(user) + end + end +end diff --git a/spec/models/session_spec.rb b/spec/models/session_spec.rb new file mode 100644 index 000000000..a8e01daac --- /dev/null +++ b/spec/models/session_spec.rb @@ -0,0 +1,5 @@ +require "rails_helper" + +RSpec.describe Session, type: :model do + it { is_expected.to belong_to(:user) } +end diff --git a/spec/models/spreadsheet_import_row_error_spec.rb b/spec/models/spreadsheet_import_row_error_spec.rb new file mode 100644 index 000000000..ab710dcef --- /dev/null +++ b/spec/models/spreadsheet_import_row_error_spec.rb @@ -0,0 +1,9 @@ +require "rails_helper" + +RSpec.describe SpreadsheetImportRowError, type: :model do + subject { build(:spreadsheet_import_row_error) } + + it { is_expected.to belong_to(:spreadsheet_import) } + it { is_expected.to validate_presence_of(:row_number) } + it { is_expected.to validate_presence_of(:message) } +end diff --git a/spec/models/spreadsheet_import_spec.rb b/spec/models/spreadsheet_import_spec.rb new file mode 100644 index 000000000..78bdfcc72 --- /dev/null +++ b/spec/models/spreadsheet_import_spec.rb @@ -0,0 +1,128 @@ +require "rails_helper" + +RSpec.describe SpreadsheetImport, type: :model do + describe "validations" do + it "requires a file to be attached" do + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.detach + + expect(spreadsheet_import).not_to be_valid + expect(spreadsheet_import.errors[:file]).to be_present + end + + it "rejects an unsupported file extension" do + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.attach(io: StringIO.new("not a spreadsheet"), filename: "notes.txt", content_type: "text/plain") + + expect(spreadsheet_import).not_to be_valid + expect(spreadsheet_import.errors[:file]).to be_present + end + + it "accepts a .csv file" do + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.attach(io: StringIO.new("nome,email\n"), filename: "import.csv", content_type: "text/csv") + + expect(spreadsheet_import).to be_valid + end + + it "accepts a .xlsx file" do + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.attach(io: StringIO.new("bytes"), filename: "import.xlsx", content_type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + + expect(spreadsheet_import).to be_valid + end + + it "rejects a file that is too large" do + stub_const("SpreadsheetImport::MAX_BYTES", 10) + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.attach(io: StringIO.new("x" * 20), filename: "import.csv", content_type: "text/csv") + + expect(spreadsheet_import).not_to be_valid + expect(spreadsheet_import.errors[:file]).to be_present + end + end + + describe "associations" do + it { is_expected.to belong_to(:user) } + it { is_expected.to have_many(:spreadsheet_import_row_errors).dependent(:destroy) } + end + + describe "status enum" do + it { is_expected.to define_enum_for(:status).with_values(pending: 0, processing: 1, completed: 2, failed: 3) } + end + + describe "#has_header" do + it "defaults to true for a new import" do + expect(SpreadsheetImport.new.has_header).to be true + end + end + + describe "#progress_percent" do + it "is 0 when there are no rows yet" do + spreadsheet_import = build(:spreadsheet_import, total_rows: 0, processed_rows: 0) + + expect(spreadsheet_import.progress_percent).to eq(0) + end + + it "rounds the processed/total ratio to a whole percentage" do + spreadsheet_import = build(:spreadsheet_import, total_rows: 3, processed_rows: 1) + + expect(spreadsheet_import.progress_percent).to eq(33) + end + end + + describe "background processing" do + it "enqueues a SpreadsheetImportJob after a successful save" do + spreadsheet_import = build(:spreadsheet_import) + + expect { spreadsheet_import.save! }.to have_enqueued_job(SpreadsheetImportJob).with(spreadsheet_import.id) + end + + it "does not enqueue a job when the save fails" do + spreadsheet_import = build(:spreadsheet_import) + spreadsheet_import.file.detach + + expect { spreadsheet_import.save }.not_to have_enqueued_job(SpreadsheetImportJob) + end + end + + describe "progress broadcasts" do + include ActionCable::TestHelper + + it "broadcasts when the status changes" do + spreadsheet_import = create(:spreadsheet_import) + + expect { spreadsheet_import.update!(status: :processing) } + .to have_broadcasted_to("spreadsheet_import_#{spreadsheet_import.id}") + end + + it "broadcasts when total_rows changes" do + spreadsheet_import = create(:spreadsheet_import) + + expect { spreadsheet_import.update!(total_rows: 3) } + .to have_broadcasted_to("spreadsheet_import_#{spreadsheet_import.id}") + end + + it "does not auto-broadcast when only processed_rows changes (throttled explicitly by the job instead)" do + spreadsheet_import = create(:spreadsheet_import) + + expect { spreadsheet_import.update_columns(processed_rows: 1) } + .not_to have_broadcasted_to("spreadsheet_import_#{spreadsheet_import.id}") + end + + it "#broadcast_progress broadcasts on demand" do + spreadsheet_import = create(:spreadsheet_import) + + expect { spreadsheet_import.broadcast_progress } + .to have_broadcasted_to("spreadsheet_import_#{spreadsheet_import.id}") + end + + it "does not broadcast to a different import's stream" do + spreadsheet_import = create(:spreadsheet_import) + other_import = create(:spreadsheet_import) + + expect { spreadsheet_import.update!(status: :processing) } + .not_to have_broadcasted_to("spreadsheet_import_#{other_import.id}") + end + end +end diff --git a/spec/models/user_spec.rb b/spec/models/user_spec.rb new file mode 100644 index 000000000..f875e6838 --- /dev/null +++ b/spec/models/user_spec.rb @@ -0,0 +1,141 @@ +require "rails_helper" + +RSpec.describe User, type: :model do + describe "validations" do + subject { build(:user) } + + it { is_expected.to validate_presence_of(:full_name) } + it { is_expected.to validate_presence_of(:email) } + it { is_expected.to validate_uniqueness_of(:email).case_insensitive } + it { is_expected.to have_secure_password } + + it "rejects a malformed email" do + user = build(:user, email: "not-an-email") + + expect(user).not_to be_valid + expect(user.errors[:email]).to be_present + end + + it "rejects a password shorter than 8 characters" do + user = build(:user, password: "short1", password_confirmation: "short1") + + expect(user).not_to be_valid + expect(user.errors[:password]).to be_present + end + end + + describe "email normalization" do + it "strips whitespace and downcases the email before saving" do + user = create(:user, email: " MixedCase@Example.com ") + + expect(user.email).to eq("mixedcase@example.com") + end + end + + describe "role enum" do + it "defaults to no_admin" do + user = User.new + + expect(user.role).to eq("no_admin") + expect(user).to be_no_admin + end + + it { is_expected.to define_enum_for(:role).with_values(no_admin: 0, admin: 1) } + end + + describe "associations" do + it { is_expected.to have_many(:sessions).dependent(:destroy) } + end + + describe "avatar" do + it "accepts a supported image within the size limit" do + user = build(:user) + user.avatar.attach(io: StringIO.new("bytes"), filename: "avatar.png", content_type: "image/png") + + expect(user).to be_valid + end + + it "rejects an unsupported content type" do + user = build(:user) + user.avatar.attach(io: StringIO.new("not-an-image"), filename: "file.txt", content_type: "text/plain") + + expect(user).not_to be_valid + expect(user.errors[:avatar]).to be_present + end + + it "rejects a file that is too large" do + stub_const("User::AVATAR_MAX_BYTES", 10) + user = build(:user) + user.avatar.attach(io: StringIO.new("x" * 20), filename: "avatar.png", content_type: "image/png") + + expect(user).not_to be_valid + expect(user.errors[:avatar]).to be_present + end + end + + describe "avatar_url" do + it "rejects a value that is not a valid http(s) URL" do + user = build(:user, avatar_url: "not a url") + + expect(user).not_to be_valid + expect(user.errors[:avatar_url]).to be_present + end + + it "accepts a valid http(s) URL" do + user = build(:user, avatar_url: "https://example.com/avatar.png") + + expect(user).to be_valid + end + + it "enqueues a download job after a successful save" do + user = build(:user, avatar_url: "https://example.com/avatar.png") + + expect { user.save! }.to have_enqueued_job(AvatarDownloadJob).with { |id, url| + expect(id).to eq(user.id) + expect(url).to eq("https://example.com/avatar.png") + } + end + + it "does not enqueue a download job when blank" do + user = build(:user) + + expect { user.save! }.not_to have_enqueued_job(AvatarDownloadJob) + end + end + + describe "dashboard broadcasts" do + include ActionCable::TestHelper + + it "broadcasts updated counts when a user is created" do + expect { create(:user) }.to have_broadcasted_to("admin_dashboard") + end + + it "broadcasts updated counts when a user is destroyed" do + user = create(:user) + + expect { user.destroy }.to have_broadcasted_to("admin_dashboard") + end + + it "broadcasts updated counts when a user's role changes" do + user = create(:user) + + expect { user.update!(role: :admin) }.to have_broadcasted_to("admin_dashboard") + end + + it "does not broadcast when an unrelated attribute changes" do + user = create(:user) + + expect { user.update!(full_name: "New Name") }.not_to have_broadcasted_to("admin_dashboard") + end + + it "does not broadcast when skip_dashboard_broadcast is set (bulk import path)" do + user = build(:user, skip_dashboard_broadcast: true) + + expect { user.save! }.not_to have_broadcasted_to("admin_dashboard") + end + + it "self.broadcast_dashboard_counts! broadcasts on demand" do + expect { User.broadcast_dashboard_counts! }.to have_broadcasted_to("admin_dashboard") + end + end +end diff --git a/spec/policies/spreadsheet_import_policy_spec.rb b/spec/policies/spreadsheet_import_policy_spec.rb new file mode 100644 index 000000000..5bf2f76a8 --- /dev/null +++ b/spec/policies/spreadsheet_import_policy_spec.rb @@ -0,0 +1,35 @@ +require "rails_helper" + +RSpec.describe SpreadsheetImportPolicy do + let(:admin) { build_stubbed(:user, :admin) } + let(:no_admin) { build_stubbed(:user) } + + context "when the user is an admin" do + subject { described_class.new(admin, SpreadsheetImport) } + + it { is_expected.to permit_actions(:index, :show, :create) } + end + + context "when the user is not an admin" do + subject { described_class.new(no_admin, SpreadsheetImport) } + + it { is_expected.to forbid_actions(:index, :show, :create) } + end + + describe "Scope" do + let!(:admin_import) { create(:spreadsheet_import) } + let!(:other_import) { create(:spreadsheet_import) } + + it "resolves every import for an admin" do + resolved = SpreadsheetImportPolicy::Scope.new(admin, SpreadsheetImport.all).resolve + + expect(resolved).to contain_exactly(admin_import, other_import) + end + + it "resolves nothing for a no_admin user" do + resolved = SpreadsheetImportPolicy::Scope.new(no_admin, SpreadsheetImport.all).resolve + + expect(resolved).to be_empty + end + end +end diff --git a/spec/policies/user_policy_spec.rb b/spec/policies/user_policy_spec.rb new file mode 100644 index 000000000..7ed0793fd --- /dev/null +++ b/spec/policies/user_policy_spec.rb @@ -0,0 +1,43 @@ +require "rails_helper" + +RSpec.describe UserPolicy do + let(:admin) { build_stubbed(:user, :admin) } + let(:no_admin) { build_stubbed(:user) } + let(:other_no_admin) { build_stubbed(:user) } + + context "when the user is an admin" do + subject { described_class.new(admin, other_no_admin) } + + it { is_expected.to permit_all_actions } + end + + context "when the user manages their own record" do + subject { described_class.new(no_admin, no_admin) } + + it { is_expected.to permit_actions(:show, :update, :edit, :destroy) } + it { is_expected.to forbid_actions(:index, :create, :new, :toggle_role) } + end + + context "when the user tries to manage another user's record" do + subject { described_class.new(no_admin, other_no_admin) } + + it { is_expected.to forbid_all_actions } + end + + describe "Scope" do + let!(:admin_record) { create(:user, :admin) } + let!(:no_admin_record) { create(:user) } + + it "resolves every user for an admin" do + resolved = UserPolicy::Scope.new(admin, User.all).resolve + + expect(resolved).to contain_exactly(admin_record, no_admin_record) + end + + it "resolves only the user's own record for a no_admin user" do + resolved = UserPolicy::Scope.new(no_admin_record, User.all).resolve + + expect(resolved).to contain_exactly(no_admin_record) + end + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 000000000..f7c3f3851 --- /dev/null +++ b/spec/rails_helper.rb @@ -0,0 +1,72 @@ +# This file is copied to spec/ when you run 'rails generate rspec:install' +require 'spec_helper' +ENV['RAILS_ENV'] ||= 'test' +require_relative '../config/environment' +# Prevent database truncation if the environment is production +abort("The Rails environment is running in production mode!") if Rails.env.production? +# Uncomment the line below in case you have `--require rails_helper` in the `.rspec` file +# that will avoid rails generators crashing because migrations haven't been run yet +# return unless Rails.env.test? +require 'rspec/rails' +# Add additional requires below this line. Rails is not loaded until this point! + +# Requires supporting ruby files with custom matchers and macros, etc, in +# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are +# run as spec files by default. This means that files in spec/support that end +# in _spec.rb will both be required and run as specs, causing the specs to be +# run twice. It is recommended that you do not name files matching this glob to +# end with _spec.rb. You can configure this pattern with the --pattern +# option on the command line or in ~/.rspec, .rspec or `.rspec-local`. +# +# The following line is provided for convenience purposes. It has the downside +# of increasing the boot-up time by auto-requiring all files in the support +# directory. Alternatively, in the individual `*_spec.rb` files, manually +# require only the support files necessary. +# +Rails.root.glob('spec/support/**/*.rb').sort_by(&:to_s).each { |f| require f } + +# Ensures that the test database schema matches the current schema file. +# If there are pending migrations it will invoke `db:test:prepare` to +# recreate the test database by loading the schema. +# If you are not using ActiveRecord, you can remove these lines. +begin + ActiveRecord::Migration.maintain_test_schema! +rescue ActiveRecord::PendingMigrationError => e + abort e.to_s.strip +end +RSpec.configure do |config| + # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures + config.fixture_paths = [ + Rails.root.join('spec/fixtures') + ] + + # If you're not using ActiveRecord, or you'd prefer not to run each of your + # examples within a transaction, remove the following line or assign false + # instead of true. + config.use_transactional_fixtures = true + + # You can uncomment this line to turn off ActiveRecord support entirely. + # config.use_active_record = false + + # RSpec Rails uses metadata to mix in different behaviours to your tests, + # for example enabling you to call `get` and `post` in request specs. e.g.: + # + # RSpec.describe UsersController, type: :request do + # # ... + # end + # + # The different available types are documented in the features, such as in + # https://rspec.info/features/8-0/rspec-rails + # + # You can also infer these behaviours automatically by location, e.g. + # /spec/models would pull in the same behaviour as `type: :model` but this + # behaviour is considered legacy and will be removed in a future version. + # + # To enable this behaviour uncomment the line below. + 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") +end diff --git a/spec/requests/admin/dashboard_spec.rb b/spec/requests/admin/dashboard_spec.rb new file mode 100644 index 000000000..016c3af3a --- /dev/null +++ b/spec/requests/admin/dashboard_spec.rb @@ -0,0 +1,30 @@ +require "rails_helper" + +RSpec.describe "Admin::Painel", type: :request do + describe "GET /admin/dashboard" do + it "redirects unauthenticated visitors to sign in" do + get admin_dashboard_path + + expect(response).to redirect_to(new_session_path) + end + + it "redirects a signed in no_admin user to their profile with an alert" do + user = create(:user, password: "password123") + sign_in_as(user) + + get admin_dashboard_path + + expect(response).to redirect_to(profile_url) + expect(flash[:alert]).to be_present + end + + it "allows a signed in admin user" do + admin = create(:user, :admin, password: "password123") + sign_in_as(admin) + + get admin_dashboard_path + + expect(response).to have_http_status(:ok) + end + end +end diff --git a/spec/requests/admin/spreadsheet_imports_spec.rb b/spec/requests/admin/spreadsheet_imports_spec.rb new file mode 100644 index 000000000..d950cd813 --- /dev/null +++ b/spec/requests/admin/spreadsheet_imports_spec.rb @@ -0,0 +1,117 @@ +require "rails_helper" + +RSpec.describe "Admin::SpreadsheetImports", type: :request do + let(:admin) { create(:user, :admin, password: "password123") } + let(:csv_file) { fixture_file_upload("valid_import.csv", "text/csv") } + + describe "GET /admin/spreadsheet_imports" do + it "redirects unauthenticated visitors to sign in" do + get admin_spreadsheet_imports_path + + expect(response).to redirect_to(new_session_path) + end + + it "redirects a no_admin user to their profile" do + user = create(:user, password: "password123") + sign_in_as(user) + + get admin_spreadsheet_imports_path + + expect(response).to redirect_to(profile_url) + end + + it "lists imports for an admin" do + spreadsheet_import = create(:spreadsheet_import) + sign_in_as(admin) + + get admin_spreadsheet_imports_path + + expect(response).to have_http_status(:ok) + expect(response.body).to include(spreadsheet_import.file.filename.to_s) + end + end + + describe "GET /admin/spreadsheet_imports/new" do + it "is forbidden for a no_admin user" do + user = create(:user, password: "password123") + sign_in_as(user) + + get new_admin_spreadsheet_import_path + + expect(response).to redirect_to(profile_url) + end + + it "is accessible to an admin" do + sign_in_as(admin) + + get new_admin_spreadsheet_import_path + + expect(response).to have_http_status(:ok) + end + end + + describe "POST /admin/spreadsheet_imports" do + it "uploads a spreadsheet, enqueues the import job and redirects to its progress page" do + sign_in_as(admin) + + expect { + post admin_spreadsheet_imports_path, params: { spreadsheet_import: { file: csv_file } } + }.to change(SpreadsheetImport, :count).by(1).and have_enqueued_job(SpreadsheetImportJob) + + spreadsheet_import = SpreadsheetImport.last + expect(spreadsheet_import.user).to eq(admin) + expect(response).to redirect_to(admin_spreadsheet_import_url(spreadsheet_import)) + end + + it "accepts the has_header flag" do + sign_in_as(admin) + + post admin_spreadsheet_imports_path, params: { spreadsheet_import: { file: csv_file, has_header: false } } + + expect(SpreadsheetImport.last.has_header).to be false + end + + it "re-renders the form when no file is attached" do + sign_in_as(admin) + + expect { + post admin_spreadsheet_imports_path, params: { spreadsheet_import: { file: "" } } + }.not_to change(SpreadsheetImport, :count) + + expect(response).to have_http_status(:unprocessable_entity) + end + + it "is forbidden for a no_admin user" do + user = create(:user, password: "password123") + sign_in_as(user) + + expect { + post admin_spreadsheet_imports_path, params: { spreadsheet_import: { file: csv_file } } + }.not_to change(SpreadsheetImport, :count) + + expect(response).to redirect_to(profile_url) + end + end + + describe "GET /admin/spreadsheet_imports/:id" do + it "shows the import's progress to an admin" do + spreadsheet_import = create(:spreadsheet_import) + sign_in_as(admin) + + get admin_spreadsheet_import_path(spreadsheet_import) + + expect(response).to have_http_status(:ok) + expect(response.body).to include("linhas processadas") + end + + it "is forbidden for a no_admin user" do + spreadsheet_import = create(:spreadsheet_import) + user = create(:user, password: "password123") + sign_in_as(user) + + get admin_spreadsheet_import_path(spreadsheet_import) + + expect(response).to redirect_to(profile_url) + 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..21eab7109 --- /dev/null +++ b/spec/requests/admin/users_spec.rb @@ -0,0 +1,200 @@ +require "rails_helper" + +RSpec.describe "Admin::Users", type: :request do + let(:admin) { create(:user, :admin, password: "password123") } + + describe "GET /admin/users" do + it "redirects unauthenticated visitors to sign in" do + get admin_users_path + + expect(response).to redirect_to(new_session_path) + end + + it "redirects a no_admin user to their profile" do + user = create(:user, password: "password123") + sign_in_as(user) + + get admin_users_path + + expect(response).to redirect_to(profile_url) + end + + it "lists every user for an admin" do + other_user = create(:user) + sign_in_as(admin) + + get admin_users_path + + expect(response).to have_http_status(:ok) + expect(response.body).to include(admin.full_name) + expect(response.body).to include(other_user.full_name) + end + end + + describe "GET /admin/users/new" do + it "is forbidden for a no_admin user" do + user = create(:user, password: "password123") + sign_in_as(user) + + get new_admin_user_path + + expect(response).to redirect_to(profile_url) + end + + it "is accessible to an admin" do + sign_in_as(admin) + + get new_admin_user_path + + expect(response).to have_http_status(:ok) + end + end + + describe "POST /admin/users" do + it "allows an admin to create a user with any role" do + sign_in_as(admin) + + expect { + post admin_users_path, params: { + user: { + full_name: "New Admin", + email: "new-admin@example.com", + password: "password123", + password_confirmation: "password123", + role: "admin" + } + } + }.to change(User, :count).by(1) + + expect(User.find_by(email: "new-admin@example.com")).to be_admin + expect(response).to redirect_to(admin_users_url) + end + + it "enqueues an avatar download job when an avatar_url is given" do + sign_in_as(admin) + + expect { + post admin_users_path, params: { + user: { + full_name: "New User", + email: "new-user@example.com", + password: "password123", + password_confirmation: "password123", + role: "no_admin", + avatar_url: "https://example.com/avatar.png" + } + } + }.to have_enqueued_job(AvatarDownloadJob) + end + + it "is forbidden for a no_admin user" do + user = create(:user, password: "password123") + sign_in_as(user) + + expect { + post admin_users_path, params: { + user: { full_name: "X", email: "x@example.com", password: "password123", password_confirmation: "password123" } + } + }.not_to change(User, :count) + + expect(response).to redirect_to(profile_url) + end + + it "re-renders the form with errors when invalid" do + sign_in_as(admin) + + expect { + post admin_users_path, params: { user: { full_name: "", email: "", password: "", password_confirmation: "" } } + }.not_to change(User, :count) + + expect(response).to have_http_status(:unprocessable_entity) + end + end + + describe "PATCH /admin/users/:id" do + it "allows an admin to update another user, including their role" do + other_user = create(:user) + sign_in_as(admin) + + patch admin_user_path(other_user), params: { user: { full_name: "Updated Name", role: "admin" } } + + expect(response).to redirect_to(admin_users_url) + expect(other_user.reload.full_name).to eq("Updated Name") + expect(other_user).to be_admin + end + + it "keeps the current password when the password field is left blank" do + other_user = create(:user, password: "original-password") + sign_in_as(admin) + + patch admin_user_path(other_user), params: { user: { full_name: "Updated Name", password: "", password_confirmation: "" } } + + other_user.reload + expect(other_user.full_name).to eq("Updated Name") + expect(other_user.authenticate("original-password")).to eq(other_user) + end + + it "is forbidden for a no_admin user" do + other_user = create(:user) + user = create(:user, password: "password123") + sign_in_as(user) + + patch admin_user_path(other_user), params: { user: { full_name: "Hacked" } } + + expect(response).to redirect_to(profile_url) + expect(other_user.reload.full_name).not_to eq("Hacked") + end + + it "re-renders the form with errors when invalid" do + other_user = create(:user) + sign_in_as(admin) + + patch admin_user_path(other_user), params: { user: { full_name: "", email: "" } } + + expect(response).to have_http_status(:unprocessable_entity) + end + end + + describe "DELETE /admin/users/:id" do + it "allows an admin to delete another user" do + other_user = create(:user) + sign_in_as(admin) + + expect { delete admin_user_path(other_user) }.to change(User, :count).by(-1) + expect(response).to redirect_to(admin_users_url) + end + end + + describe "PATCH /admin/users/:id/toggle_role" do + it "toggles another user's role" do + other_user = create(:user) + sign_in_as(admin) + + patch toggle_role_admin_user_path(other_user) + + expect(other_user.reload).to be_admin + expect(response).to redirect_to(admin_users_url) + end + + it "refuses to let an admin change their own role" do + sign_in_as(admin) + + patch toggle_role_admin_user_path(admin) + + expect(admin.reload).to be_admin + expect(response).to redirect_to(admin_users_url) + expect(flash[:alert]).to be_present + end + + it "is forbidden for a no_admin user" do + other_user = create(:user) + user = create(:user, password: "password123") + sign_in_as(user) + + patch toggle_role_admin_user_path(other_user) + + expect(other_user.reload).not_to be_admin + expect(response).to redirect_to(profile_url) + end + end +end diff --git a/spec/requests/health_check_spec.rb b/spec/requests/health_check_spec.rb new file mode 100644 index 000000000..ddeecc794 --- /dev/null +++ b/spec/requests/health_check_spec.rb @@ -0,0 +1,9 @@ +require "rails_helper" + +RSpec.describe "Health check", type: :request do + it "responds with 200 OK on GET /up" do + get "/up" + + expect(response).to have_http_status(:ok) + end +end diff --git a/spec/requests/passwords_spec.rb b/spec/requests/passwords_spec.rb new file mode 100644 index 000000000..8c11abdec --- /dev/null +++ b/spec/requests/passwords_spec.rb @@ -0,0 +1,75 @@ +require "rails_helper" + +RSpec.describe "Passwords", type: :request do + describe "GET /passwords/new" do + it "is accessible to a visitor" do + get new_password_path + + expect(response).to have_http_status(:ok) + end + end + + describe "POST /passwords" do + it "sends a reset e-mail when the address exists" do + user = create(:user) + + expect { + post passwords_path, params: { email: user.email } + }.to have_enqueued_mail(PasswordsMailer, :reset) + + expect(response).to redirect_to(new_session_path) + end + + it "does not reveal whether the e-mail exists" do + expect { + post passwords_path, params: { email: "nobody@example.com" } + }.not_to have_enqueued_mail(PasswordsMailer, :reset) + + expect(response).to redirect_to(new_session_path) + follow_redirect! + expect(response.body).to include("Instruções de redefinição enviadas (caso o e-mail exista).") + end + end + + describe "GET /passwords/:token/edit" do + it "is accessible with a valid token" do + user = create(:user) + + get edit_password_path(user.password_reset_token) + + expect(response).to have_http_status(:ok) + end + + it "redirects with an alert when the token is invalid or expired" do + get edit_password_path("bogus-token") + + expect(response).to redirect_to(new_password_path) + follow_redirect! + expect(response.body).to include("O link de redefinição é inválido ou expirou.") + end + end + + describe "PATCH /passwords/:token" do + it "updates the password and signs the user out of every session" do + user = create(:user, password: "old-password123") + sign_in_as(user, password: "old-password123") + token = user.password_reset_token + + patch password_path(token), params: { user: { password: "new-password123", password_confirmation: "new-password123" } } + + expect(response).to redirect_to(new_session_path) + expect(user.reload.authenticate("new-password123")).to eq(user) + expect(user.sessions.count).to eq(0) + end + + it "redirects back to edit with an alert when the confirmation does not match" do + user = create(:user) + token = user.password_reset_token + + patch password_path(token), params: { user: { password: "new-password123", password_confirmation: "mismatch" } } + + expect(response).to redirect_to(edit_password_path(token)) + expect(user.reload.authenticate("new-password123")).to be false + end + end +end diff --git a/spec/requests/profiles_spec.rb b/spec/requests/profiles_spec.rb new file mode 100644 index 000000000..a95198061 --- /dev/null +++ b/spec/requests/profiles_spec.rb @@ -0,0 +1,95 @@ +require "rails_helper" + +RSpec.describe "Profiles", type: :request do + describe "GET /profile" do + it "redirects unauthenticated visitors to sign in" do + get profile_path + + expect(response).to redirect_to(new_session_path) + end + + it "shows the signed in user's own info" do + user = create(:user, password: "password123") + sign_in_as(user) + + get profile_path + + expect(response).to have_http_status(:ok) + expect(response.body).to include(user.full_name) + end + end + + describe "GET /profile/edit" do + it "is accessible to the signed in user" do + user = create(:user, password: "password123") + sign_in_as(user) + + get edit_profile_path + + expect(response).to have_http_status(:ok) + end + end + + describe "PATCH /profile" do + it "updates the signed in user's own info" do + user = create(:user, password: "password123") + sign_in_as(user) + + patch profile_path, params: { user: { full_name: "New Name" } } + + expect(response).to redirect_to(profile_url) + expect(user.reload.full_name).to eq("New Name") + end + + it "keeps the current password when the password field is left blank" do + user = create(:user, password: "original-password") + sign_in_as(user, password: "original-password") + + patch profile_path, params: { user: { full_name: "New Name", password: "", password_confirmation: "" } } + + user.reload + expect(user.full_name).to eq("New Name") + expect(user.authenticate("original-password")).to eq(user) + end + + it "ignores an injected role param and never promotes the user to admin" do + user = create(:user, password: "password123") + sign_in_as(user) + + patch profile_path, params: { user: { full_name: "New Name", role: "admin" } } + + expect(user.reload).to be_no_admin + end + + it "enqueues an avatar download job when an avatar_url is given" do + user = create(:user, password: "password123") + sign_in_as(user) + + expect { + patch profile_path, params: { user: { avatar_url: "https://example.com/avatar.png" } } + }.to have_enqueued_job(AvatarDownloadJob).with(user.id, "https://example.com/avatar.png") + end + + it "re-renders the form with errors when invalid" do + user = create(:user, password: "password123") + sign_in_as(user) + + patch profile_path, params: { user: { email: "" } } + + expect(response).to have_http_status(:unprocessable_entity) + end + end + + describe "DELETE /profile" do + it "deletes the signed in user's own account and signs them out" do + user = create(:user, password: "password123") + sign_in_as(user) + + expect { delete profile_path }.to change(User, :count).by(-1) + expect(response).to redirect_to(new_session_path) + + get profile_path + expect(response).to redirect_to(new_session_path) + end + end +end diff --git a/spec/requests/registrations_spec.rb b/spec/requests/registrations_spec.rb new file mode 100644 index 000000000..863642a23 --- /dev/null +++ b/spec/requests/registrations_spec.rb @@ -0,0 +1,63 @@ +require "rails_helper" + +RSpec.describe "Registrations", type: :request do + describe "GET /registration/new" do + it "is accessible to a visitor" do + get new_registration_path + + expect(response).to have_http_status(:ok) + end + end + + describe "POST /registration" do + it "creates a no_admin user, signs them in, and redirects to the profile" do + expect { + post registration_path, params: { + user: { + full_name: "Ada Lovelace", + email: "ada@example.com", + password: "password123", + password_confirmation: "password123" + } + } + }.to change(User, :count).by(1) + + user = User.find_by(email: "ada@example.com") + expect(user).to be_no_admin + expect(response).to redirect_to(profile_url) + + get profile_path + expect(response).to have_http_status(:ok) + end + + it "ignores a role param and always forces no_admin" do + post registration_path, params: { + user: { + full_name: "Eve Attacker", + email: "eve@example.com", + password: "password123", + password_confirmation: "password123", + role: "admin" + } + } + + user = User.find_by(email: "eve@example.com") + expect(user).to be_no_admin + end + + it "re-renders the form with errors when the password confirmation does not match" do + expect { + post registration_path, params: { + user: { + full_name: "Ada Lovelace", + email: "ada@example.com", + password: "password123", + password_confirmation: "mismatch" + } + } + }.not_to change(User, :count) + + expect(response).to have_http_status(:unprocessable_entity) + end + end +end diff --git a/spec/requests/security_spec.rb b/spec/requests/security_spec.rb new file mode 100644 index 000000000..3233843e7 --- /dev/null +++ b/spec/requests/security_spec.rb @@ -0,0 +1,72 @@ +require "rails_helper" + +RSpec.describe "Security", type: :request do + describe "SQL injection" do + it "does not let a crafted email bypass authentication" do + create(:user, email: "victim@example.com", password: "password123") + + post session_path, params: { email: "' OR '1'='1", password: "anything" } + + expect(response).to redirect_to(new_session_path) + expect(flash[:alert]).to be_present + end + + it "treats a crafted email as a literal, parameterized value with no match" do + create(:user, email: "victim@example.com") + + expect(User.find_by(email: "' OR '1'='1")).to be_nil + end + end + + describe "reflected/stored XSS" do + it "escapes a malicious full_name when rendering the profile page" do + payload = "" + user = create(:user, full_name: payload, password: "password123") + sign_in_as(user) + + get profile_path + + expect(response.body).not_to include(payload) + expect(response.body).to include(CGI.escapeHTML(payload)) + end + + it "escapes a malicious full_name when rendering the admin users list" do + payload = "" + admin = create(:user, :admin, password: "password123") + create(:user, full_name: payload) + sign_in_as(admin) + + get admin_users_path + + expect(response.body).not_to include(payload) + expect(response.body).to include(CGI.escapeHTML(payload)) + end + end + + describe "CSRF protection" do + around do |example| + original = ActionController::Base.allow_forgery_protection + ActionController::Base.allow_forgery_protection = true + begin + example.run + ensure + ActionController::Base.allow_forgery_protection = original + end + end + + it "rejects a state-changing request without a valid authenticity token" do + expect { + post registration_path, params: { + user: { + full_name: "Attacker", + email: "attacker@example.com", + password: "password123", + password_confirmation: "password123" + } + } + }.not_to change(User, :count) + + expect(response).to have_http_status(:unprocessable_entity) + end + end +end diff --git a/spec/requests/sessions_spec.rb b/spec/requests/sessions_spec.rb new file mode 100644 index 000000000..94d8e5438 --- /dev/null +++ b/spec/requests/sessions_spec.rb @@ -0,0 +1,43 @@ +require "rails_helper" + +RSpec.describe "Sessions", type: :request do + describe "POST /session" do + it "signs in a no_admin user and redirects to the profile" do + user = create(:user, password: "password123") + + sign_in_as(user) + + expect(response).to redirect_to(profile_url) + end + + it "signs in an admin user and redirects to the admin dashboard" do + admin = create(:user, :admin, password: "password123") + + sign_in_as(admin, password: "password123") + + expect(response).to redirect_to(admin_dashboard_url) + end + + it "rejects invalid credentials" do + user = create(:user, password: "password123") + + sign_in_as(user, password: "wrong-password") + + expect(response).to redirect_to(new_session_path) + expect(flash[:alert]).to be_present + end + end + + describe "DELETE /session" do + it "signs the user out" do + user = create(:user, password: "password123") + sign_in_as(user) + + delete session_path + + expect(response).to redirect_to(new_session_path) + get profile_path + expect(response).to redirect_to(new_session_path) + end + end +end diff --git a/spec/services/avatar_fetcher_spec.rb b/spec/services/avatar_fetcher_spec.rb new file mode 100644 index 000000000..54aa56013 --- /dev/null +++ b/spec/services/avatar_fetcher_spec.rb @@ -0,0 +1,111 @@ +require "rails_helper" + +RSpec.describe AvatarFetcher do + let(:public_ip) { "93.184.216.34" } + + def allow_resolve(host, ip_or_ips) + allow(Resolv).to receive(:getaddresses).with(host).and_return(Array(ip_or_ips)) + end + + describe "#fetch" do + it "downloads and returns the image when the content type and size are allowed" do + allow_resolve("example.com", public_ip) + stub_request(:get, "http://example.com/avatar.png") + .to_return(status: 200, body: "fake-image-bytes", headers: { "Content-Type" => "image/png" }) + + result = described_class.new("http://example.com/avatar.png").fetch + + expect(result.content_type).to eq("image/png") + expect(result.filename).to eq("avatar.png") + expect(result.io.read).to eq("fake-image-bytes") + end + + it "follows redirects" do + allow_resolve("example.com", public_ip) + allow_resolve("cdn.example.com", public_ip) + stub_request(:get, "http://example.com/avatar.png") + .to_return(status: 302, headers: { "Location" => "http://cdn.example.com/avatar.png" }) + stub_request(:get, "http://cdn.example.com/avatar.png") + .to_return(status: 200, body: "redirected-bytes", headers: { "Content-Type" => "image/jpeg" }) + + result = described_class.new("http://example.com/avatar.png").fetch + + expect(result.content_type).to eq("image/jpeg") + end + + it "raises when there are too many redirects" do + stub_const("AvatarFetcher::MAX_REDIRECTS", 1) + allow_resolve("example.com", public_ip) + stub_request(:get, "http://example.com/a").to_return(status: 302, headers: { "Location" => "http://example.com/b" }) + stub_request(:get, "http://example.com/b").to_return(status: 302, headers: { "Location" => "http://example.com/c" }) + + expect { described_class.new("http://example.com/a").fetch } + .to raise_error(AvatarFetcher::FetchError, /redirect/) + end + + it "rejects non-http(s) schemes" do + expect { described_class.new("file:///etc/passwd").fetch } + .to raise_error(AvatarFetcher::FetchError, /invalid URL/) + end + + it "rejects a host that cannot be resolved" do + allow_resolve("nowhere.invalid", []) + + expect { described_class.new("http://nowhere.invalid/avatar.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /resolve/) + end + + it "rejects URLs that resolve to a private address" do + allow_resolve("internal.example.com", "10.0.0.5") + + expect { described_class.new("http://internal.example.com/avatar.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /disallowed address/) + end + + it "rejects URLs that resolve to the loopback address" do + allow_resolve("localhost.example.com", "127.0.0.1") + + expect { described_class.new("http://localhost.example.com/avatar.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /disallowed address/) + end + + it "rejects URLs that resolve to a link-local / cloud metadata address" do + allow_resolve("metadata.example.com", "169.254.169.254") + + expect { described_class.new("http://metadata.example.com/avatar.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /disallowed address/) + end + + it "rejects a disallowed content type" do + allow_resolve("example.com", public_ip) + stub_request(:get, "http://example.com/not-an-image.html") + .to_return(status: 200, body: "", headers: { "Content-Type" => "text/html" }) + + expect { described_class.new("http://example.com/not-an-image.html").fetch } + .to raise_error(AvatarFetcher::FetchError, /unsupported content type/) + end + + it "rejects a file that exceeds the maximum size" do + stub_const("AvatarFetcher::MAX_BYTES", 10) + allow_resolve("example.com", public_ip) + stub_request(:get, "http://example.com/big.png") + .to_return(status: 200, body: "x" * 20, headers: { "Content-Type" => "image/png" }) + + expect { described_class.new("http://example.com/big.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /too large/) + end + + it "rejects an unexpected (non-success, non-redirect) response" do + allow_resolve("example.com", public_ip) + stub_request(:get, "http://example.com/missing.png").to_return(status: 404) + + expect { described_class.new("http://example.com/missing.png").fetch } + .to raise_error(AvatarFetcher::FetchError, /unexpected response/) + end + + it "rejects a malformed URL" do + expect { described_class.new("http://exa mple.com/x").fetch } + .to raise_error(AvatarFetcher::FetchError, /invalid URL/) + end + end +end diff --git a/spec/services/spreadsheet_import_row_importer_spec.rb b/spec/services/spreadsheet_import_row_importer_spec.rb new file mode 100644 index 000000000..66181d00a --- /dev/null +++ b/spec/services/spreadsheet_import_row_importer_spec.rb @@ -0,0 +1,53 @@ +require "rails_helper" + +RSpec.describe SpreadsheetImportRowImporter do + include ActionCable::TestHelper + + let(:spreadsheet_import) { create(:spreadsheet_import) } + let(:importer) { described_class.new(spreadsheet_import) } + + before { importer } # force creation (and its associated admin user) outside the expect blocks below + + describe "#import" do + it "creates a user and returns true for a valid row" do + expect { + expect(importer.import(2, { "nome" => "Alice Example", "email" => "alice@example.com" })).to be true + }.to change(User, :count).by(1) + + user = User.find_by(email: "alice@example.com") + expect(user.full_name).to eq("Alice Example") + expect(user).to be_no_admin + end + + it "gives the imported user an unguessable random password" do + importer.import(2, { "nome" => "Alice Example", "email" => "alice@example.com" }) + + user = User.find_by(email: "alice@example.com") + expect(user.authenticate("password123")).to be false + end + + it "sends a welcome e-mail so the user can set a real password" do + expect { + importer.import(2, { "nome" => "Alice Example", "email" => "alice@example.com" }) + }.to have_enqueued_mail(PasswordsMailer, :welcome) + end + + it "does not create a user or send an e-mail, and records a row error, for invalid data" do + expect { + expect { + expect(importer.import(3, { "nome" => "Missing Email", "email" => "" })).to be false + }.not_to change(User, :count) + }.not_to have_enqueued_mail(PasswordsMailer, :welcome) + + error = spreadsheet_import.spreadsheet_import_row_errors.sole + expect(error.row_number).to eq(3) + expect(error.message).to match(/e-mail não pode ficar em branco/i) + end + + it "does not trigger a dashboard broadcast for the imported user (bulk import path)" do + expect { + importer.import(2, { "nome" => "Alice Example", "email" => "alice@example.com" }) + }.not_to have_broadcasted_to("admin_dashboard") + end + end +end diff --git a/spec/services/spreadsheet_parser_spec.rb b/spec/services/spreadsheet_parser_spec.rb new file mode 100644 index 000000000..27263b676 --- /dev/null +++ b/spec/services/spreadsheet_parser_spec.rb @@ -0,0 +1,65 @@ +require "rails_helper" + +RSpec.describe SpreadsheetParser do + def spreadsheet_import_with(fixture_name, content_type, **attrs) + spreadsheet_import = create(:spreadsheet_import, **attrs) + spreadsheet_import.file.attach( + io: File.open(Rails.root.join("spec/fixtures/files", fixture_name)), + filename: fixture_name, + content_type: content_type + ) + spreadsheet_import + end + + describe "#rows" do + it "maps columns positionally: 1st column is always the name, 2nd is always the email" do + spreadsheet_import = spreadsheet_import_with("valid_import.csv", "text/csv") + + rows = described_class.new(spreadsheet_import).rows + + expect(rows).to include([ 2, { "nome" => "Alice Example", "email" => "alice@example.com" } ]) + end + + it "never uses the header row's own text to map columns, even when it doesn't say nome/email" do + spreadsheet_import = spreadsheet_import_with("header_labels_mismatch_import.csv", "text/csv", has_header: true) + + rows = described_class.new(spreadsheet_import).rows + + expect(rows).to eq([ [ 2, { "nome" => "Henry Example", "email" => "henry@example.com" } ] ]) + end + + it "treats the first row as real data (positionally) when has_header is false" do + spreadsheet_import = spreadsheet_import_with("valid_import_no_header.csv", "text/csv", has_header: false) + + rows = described_class.new(spreadsheet_import).rows + + expect(rows).to eq([ + [ 1, { "nome" => "Frank Example", "email" => "frank@example.com" } ], + [ 2, { "nome" => "Grace Example", "email" => "grace@example.com" } ] + ]) + end + + it "skips blank rows" do + spreadsheet_import = spreadsheet_import_with("mixed_import.csv", "text/csv") + + rows = described_class.new(spreadsheet_import).rows + + expect(rows.map(&:first)).to eq([ 2, 3, 4, 5, 6 ]) + end + + it "reads both CSV and XLSX through the same API" do + csv_rows = described_class.new(spreadsheet_import_with("mixed_import.csv", "text/csv")).rows + xlsx_rows = described_class.new( + spreadsheet_import_with("mixed_import.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") + ).rows + + expect(xlsx_rows).to eq(csv_rows) + end + + it "raises a ParseError instead of a raw parsing exception when the file is malformed" do + spreadsheet_import = spreadsheet_import_with("malformed_import.csv", "text/csv") + + expect { described_class.new(spreadsheet_import).rows }.to raise_error(described_class::ParseError) + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 000000000..613b2efd1 --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,102 @@ +# 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 +require "simplecov" +SimpleCov.start "rails" do + skip "/spec/" + skip "/config/" + skip "/db/" + + # Only enforced on a plain sequential `bundle exec rspec` run: each + # parallel_rspec worker (TEST_ENV_NUMBER set) only exercises a slice of the + # suite, so its own coverage is never representative of the whole. + minimum_coverage 90 unless ENV["TEST_ENV_NUMBER"] +end + +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 context metadata to be + # inherited by the metadata hash of host groups and examples, rather than + # triggering implicit auto-inclusion in groups with matching metadata. + config.shared_context_metadata_behavior = :apply_to_host_groups + + # This allows you to limit a spec run to individual examples or groups + # you care about by tagging them with `:focus` metadata. When nothing + # is tagged with `:focus`, all examples get run. RSpec also provides + # aliases for `it`, `describe`, and `context` that include `:focus` + # metadata: `fit`, `fdescribe` and `fcontext`, respectively. + config.filter_run_when_matching :focus + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # https://rspec.info/features/3-12/rspec-core/configuration/zero-monkey-patching-mode/ + config.disable_monkey_patching! + + # 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/spec/support/authentication_helpers.rb b/spec/support/authentication_helpers.rb new file mode 100644 index 000000000..a5d7f4f12 --- /dev/null +++ b/spec/support/authentication_helpers.rb @@ -0,0 +1,17 @@ +module AuthenticationHelpers + def sign_in_as(user, password: "password123") + post session_path, params: { email: user.email, password: password } + end + + def sign_in_via_ui(user, password: "password123") + visit new_session_path + fill_in "email", with: user.email + fill_in "password", with: password + click_button "Entrar" + end +end + +RSpec.configure do |config| + config.include AuthenticationHelpers, type: :request + config.include AuthenticationHelpers, type: :system +end diff --git a/spec/support/capybara.rb b/spec/support/capybara.rb new file mode 100644 index 000000000..d54f8897e --- /dev/null +++ b/spec/support/capybara.rb @@ -0,0 +1,14 @@ +require "capybara-playwright-driver" + +Capybara.register_driver(:playwright) do |app| + Capybara::Playwright::Driver.new(app, browser_type: :chromium, headless: true) +end + +Capybara.default_max_wait_time = 5 +Capybara.save_path = Rails.root.join("tmp/capybara") + +RSpec.configure do |config| + config.before(:each, type: :system) do + driven_by :playwright + end +end diff --git a/spec/support/factory_bot.rb b/spec/support/factory_bot.rb new file mode 100644 index 000000000..c7890e49c --- /dev/null +++ b/spec/support/factory_bot.rb @@ -0,0 +1,3 @@ +RSpec.configure do |config| + config.include FactoryBot::Syntax::Methods +end diff --git a/spec/support/shoulda_matchers.rb b/spec/support/shoulda_matchers.rb new file mode 100644 index 000000000..7d045f359 --- /dev/null +++ b/spec/support/shoulda_matchers.rb @@ -0,0 +1,6 @@ +Shoulda::Matchers.configure do |config| + config.integrate do |with| + with.test_framework :rspec + with.library :rails + end +end diff --git a/spec/support/webmock.rb b/spec/support/webmock.rb new file mode 100644 index 000000000..4b72e2ceb --- /dev/null +++ b/spec/support/webmock.rb @@ -0,0 +1,3 @@ +require "webmock/rspec" + +WebMock.disable_net_connect!(allow_localhost: true) diff --git a/spec/system/admin_dashboard_live_updates_spec.rb b/spec/system/admin_dashboard_live_updates_spec.rb new file mode 100644 index 000000000..2e91622aa --- /dev/null +++ b/spec/system/admin_dashboard_live_updates_spec.rb @@ -0,0 +1,37 @@ +require "rails_helper" + +RSpec.describe "Admin dashboard live updates", type: :system do + it "reflects a user created by one admin in another admin's dashboard without a reload" do + admin_one = create(:user, :admin, password: "password123") + admin_two = create(:user, :admin, password: "password123") + + using_session(:admin_two) do + sign_in_via_ui(admin_two) + + within("#dashboard_counts") do + expect(page).to have_content("Total de Usuários") + expect(page).to have_content("2") + end + end + + using_session(:admin_one) do + sign_in_via_ui(admin_one) + click_link "Usuários" + click_link "Novo Usuário" + + fill_in "Nome", with: "Grace Hopper" + fill_in "E-mail", with: "grace-live@example.com" + fill_in "Senha", with: "password123", exact: true + fill_in "Confirmar senha", with: "password123" + click_button "Criar Usuário" + + expect(page).to have_content("Usuário criado com sucesso") + end + + using_session(:admin_two) do + within("#dashboard_counts") do + expect(page).to have_content("3") + end + end + end +end diff --git a/spec/system/admin_spreadsheet_import_live_progress_spec.rb b/spec/system/admin_spreadsheet_import_live_progress_spec.rb new file mode 100644 index 000000000..ef3d83e6a --- /dev/null +++ b/spec/system/admin_spreadsheet_import_live_progress_spec.rb @@ -0,0 +1,30 @@ +require "rails_helper" + +RSpec.describe "Admin spreadsheet import live progress", type: :system do + it "updates the progress bar and status live as the background job processes rows" do + admin = create(:user, :admin, password: "password123") + + sign_in_via_ui(admin) + click_link "Importações de Planilha" + click_link "Nova Importação" + + attach_file "Planilha (CSV ou XLSX)", Rails.root.join("spec/fixtures/files/valid_import.csv") + expect(page).to have_checked_field("Este arquivo tem uma linha de cabeçalho") + click_button "Enviar" + + expect(page).to have_content("Planilha enviada. A importação está sendo processada em segundo plano.") + within("#spreadsheet_import_progress") do + expect(page).to have_content("Pendente") + expect(page).to have_content("0 / 0 linhas processadas") + end + + SpreadsheetImportJob.perform_now(SpreadsheetImport.last.id) + + within("#spreadsheet_import_progress") do + expect(page).to have_content("Concluída") + expect(page).to have_content("3 / 3 linhas processadas") + end + + expect(User.exists?(email: "alice@example.com")).to be true + end +end diff --git a/spec/system/responsive_navigation_spec.rb b/spec/system/responsive_navigation_spec.rb new file mode 100644 index 000000000..25ecaca0b --- /dev/null +++ b/spec/system/responsive_navigation_spec.rb @@ -0,0 +1,31 @@ +require "rails_helper" + +RSpec.describe "Responsive navigation", type: :system do + after { Capybara.current_window.resize_to(1280, 800) } + + it "shows the nav links inline on a desktop viewport" do + Capybara.current_window.resize_to(1280, 800) + user = create(:user, password: "password123") + + sign_in_via_ui(user) + + expect(page).to have_link("Meu Perfil", visible: true) + expect(page).not_to have_button("Menu", visible: true) + end + + it "collapses the nav behind a toggle button on a mobile viewport" do + Capybara.current_window.resize_to(375, 667) + admin = create(:user, :admin, password: "password123") + + sign_in_via_ui(admin) + + expect(page).to have_button("Menu", visible: true) + expect(page).to have_link("Usuários", visible: :all) + + click_button "Menu" + click_link "Usuários" + + expect(page).to have_content("Usuários") + expect(page).to have_link("Novo Usuário") + end +end diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/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