diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..325bfc036d --- /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/.gitattributes b/.gitattributes new file mode 100644 index 0000000000..8dc4323435 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,9 @@ +# See https://git-scm.com/docs/gitattributes for more about git attribute files. + +# Mark the database schema as having been generated. +db/schema.rb linguist-generated + +# Mark any vendored files as having been vendored. +vendor/* linguist-vendored +config/credentials/*.yml.enc diff=rails_credentials +config/credentials.yml.enc diff=rails_credentials diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000000..83610cfa4c --- /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 0000000000..d0cf862cbd --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,88 @@ +name: CI + +on: + pull_request: + push: + branches: [ main ] + +jobs: + scan_ruby: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - 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 + + scan_js: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - 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@v4 + + - 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 + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Install Chrome + uses: browser-actions/setup-chrome@v1 + + - name: Set up database + run: bin/rails db:test:prepare + + - name: Run Cucumber tests + run: bundle exec cucumber + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000..a82c6d42e9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,38 @@ +# See https://help.github.com/articles/ignoring-files for more about ignoring files. +# +# Temporary files generated by your text editor or operating system +# belong in git's global ignore instead: +# `$XDG_CONFIG_HOME/git/ignore` or `~/.config/git/ignore` + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/ +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/ +!/tmp/storage/.keep + +/public/assets + +# Ignore key files for decrypting credentials and more. +/config/*.key + +# Ignore Kamal secrets (may contain real credentials) +/.kamal/secrets + diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 0000000000..2fb07d7d7a --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 0000000000..70f9c4bc95 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 0000000000..fd364c2a77 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/bin/sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 0000000000..1435a677f2 --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 0000000000..45f7355045 --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 0000000000..c5a55678b2 --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/bin/sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 0000000000..77744bdca8 --- /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 0000000000..05b3055b72 --- /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 0000000000..061f8059e6 --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.kamal/secrets b/.kamal/secrets new file mode 100644 index 0000000000..b3089d6f5a --- /dev/null +++ b/.kamal/secrets @@ -0,0 +1,20 @@ +# 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 +# KAMAL_REGISTRY_PASSWORD=$KAMAL_REGISTRY_PASSWORD + +# 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 0000000000..c99d2e7396 --- /dev/null +++ b/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000000..f9d86d4a54 --- /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 0000000000..1cf8253024 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +3.4.6 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000..36831f424b --- /dev/null +++ b/Dockerfile @@ -0,0 +1,77 @@ +# 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 camaar . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name camaar camaar + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=3.4.6 +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. +ENV RAILS_ENV="production" \ + BUNDLE_DEPLOYMENT="1" \ + BUNDLE_PATH="/usr/local/bundle" \ + BUNDLE_WITHOUT="development" \ + LD_PRELOAD="/usr/local/lib/libjemalloc.so" + +# 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 0000000000..9199cbb410 --- /dev/null +++ b/Gemfile @@ -0,0 +1,69 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.3" +# 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" +# Build JSON APIs with ease [https://github.com/rails/jbuilder] +gem "jbuilder" + +# Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] +gem "bcrypt", "~> 3.1.7" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # 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 + + gem "rspec-rails" +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + gem "cucumber-rails", require: false + gem "database_cleaner" + gem "capybara" + gem "selenium-webdriver" +end \ No newline at end of file diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 0000000000..df01ec5e06 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,650 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.3) + actionpack (= 8.1.3) + activesupport (= 8.1.3) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.3) + actionpack (= 8.1.3) + activejob (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + mail (>= 2.8.0) + actionmailer (8.1.3) + actionpack (= 8.1.3) + actionview (= 8.1.3) + activejob (= 8.1.3) + activesupport (= 8.1.3) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.3) + actionview (= 8.1.3) + activesupport (= 8.1.3) + 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) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.3) + activesupport (= 8.1.3) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.3) + activesupport (= 8.1.3) + globalid (>= 0.3.6) + activemodel (8.1.3) + activesupport (= 8.1.3) + activerecord (8.1.3) + activemodel (= 8.1.3) + activesupport (= 8.1.3) + timeout (>= 0.4.0) + activestorage (8.1.3) + actionpack (= 8.1.3) + activejob (= 8.1.3) + activerecord (= 8.1.3) + activesupport (= 8.1.3) + marcel (~> 1.0) + activesupport (8.1.3) + 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.24.5) + msgpack (~> 1.2) + brakeman (8.0.4) + 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) + concurrent-ruby (1.3.6) + connection_pool (3.0.2) + crass (1.0.6) + cucumber (10.2.0) + base64 (~> 0.2) + builder (~> 3.2) + cucumber-ci-environment (> 9, < 12) + cucumber-core (> 15, < 17) + cucumber-cucumber-expressions (> 17, < 20) + cucumber-html-formatter (> 21, < 23) + diff-lcs (~> 1.5) + logger (~> 1.6) + mini_mime (~> 1.1) + multi_test (~> 1.1) + sys-uname (~> 1.3) + cucumber-ci-environment (11.0.0) + cucumber-core (16.2.0) + cucumber-gherkin (> 36, < 40) + cucumber-messages (> 31, < 33) + cucumber-tag-expressions (> 6, < 9) + cucumber-cucumber-expressions (19.0.1) + bigdecimal + cucumber-gherkin (39.1.0) + cucumber-messages (>= 31, < 33) + cucumber-html-formatter (22.3.0) + cucumber-messages (> 23, < 33) + cucumber-messages (32.3.1) + cucumber-rails (4.0.1) + capybara (>= 3.25, < 4) + cucumber (>= 7, < 11) + railties (>= 6.1, < 9) + cucumber-tag-expressions (8.1.0) + database_cleaner (2.1.0) + database_cleaner-active_record (>= 2, < 3) + database_cleaner-active_record (2.2.2) + activerecord (>= 5.a) + database_cleaner-core (~> 2.0) + database_cleaner-core (2.1.0) + 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.4) + erubi (1.13.1) + et-orbi (1.4.0) + tzinfo + 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-arm64-darwin) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fugit (1.12.2) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.3.0) + activesupport (>= 6.1) + i18n (1.14.8) + 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.8.2) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.15.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.19.7) + kamal (2.11.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.5) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.1) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.0) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + matrix (0.4.3) + memoist3 (1.0.0) + mini_magick (5.3.1) + logger + mini_mime (1.1.5) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + msgpack (1.8.1) + multi_test (1.1.0) + net-imap (0.6.4) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.2) + nio4r (2.7.5) + nokogiri (1.19.3-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.3-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.3-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.3-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.3-arm64-darwin) + racc (~> 1.4) + nokogiri (1.19.3-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.3-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (2.1.0) + parser (3.3.11.1) + ast (~> 2.4.1) + racc + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.9.0) + propshaft (1.3.2) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + psych (5.3.1) + date + stringio + public_suffix (7.0.5) + puma (8.0.2) + nio4r (~> 2.0) + raabro (1.4.0) + racc (1.8.1) + rack (3.2.6) + 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) + actioncable (= 8.1.3) + actionmailbox (= 8.1.3) + actionmailer (= 8.1.3) + actionpack (= 8.1.3) + actiontext (= 8.1.3) + actionview (= 8.1.3) + activejob (= 8.1.3) + activemodel (= 8.1.3) + activerecord (= 8.1.3) + activestorage (= 8.1.3) + activesupport (= 8.1.3) + bundler (>= 1.15.0) + railties (= 8.1.3) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.0) + loofah (~> 2.25) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.3) + actionpack (= 8.1.3) + activesupport (= 8.1.3) + 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) + rdoc (7.2.0) + erb + psych (>= 4.0.0) + tsort + regexp_parser (2.12.0) + reline (0.6.3) + io-console (~> 0.5) + rexml (3.4.4) + 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.87.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.49.1) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-performance (1.26.1) + lint_roller (~> 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.35.3) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + ruby-vips (2.3.0) + ffi (~> 1.12) + logger + rubyzip (3.2.2) + securerandom (0.4.1) + selenium-webdriver (4.43.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + solid_cable (4.0.0) + 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.4.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.4-aarch64-linux-gnu) + sqlite3 (2.9.4-aarch64-linux-musl) + sqlite3 (2.9.4-arm-linux-gnu) + sqlite3 (2.9.4-arm-linux-musl) + sqlite3 (2.9.4-arm64-darwin) + sqlite3 (2.9.4-x86_64-linux-gnu) + sqlite3 (2.9.4-x86_64-linux-musl) + sshkit (1.25.0) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.2.0) + sys-uname (1.5.1) + ffi (~> 1.1) + memoist3 (~> 1.0.0) + thor (1.5.0) + thruster (0.1.21) + thruster (0.1.21-aarch64-linux) + thruster (0.1.21-arm64-darwin) + thruster (0.1.21-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) + websocket (1.2.11) + websocket-driver (0.8.0) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.8.2) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin-24 + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bcrypt (~> 3.1.7) + bootsnap + brakeman + bundler-audit + capybara + cucumber-rails + database_cleaner + debug + image_processing (~> 1.2) + importmap-rails + jbuilder + kamal + propshaft + puma (>= 5.0) + rails (~> 8.1.3) + rspec-rails + rubocop-rails-omakase + selenium-webdriver + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + thruster + turbo-rails + tzinfo-data + web-console + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.3) sha256=e5bc7f75e44e6a22de29c4f43176927c3a9ce4824464b74ed18d8226e75a80f0 + actionmailbox (8.1.3) sha256=df7da474eaa0e70df4ed5a6fef66eb3b3b0f2dbf7f14518deee8d77f1b4aae59 + actionmailer (8.1.3) sha256=831f724891bb70d0aaa4d76581a6321124b6a752cb655c9346aae5479318448d + actionpack (8.1.3) sha256=af998cae4d47c5d581a2cc363b5c77eb718b7c4b45748d81b1887b25621c29a3 + actiontext (8.1.3) sha256=d291019c00e1ea9e6463011fa214f6081a56d7b9a1d224e7d3f6384c1dafc7d2 + actionview (8.1.3) sha256=1347c88c7f3edb38100c5ce0e9fb5e62d7755f3edc1b61cce2eb0b2c6ea2fd5d + activejob (8.1.3) sha256=a149b1766aa8204c3c3da7309e4becd40fcd5529c348cffbf6c9b16b565fe8d3 + activemodel (8.1.3) sha256=90c05cbe4cef3649b8f79f13016191ea94c4525ce4a5c0fb7ef909c4b91c8219 + activerecord (8.1.3) sha256=8003be7b2466ba0a2a670e603eeb0a61dd66058fccecfc49901e775260ac70ab + activestorage (8.1.3) sha256=0564ce9309143951a67615e1bb4e090ee54b8befed417133cae614479b46384d + activesupport (8.1.3) sha256=21a5e0dfbd4c3ddd9e1317ec6a4d782fa226e7867dc70b0743acda81a1dca20e + 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.24.5) sha256=36b677448524d279b470469aabd5dff4a980e3fa4931a0df68da4a500eb1b6c4 + brakeman (8.0.4) sha256=7bf921fa9638544835df9aa7b3e720a9a72c0267f34f92135955edd80d4dcf6f + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + bundler (4.0.12) sha256=7f8b757d28dfb636e7b24fba2344ac6dd13b5b24f4b46d62573d483f211825ac + bundler-audit (0.9.3) sha256=81c8766c71e47d0d28a0f98c7eed028539f21a6ea3cd8f685eb6f42333c9b4e9 + capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef + concurrent-ruby (1.3.6) sha256=6b56837e1e7e5292f9864f34b69c5a2cbc75c0cf5338f1ce9903d10fa762d5ab + connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a + crass (1.0.6) sha256=dc516022a56e7b3b156099abc81b6d2b08ea1ed12676ac7a5657617f012bd45d + cucumber (10.2.0) sha256=fdedbd31ecf40858b60f04853f2aa15c44f5c30bbac29c6a227fa1e7005a8158 + cucumber-ci-environment (11.0.0) sha256=0df79a9e1d0b015b3d9def680f989200d96fef206f4d19ccf86a338c4f71d1e2 + cucumber-core (16.2.0) sha256=592b58a95cf42feef8e5a349f68e363784ba3b6568ffbcf6776e38e136cf970b + cucumber-cucumber-expressions (19.0.1) sha256=648ec09045190d818fb797af46e1648148599fd67a086a34a7f0e647d9e36c8c + cucumber-gherkin (39.1.0) sha256=aed12a0c955d8563d80a012633c1a72075525f4d64d4cc983001df2181b379ed + cucumber-html-formatter (22.3.0) sha256=f9768ed05588dbd73a5f3824c2cc648bd86b00206e6972d743af8051281d0729 + cucumber-messages (32.3.1) sha256=ddc88e4c1cf7afb96c06005b92a4a6f221a2fa435a8b4ca04677d215fd82771c + cucumber-rails (4.0.1) sha256=bd3513ec47dc06188cc05703648cbc3560fb115f3f5cfb8b616065b4d6e8024d + cucumber-tag-expressions (8.1.0) sha256=9bd8c4b6654f8e5bf2a9c99329b6f32136a75e50cd39d4cfb3927d0fa9f52e21 + database_cleaner (2.1.0) sha256=1dcba26e3b1576da692fc6bac10136a4744da5bcc293d248aae19640c65d89cd + database_cleaner-active_record (2.2.2) sha256=88296b9f3088c31f7c0d4fcec10f68e4b71c96698043916de59b04debec10388 + database_cleaner-core (2.1.0) sha256=b2875266d9b26b716e8b669c883e01c5250839f6f2ec56422b5e79aa97fb6927 + 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.4) sha256=38e3803694be357fe2bfe312487c74beaf9fb4e5beb3e22498952fe1645b95d9 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + et-orbi (1.4.0) sha256=6c7e3c90779821f9e3b324c5e96fda9767f72995d6ae435b96678a4f3e2de8bc + 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-arm64-darwin) sha256=19071aaf1419251b0a46852abf960e77330a3b334d13a4ab51d58b31a937001b + ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d + ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e + fugit (1.12.2) sha256=643f2bf28db263bd400cbf8e0dd8b76b2c9b94bdb130e12d2394de04d9c20e5e + globalid (1.3.0) sha256=05c639ad6eb4594522a0b07983022f04aa7254626ab69445a0e493aa3786ff11 + i18n (1.14.8) sha256=285778639134865c5e0f6269e0b818256017e8cde89993fdfcbfb64d088824a5 + image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb + importmap-rails (2.2.3) sha256=7101be2a4dc97cf1558fb8f573a718404c5f6bcfe94f304bf1f39e444feeb16a + io-console (0.8.2) sha256=d6e3ae7a7cc7574f4b8893b4fca2162e57a825b223a177b7afa236c5ef9814cc + irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 + jbuilder (2.15.1) sha256=2430bec28fb0cebacb5875b1009cf9d8bc3c303ccb810c4c8b062a4b51457637 + json (2.19.7) sha256=fe432c8639f6efff69f9d73b518a3705d9581ab93156f981ea72806e1e5bcc3e + kamal (2.11.0) sha256=1408864425e0dec7e0a14d712a3b13f614e9f3a425b7661d3f9d287a51d7dd75 + language_server-protocol (3.17.0.5) sha256=fd1e39a51a28bf3eec959379985a72e296e9f9acfce46f6a79d31ca8760803cc + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.1) sha256=d436c73dbd0c1147b16c4a41db097942d217303e1f7728704b37e4df9f6d2e04 + mail (2.9.0) sha256=6fa6673ecd71c60c2d996260f9ee3dd387d4673b8169b502134659ece6d34941 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b + memoist3 (1.0.0) sha256=686e42402cf150a362050c23143dc57b0ef88f8c344943ff8b7845792b50d56f + mini_magick (5.3.1) sha256=29395dfd76badcabb6403ee5aff6f681e867074f8f28ce08d78661e9e4a351c4 + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + msgpack (1.8.1) sha256=3fef787cd3965fd119c08a22724a56a93ca25008c3421fc15039f603a8b7c86c + multi_test (1.1.0) sha256=e9e550cdd863fb72becfe344aefdcd4cbd26ebf307847f4a6c039a4082324d10 + net-imap (0.6.4) sha256=9a5598c67a3022c284d98430ef1d4948e7dbdb62596f61081ea8ca933270a02b + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.2.2) sha256=aa73e0cba6a125369de9837b8d8ef82a61849360eba0521900e2c3713aa162a8 + 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.2) sha256=65029e213c380e20e5fd92ece663934ab0a0fe888e0cd7cc6a5b664074362dd4 + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.3-aarch64-linux-gnu) sha256=46b89e5d7b9e844c2ee360794240c6ea2a4e6fa0c5892a4ed487db621224b639 + nokogiri (1.19.3-aarch64-linux-musl) sha256=8392dfdcd21be7a94dbbe9ccc138dea01b97b24cb2dc02a114ca98bfb1d9a0b7 + nokogiri (1.19.3-arm-linux-gnu) sha256=3919d5ffc334ad778a4a9eb88fda7dcb8b1fb58c8a52ac640c6dcd2f038e774f + nokogiri (1.19.3-arm-linux-musl) sha256=9ce1cb6346bb9c67b1550eb537aa183ead91e4b6eadb2f36ade02d8dd2a79fb6 + nokogiri (1.19.3-arm64-darwin) sha256=71b9bd424b1b7abc18b05052a1a3cfd3627abdca62be280854cc411791357e42 + nokogiri (1.19.3-x86_64-linux-gnu) sha256=2f5078620fe12e83669b5b17311b32532a8153d02eee7ad06948b926d6080976 + nokogiri (1.19.3-x86_64-linux-musl) sha256=248c906d2166eca5efb56d52fdee5f9a1f51d69a72e2b64fdac647b4ce39ea3f + ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 + parallel (2.1.0) sha256=b35258865c2e31134c5ecb708beaaf6772adf9d5efae28e93e99260877b09356 + parser (3.3.11.1) sha256=d17ace7aabe3e72c3cc94043714be27cc6f852f104d81aa284c2281aecc65d54 + pp (0.6.3) sha256=2951d514450b93ccfeb1df7d021cae0da16e0a7f95ee1e2273719669d0ab9df6 + prettyprint (0.2.0) sha256=2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e + psych (5.3.1) sha256=eb7a57cef10c9d70173ff74e739d843ac3b2c019a003de48447b2963d81b1974 + public_suffix (7.0.5) sha256=1a8bb08f1bbea19228d3bed6e5ed908d1cb4f7c2726d18bd9cadf60bc676f623 + puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb + raabro (1.4.0) sha256=d4fa9ff5172391edb92b242eed8be802d1934b1464061ae5e70d80962c5da882 + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.6) sha256=5ed78e1f73b2e25679bec7d45ee2d4483cc4146eb1be0264fc4d94cb5ef212c2 + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.3) sha256=6d017ba5348c98fc909753a8169b21d44de14d2a0b92d140d1a966834c3c9cd3 + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.0) sha256=28b145cceaf9cc214a9874feaa183c3acba036c9592b19886e0e45efc62b1e89 + railties (8.1.3) sha256=913eb0e0cb520aac687ffd74916bd726d48fa21f47833c6292576ef6a286de22 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rdoc (7.2.0) sha256=8650f76cd4009c3b54955eb5d7e3a075c60a57276766ebf36f9085e8c9f23192 + regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb + reline (0.6.3) sha256=1198b04973565b36ec0f11542ab3f5cfeeec34823f4e54cebde90968092b1835 + rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 + 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.87.0) sha256=b9d9ddf55116a513f8ef2c7ae660662d8b49301f118d3f0df61865b33a5c188d + rubocop-ast (1.49.1) sha256=4412f3ee70f6fe4546cc489548e0f6fcf76cafcfa80fa03af67098ffed755035 + rubocop-performance (1.26.1) sha256=cd19b936ff196df85829d264b522fd4f98b6c89ad271fa52744a8c11b8f71834 + rubocop-rails (2.35.3) sha256=6edd45410866912b9b2e90ae3aeafd31d576df2bb2a9c9408f1667a50c32c7de + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374 + rubyzip (3.2.2) sha256=c0ed99385f0625415c8f05bcae33fe649ed2952894a95ff8b08f26ca57ea5b3c + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + selenium-webdriver (4.43.0) sha256=a634377b964b701c6ac0a009ce3a08fa34ec1e1e7fe9a6d57e3088d14529a65c + solid_cable (4.0.0) sha256=8379680ef6bf36e195eb876a6306ea290f87d5fa10bc4a757bc2a918f83229b5 + solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 + solid_queue (1.4.0) sha256=e6a18d196f0b27cb6e3c77c5b31258b05fb634f8ed64fb1866ed164047216c2a + sqlite3 (2.9.4-aarch64-linux-gnu) sha256=ecabed721e6eaad54601d2685f09029d90025efc8d931040dc89cb3f8a2080ec + sqlite3 (2.9.4-aarch64-linux-musl) sha256=ffb4255947fb54c8c3eeca97460c9702b40de91ce390455ef7367ca6a3929a31 + sqlite3 (2.9.4-arm-linux-gnu) sha256=9ee2008b9fbec984c3c165b0d7eedd2bd2a415100b761bfa3a4c6fbec9208bf6 + sqlite3 (2.9.4-arm-linux-musl) sha256=8dc1fe4da6977992cd62decf4a93ccf6cc2e124a5e6a340160d52092f70e837a + sqlite3 (2.9.4-arm64-darwin) sha256=1d5aad413a815d236e96d43f05a1acc600b6cd086800770342a3f9c2877499ff + sqlite3 (2.9.4-x86_64-linux-gnu) sha256=537a3eda71b1df1336d0055cbebe55a7317c34870c192c7b6b9d8d0be6871847 + sqlite3 (2.9.4-x86_64-linux-musl) sha256=3fc5e865b4be9a85d998203ef8d0c0fdcb92f20acf34a254346ff8a19088efec + sshkit (1.25.0) sha256=c8c6543cdb60f91f1d277306d585dd11b6a064cb44eab0972827e4311ff96744 + stimulus-rails (1.3.4) sha256=765676ffa1f33af64ce026d26b48e8ffb2e0b94e0f50e9119e11d6107d67cb06 + stringio (3.2.0) sha256=c37cb2e58b4ffbd33fe5cd948c05934af997b36e0b6ca6fdf43afa234cf222e1 + sys-uname (1.5.1) sha256=784d7e6491b0393c25cbbe5ac38324ac7be9fda083a6094832648af669386d7b + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + thruster (0.1.21) sha256=dc67928f36e5894844579a95e45637a5091db7a7ea05468ee8c2c6eb0a3f77cf + thruster (0.1.21-aarch64-linux) sha256=f5aff78fb7a6431ed3d6ab4bde03a89c461e9a73981dbc97d6990d85c3db235c + thruster (0.1.21-arm64-darwin) sha256=bd8db9f57fae2cbb3fe08ebab49cb47fe49608122dac23daf0ce709adfb9bfc8 + thruster (0.1.21-x86_64-linux) sha256=6e2fbcf826540a72d3710ae4db072c2333287ac2ee57e7e52f35bc10900d74a7 + 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 + websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737 + websocket-driver (0.8.0) sha256=ed0dba4b943c22f17f9a734817e808bc84cdce6a7e22045f5315aa57676d4962 + websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 + xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e + zeitwerk (2.8.2) sha256=7212a61311083c604184b1ea2574b9aa05cd14f855a0841c06985cabe9181d12 + +BUNDLED WITH + 4.0.12 diff --git a/Rakefile b/Rakefile new file mode 100644 index 0000000000..9a5ea7383a --- /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/images/.keep b/app/assets/images/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 0000000000..8eb2570f83 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,82 @@ +.login-page { + min-height: 100vh; + background-color: #dddddd; + display: flex; + align-items: center; + justify-content: center; +} + +.login-card { + width: 760px; + height: 350px; + display: flex; + border-radius: 4px; + overflow: hidden; + background-color: #ffffff; +} + +.login-form-section { + width: 45%; + background-color: #ffffff; + padding: 70px 36px; + box-sizing: border-box; +} + +.login-form-section h1 { + text-align: center; + font-size: 18px; + font-weight: 400; + margin-bottom: 24px; +} + +.form-group { + margin-bottom: 14px; +} + +.form-group label { + display: block; + font-size: 13px; + margin-bottom: 6px; +} + +.form-group input { + width: 100%; + height: 34px; + border: 1px solid #d6d6d6; + border-radius: 5px; + padding: 0 10px; + box-sizing: border-box; +} + +.login-button { + width: 100%; + height: 34px; + border: none; + border-radius: 5px; + background-color: #28c45d; + color: #ffffff; + cursor: pointer; + margin-top: 4px; +} + +.login-error { + color: #c0392b; + font-size: 13px; + margin-top: 12px; + text-align: center; +} + +.login-welcome-section { + width: 55%; + background-color: #6f2477; + color: #ffffff; + display: flex; + align-items: center; + justify-content: center; +} + +.login-welcome-section h2 { + font-size: 36px; + line-height: 1.35; + text-align: center; +} \ No newline at end of file diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 0000000000..f9a9d7d489 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,19 @@ +class ApplicationController < ActionController::Base + allow_browser versions: :modern + + stale_when_importmap_changes + + helper_method :current_user, :admin? + + def current_user + @current_user ||= User.find_by(id: session[:user_id]) + end + + def admin? + current_user&.perfil == "Administrador" + end + + def require_login + redirect_to login_path unless current_user + end +end \ No newline at end of file diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/controllers/dashboards_controller.rb b/app/controllers/dashboards_controller.rb new file mode 100644 index 0000000000..5252f6b436 --- /dev/null +++ b/app/controllers/dashboards_controller.rb @@ -0,0 +1,9 @@ +class DashboardsController < ApplicationController + before_action :require_login + + def admin + end + + def discente + end +end \ No newline at end of file diff --git a/app/controllers/envio_formularios_controller.rb b/app/controllers/envio_formularios_controller.rb new file mode 100644 index 0000000000..0d0b04bde4 --- /dev/null +++ b/app/controllers/envio_formularios_controller.rb @@ -0,0 +1,91 @@ +# app/controllers/envio_formularios_controller.rb +class EnvioFormulariosController < ApplicationController + before_action :exigir_discente! + before_action :set_formulario + before_action :verificar_acesso_a_turma! + before_action :verificar_prazo! + before_action :verificar_nao_respondido!, only: [:new] + + # GET /envio_formularios/new?formulario_id=X + def new + @questoes = @formulario.questoes + .includes(questao_template: :opcao_questoes) + .order(:id) + end + + # POST /envio_formularios + def create + ActiveRecord::Base.transaction do + @envio = EnvioFormulario.new( + formulario: @formulario, + discente: discente_atual, + enviado_em: Time.current + ) + + unless @envio.save + # trata tentativa de resposta duplicada (constraint UNIQUE) + if @envio.errors[:formulario_id].any? + redirect_to minha_resposta_formulario_path(@formulario), + notice: "Você já respondeu este formulário." + return + end + raise ActiveRecord::Rollback + end + + questoes_ids = @formulario.questoes.pluck(:id) + respostas_params = params[:respostas] || {} + + # valida que todas as questões foram respondidas + questoes_nao_respondidas = questoes_ids.reject do |id| + respostas_params[id.to_s].present? + end + + if questoes_nao_respondidas.any? + @envio.destroy + @questoes = @formulario.questoes.includes(questao_template: :opcao_questoes).order(:id) + flash.now[:alert] = "Todas as questões são obrigatórias" + render :new, status: :unprocessable_entity + raise ActiveRecord::Rollback + end + + questoes_ids.each do |questao_id| + Resposta.create!( + envio_formulario: @envio, + questao_id: questao_id, + conteudo: respostas_params[questao_id.to_s] + ) + end + end + + redirect_to root_path, notice: "Formulário respondido com sucesso!" + end + + private + + def set_formulario + @formulario = Formulario.find_by(id: params[:formulario_id]) + unless @formulario + redirect_to formularios_path, alert: "Formulário não encontrado." and return + end + end + + def verificar_acesso_a_turma! + unless discente_atual.turmas.include?(@formulario.turma) + redirect_to formularios_path, alert: "Você não tem acesso a este formulário." and return + end + end + + def verificar_prazo! + if @formulario.fechado? + redirect_to formularios_path, + alert: "O prazo para responder este formulário já encerrou." and return + end + end + + def verificar_nao_respondido! + if discente_atual.ja_respondeu?(@formulario) + redirect_to minha_resposta_formulario_path(@formulario), + notice: "Você já respondeu este formulário." and return + end + end +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 0000000000..8665e5724f --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,28 @@ +class SessionsController < ApplicationController + def new + end + + def create + identifier = params[:identifier].to_s.strip + + user = User.find_by(email: identifier) || User.find_by(matricula: identifier) + + if user&.authenticate(params[:password]) + session[:user_id] = user.id + + if user.perfil == "Administrador" + redirect_to admin_dashboard_path + else + redirect_to discente_dashboard_path + end + else + flash.now[:alert] = "Usuário e/ou senha inválidos" + render :new, status: :unprocessable_entity + end + end + + def destroy + reset_session + redirect_to login_path + end +end \ No newline at end of file diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 0000000000..de6be7945c --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/helpers/dashboards_helper.rb b/app/helpers/dashboards_helper.rb new file mode 100644 index 0000000000..28cd48d0e0 --- /dev/null +++ b/app/helpers/dashboards_helper.rb @@ -0,0 +1,2 @@ +module DashboardsHelper +end diff --git a/app/helpers/sessions_helper.rb b/app/helpers/sessions_helper.rb new file mode 100644 index 0000000000..309f8b2eb3 --- /dev/null +++ b/app/helpers/sessions_helper.rb @@ -0,0 +1,2 @@ +module SessionsHelper +end diff --git a/app/javascript/application.js b/app/javascript/application.js new file mode 100644 index 0000000000..0d7b49404c --- /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 0000000000..1213e85c7a --- /dev/null +++ b/app/javascript/controllers/application.js @@ -0,0 +1,9 @@ +import { Application } from "@hotwired/stimulus" + +const application = Application.start() + +// Configure Stimulus development experience +application.debug = false +window.Stimulus = application + +export { application } diff --git a/app/javascript/controllers/hello_controller.js b/app/javascript/controllers/hello_controller.js new file mode 100644 index 0000000000..5975c0789d --- /dev/null +++ b/app/javascript/controllers/hello_controller.js @@ -0,0 +1,7 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + connect() { + this.element.textContent = "Hello World!" + } +} diff --git a/app/javascript/controllers/index.js b/app/javascript/controllers/index.js new file mode 100644 index 0000000000..1156bf8362 --- /dev/null +++ b/app/javascript/controllers/index.js @@ -0,0 +1,4 @@ +// Import and register all your controllers from the importmap via controllers/**/*_controller +import { application } from "controllers/application" +import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading" +eagerLoadControllersFrom("controllers", application) diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 0000000000..d394c3d106 --- /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/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 0000000000..3c34c8148f --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 0000000000..b63caeb8a5 --- /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 0000000000..e69de29bb2 diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 0000000000..c5a19cf05b --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,8 @@ +class User < ApplicationRecord + has_secure_password + + validates :nome, presence: true + validates :email, presence: true, uniqueness: true + validates :matricula, presence: true, uniqueness: true + validates :perfil, presence: true +end \ No newline at end of file diff --git a/app/views/dashboards/admin.html.erb b/app/views/dashboards/admin.html.erb new file mode 100644 index 0000000000..e587db56c8 --- /dev/null +++ b/app/views/dashboards/admin.html.erb @@ -0,0 +1,17 @@ +
+ + +
+

Perfil de Administrador

+

Bem-vindo ao painel do administrador.

+
+
\ No newline at end of file diff --git a/app/views/dashboards/discente.html.erb b/app/views/dashboards/discente.html.erb new file mode 100644 index 0000000000..c5c0a0720a --- /dev/null +++ b/app/views/dashboards/discente.html.erb @@ -0,0 +1,17 @@ +
+ + +
+

Perfil de Discente

+

Bem-vindo à área do discente.

+
+
\ No newline at end of file diff --git a/app/views/envio_formularios/new.html.erb b/app/views/envio_formularios/new.html.erb new file mode 100644 index 0000000000..30059f54f9 --- /dev/null +++ b/app/views/envio_formularios/new.html.erb @@ -0,0 +1,309 @@ +<% content_for :title, "Responder · #{@formulario.titulo}" %> + + + + + +
+

<%= @formulario.titulo %>

+
+ 📚 <%= @formulario.turma.disciplina.nome %> · Turma <%= @formulario.turma.codigo %> + <% if @formulario.prazo %> + <% dias = (@formulario.prazo.to_date - Date.today).to_i %> + ⏱ Prazo: <%= @formulario.prazo.strftime("%d/%m/%Y às %H:%M") %> + <% if dias == 0 %> · Hoje! + <% elsif dias == 1 %> · Amanhã + <% elsif dias > 0 %> · <%= dias %> dias + <% end %> + + <% end %> +
+
+ +
+ ⚠️ Todas as questões são obrigatórias. Não será possível enviar com campos em branco. +
+ +
+ +<%= form_with url: envio_formularios_path, method: :post, id: "form-resposta" do |f| %> + <%= f.hidden_field :formulario_id, value: @formulario.id %> + + <% @questoes.each_with_index do |questao, i| %> +
+
+
<%= i + 1 %>
+
+
<%= questao.enunciado %>
+ + <%= questao.aberta? ? "✏️ Resposta aberta" : "☑️ Múltipla escolha" %> + +
+
+ +
+ <% if questao.aberta? %> + + + <% else %> +
+ <% questao.opcao_questoes.each do |opcao| %> + + <% end %> +
+ <% end %> +
+
+ <% end %> + +
+
+ 0 de <%= @questoes.count %> questões respondidas +
+
+ <%= link_to "← Voltar", formulario_path(@formulario), class: "btn btn-secondary" %> + <%= f.submit "Enviar Respostas", class: "btn btn-primary", id: "btn-enviar" %> +
+
+<% end %> + + diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 0000000000..9e51e3817f --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,29 @@ + + + + <%= content_for(:title) || "Camaar" %> + + + + + <%= 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 %> + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000000..3aac9002ed --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000000..37f0bddbd7 --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 0000000000..fca522bbe4 --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "Camaar", + "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": "Camaar.", + "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 0000000000..b3a13fb7bb --- /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/sessions/new.html.erb b/app/views/sessions/new.html.erb new file mode 100644 index 0000000000..1cf45a7aa1 --- /dev/null +++ b/app/views/sessions/new.html.erb @@ -0,0 +1,29 @@ +
+ +
\ No newline at end of file diff --git a/bin/brakeman b/bin/brakeman new file mode 100755 index 0000000000..ace1c9ba08 --- /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 0000000000..e2ef22690c --- /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 0000000000..4137ad5bb0 --- /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/cucumber b/bin/cucumber new file mode 100755 index 0000000000..eb5e962e86 --- /dev/null +++ b/bin/cucumber @@ -0,0 +1,11 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +vendored_cucumber_bin = Dir["#{File.dirname(__FILE__)}/../vendor/{gems,plugins}/cucumber*/bin/cucumber"].first +if vendored_cucumber_bin + load File.expand_path(vendored_cucumber_bin) +else + require 'rubygems' unless ENV['NO_RUBYGEMS'] + require 'cucumber' + load Cucumber::BINARY +end diff --git a/bin/dev b/bin/dev new file mode 100755 index 0000000000..5f91c20545 --- /dev/null +++ b/bin/dev @@ -0,0 +1,2 @@ +#!/usr/bin/env ruby +exec "./bin/rails", "server", *ARGV diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 0000000000..ed31659f40 --- /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 0000000000..36502ab16c --- /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 0000000000..dcf59f309a --- /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 0000000000..d9ba276702 --- /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 0000000000..efc0377492 --- /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 0000000000..4fbf10b960 --- /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 0000000000..5a20504716 --- /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 0000000000..81be011e87 --- /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 0000000000..36bde2d832 --- /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 0000000000..4a3c09a688 --- /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 0000000000..6fc486721d --- /dev/null +++ b/config/application.rb @@ -0,0 +1,42 @@ +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 Camaar + 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") + + # 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 0000000000..988a5ddc46 --- /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 0000000000..e74b3af949 --- /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 0000000000..b9adc5aa3a --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,17 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 0000000000..19d490843b --- /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 0000000000..239b343986 --- /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/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 0000000000..d65669b312 --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +Hlze+fjWrATU90vYzEKI8rYl9cpgK3z4DMWBytoO9oJcXJoaGUBCsbttzz5qdcTt6z3Exn0daGtjcOPuKvCj1ecMyTlvHbASoq2soV4Uh2B8WmkIyZmS2+Vd2rNVBCiG+VjNSh9GrdfwHytvV451vzguLW+od6loxMvyNv8lqCMkOmeD60BxgWtaCIa7el0Lv5E6eVf/IMW+P06PMhch9V3rgmzADmSY3msbpcdTJnqGBJuWUmYYKRjjej3uwFxWyA3azL6Iv8SWVnm62vDPiNzT8n2zZy/Kzi9wwrBSemM8+IhIyBXDvGXUxKxmDFueVpto36qJ4ByKy+uT7hh+vQ4x8LcRiDwc6hGDp9hST99NIe0tAw3e8nsYgnlS394j5UteZw3hI5fJf4RVJiD11ywfQzYuZKp4h1kq/7IPwpNYWf8pxU5SFBZ6uxmcbIOhdKjKqFSEGoCuJW7brnBlDwtNdEuiK8KewSRQAWPoJCoWN2YuQIWfPpgV--0WMCoRMo8vE9kZmG--M0634iZQ9+USW0msapdTGQ== \ No newline at end of file diff --git a/config/cucumber.yml b/config/cucumber.yml new file mode 100644 index 0000000000..47a4663ae2 --- /dev/null +++ b/config/cucumber.yml @@ -0,0 +1,8 @@ +<% +rerun = File.file?('rerun.txt') ? IO.read('rerun.txt') : "" +rerun = rerun.strip.gsub /\s/, ' ' +rerun_opts = rerun.empty? ? "--format #{ENV['CUCUMBER_FORMAT'] || 'progress'} features" : "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} #{rerun}" +std_opts = "--format #{ENV['CUCUMBER_FORMAT'] || 'pretty'} --strict --tags 'not @wip'" +%> +default: <%= std_opts %> features +rerun: <%= rerun_opts %> --format rerun --out rerun.txt --strict --tags 'not @wip' diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 0000000000..302d638c96 --- /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.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 0000000000..097f34d22d --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,119 @@ +# Name of your application. Used to uniquely configure containers. +service: camaar + +# Name of the container image (use your-user/app-name on external registries). +image: camaar + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# 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. +registry: + # Alternatives: hub.docker.com / registry.digitalocean.com / ghcr.io / ... + server: localhost:5555 + + # Needed for authenticated registries. + # username: your-user + + # Always use an access token rather than real password when possible. + # password: + # - KAMAL_REGISTRY_PASSWORD + +# Inject ENV variables into containers (secrets come from .kamal/secrets). +env: + secret: + - RAILS_MASTER_KEY + clear: + # Run the Solid Queue Supervisor inside the web server's Puma process to do jobs. + # When you start using multiple servers, you should split out job processing to a dedicated machine. + SOLID_QUEUE_IN_PUMA: true + + # Set number of processes dedicated to Solid Queue (default: 1) + # JOB_CONCURRENCY: 3 + + # Set number of cores available to the application on each server (default: 1). + # WEB_CONCURRENCY: 2 + + # Match this to any external database server to configure Active Record correctly + # Use camaar-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: + - "camaar_storage:/rails/storage" + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: 3.4.6 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +# accessories: +# db: +# image: mysql:8.0 +# host: 192.168.0.2 +# # Change to 3306 to expose port to the world instead of just local network. +# port: "127.0.0.1:3306:3306" +# env: +# clear: +# MYSQL_ROOT_HOST: '%' +# secret: +# - MYSQL_ROOT_PASSWORD +# files: +# - config/mysql/production.cnf:/etc/mysql/my.cnf +# - db/production.sql:/docker-entrypoint-initdb.d/setup.sql +# directories: +# - data:/var/lib/mysql +# redis: +# image: 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 0000000000..cac5315775 --- /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 0000000000..7d1b179ef2 --- /dev/null +++ b/config/environments/development.rb @@ -0,0 +1,82 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Configure 'rails notes' to inspect Cucumber files + config.annotations.register_directories('features') + config.annotations.register_extensions('feature') { |tag| /#\s*(#{tag}):?\s*(.*)$/ } + + # Settings specified here will take precedence over those in config/application.rb. + + # Make code changes take effect immediately without server restart. + config.enable_reloading = true + + # Do not eager load code on boot. + config.eager_load = false + + # Show full error reports. + config.consider_all_requests_local = true + + # Enable server timing. + config.server_timing = true + + # Enable/disable Action Controller caching. By default Action Controller caching is disabled. + # Run rails dev:cache to toggle Action Controller caching. + if Rails.root.join("tmp/caching-dev.txt").exist? + config.action_controller.perform_caching = true + config.action_controller.enable_fragment_cache_logging = true + config.public_file_server.headers = { "cache-control" => "public, max-age=#{2.days.to_i}" } + else + config.action_controller.perform_caching = false + end + + # Change to :null_store to avoid any caching. + config.cache_store = :memory_store + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Don't care if the mailer can't send. + config.action_mailer.raise_delivery_errors = false + + # Make template changes take effect immediately. + config.action_mailer.perform_caching = false + + # Set localhost to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "localhost", port: 3000 } + + # Print deprecation notices to the Rails logger. + config.active_support.deprecation = :log + + # Raise an error on page load if there are pending migrations. + config.active_record.migration_error = :page_load + + # Highlight code that triggered database queries in logs. + config.active_record.verbose_query_logs = true + + # Append comments with runtime information tags to SQL queries in logs. + config.active_record.query_log_tags_enabled = true + + # Highlight code that enqueued background job in logs. + config.active_job.verbose_enqueue_logs = true + + # 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 0000000000..f5763e04e5 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,90 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy. + # config.assume_ssl = true + + # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. + # config.force_ssl = true + + # Skip http-to-https redirect for the default health check endpoint. + # config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + + # Log to STDOUT with the current request id as a default log tag. + config.log_tags = [ :request_id ] + config.logger = ActiveSupport::TaggedLogging.logger(STDOUT) + + # Change to "debug" to log everything (including potentially personally-identifiable information!). + config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") + + # Prevent health checks from clogging up the logs. + config.silence_healthcheck_path = "/up" + + # Don't log any deprecations. + config.active_support.report_deprecations = false + + # Replace the default in-process memory cache store with a durable alternative. + config.cache_store = :solid_cache_store + + # Replace the default in-process and non-durable queuing backend for Active Job. + config.active_job.queue_adapter = :solid_queue + config.solid_queue.connects_to = { database: { writing: :queue } } + + # Ignore bad email addresses and do not raise email delivery errors. + # Set this to true and configure the email server for immediate delivery to raise delivery errors. + # config.action_mailer.raise_delivery_errors = false + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Specify outgoing SMTP server. Remember to add smtp/* credentials via 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 0000000000..e6b5c1b020 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,57 @@ +# 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 + # Configure 'rails notes' to inspect Cucumber files + config.annotations.register_directories('features') + config.annotations.register_extensions('feature') { |tag| /#\s*(#{tag}):?\s*(.*)$/ } + + # 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 0000000000..909dfc542d --- /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 0000000000..487324424f --- /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 0000000000..d51d713979 --- /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 0000000000..c0b717f7ec --- /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 0000000000..3860f659ea --- /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 0000000000..6c349ae5e3 --- /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/puma.rb b/config/puma.rb new file mode 100644 index 0000000000..38c4b86596 --- /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 0000000000..9eace59c41 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 0.1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 0000000000..b4207f9b07 --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,15 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 0000000000..ed6cd2ed4e --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,21 @@ +# config/routes.rb +Rails.application.routes.draw do + get "/login", to: "sessoes#new", as: :login + post "/login", to: "sessoes#create" + delete "/logout", to: "sessoes#destroy", as: :logout + + get "/usuarios/mudar-senha", to: "usuarios#mudar_senha", as: :mudar_senha + patch "/usuarios/mudar-senha", to: "usuarios#atualizar_senha" + + # Issue #8 — listar e visualizar formulários (discente) + resources :formularios, only: [:index, :show] do + member do + get :minha_resposta + end + end + + # Issue #18 — responder formulário (discente) + resources :envio_formularios, only: [:new, :create] + + root to: "dashboard#index" +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 0000000000..927dc537c8 --- /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 0000000000..23666604a5 --- /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 0000000000..81a410d188 --- /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/20260604024535_create_users.rb b/db/migrate/20260604024535_create_users.rb new file mode 100644 index 0000000000..4e7c9f75de --- /dev/null +++ b/db/migrate/20260604024535_create_users.rb @@ -0,0 +1,16 @@ +class CreateUsers < ActiveRecord::Migration[8.1] + def change + create_table :users do |t| + t.string :nome, null: false + t.string :email, null: false + t.string :matricula, null: false + t.string :perfil, null: false + t.string :password_digest, null: false + + t.timestamps + end + + add_index :users, :email, unique: true + add_index :users, :matricula, unique: true + end +end \ No newline at end of file diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 0000000000..85194b6a88 --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,129 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 0000000000..cb5f04ad4b --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,25 @@ +# 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_06_04_024535) do + create_table "users", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "email", null: false + t.string "matricula", null: false + t.string "nome", null: false + t.string "password_digest", null: false + t.string "perfil", null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", unique: true + t.index ["matricula"], name: "index_users_on_matricula", unique: true + end +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 0000000000..280a5c7c7a --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,15 @@ +User.find_or_create_by!(email: "discente@camaar.com") do |user| + user.nome = "Discente Teste" + user.matricula = "202400001" + user.perfil = "Discente" + user.password = "123456" + user.password_confirmation = "123456" +end + +User.find_or_create_by!(email: "admin@camaar.com") do |user| + user.nome = "Administrador Teste" + user.matricula = "000000001" + user.perfil = "Administrador" + user.password = "123456" + user.password_confirmation = "123456" +end \ No newline at end of file diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 0000000000..6d69548479 --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,82 @@ +# Setup do ambiente — CAMAAR + +## Pré-requisitos + +- Ruby 3.4.6 +- Google Chrome instalado +- SQLite3 + +--- + +## 1. Clonar o repositório + +```bash +git clone +cd CAMAAR +``` + +--- + +## 2. Instalar as gems + +```bash +bundle install +``` + +--- + +## 3. Configurar o banco de dados + +```bash +bin/rails db:prepare +bin/rails db:test:prepare +``` + +--- + +## 4. Verificar a instalação + +```bash +bundle exec cucumber --dry-run +``` + +Saída esperada (antes de implementar os steps): + +``` +71 scenarios (71 undefined) +404 steps (404 undefined) +``` + +Nenhum erro de configuração = ambiente pronto. + +--- + +## Rodando os testes + +```bash +# Todos os cenários +bundle exec cucumber + +# Um arquivo específico +bundle exec cucumber features/sistema_login.feature + +# Um cenário pela linha +bundle exec cucumber features/sistema_login.feature:10 + +# Por tag +bundle exec cucumber --tags @Issue-9 +``` + +--- + +## Problemas comuns + +**`FATAL: database does not exist`** +```bash +bin/rails db:test:prepare +``` + +**ChromeDriver incompatível com o Chrome instalado** +```bash +bundle update selenium-webdriver +``` diff --git a/features/atualizar_bd_SIGAA.feature b/features/atualizar_bd_SIGAA.feature new file mode 100644 index 0000000000..d2c3a8be29 --- /dev/null +++ b/features/atualizar_bd_SIGAA.feature @@ -0,0 +1,21 @@ +# language: pt + +#Issue-9 + +Funcionalidade: Atualizar base de dados com os dados do SIGAA + Como administrador acadêmico + Quero atualizar os dados já cadastrados + A fim de manter a base sincronizada com o SIGAA + + Cenário: Caminho feliz + Dado que existem novos dados disponíveis no arquivo JSON + E a base local possui registros antigos + Quando o administrador solicitar a atualização + Então os registros devem ser sincronizados + E a base local deve refletir os novos dados + + Cenário: Caminho triste + Dado que ocorreu falha na leitura do JSON + Quando o administrador solicitar a atualização + Então o sistema deve informar falha na sincronização + E a base local deve permanecer inalterada diff --git a/features/cadastrar_usuarios.feature b/features/cadastrar_usuarios.feature new file mode 100644 index 0000000000..e0bc328042 --- /dev/null +++ b/features/cadastrar_usuarios.feature @@ -0,0 +1,47 @@ +# language: pt + +@Issue-17 + +Funcionalidade: Cadastrar usuários do sistema + Eu como Administrador + Quero cadastrar participantes de turmas do SIGAA ao importar dados de usuários novos para o sistema + A fim de que eles acessem o sistema CAMAAR + + Cenário: [Feliz] Cadastrar usuário com dados válidos + Dado que eu estou logado no sistema com o perfil de "administrador" + E que eu acesso a opção de "Gerenciamento" no menu lateral + Quando eu clico em "Importar Usuários" + E seleciono um arquivo JSON contendo os dados de novos usuários do SIGAA + E os dados estão válidos no arquivo importado + Então o sistema deve processar o arquivo e criar solicitações de definição de senha para cada usuário novo + E os usuários devem receber um e-mail com um link para definir suas senhas + + Cenário: [Feliz] Usuário permanece pendente enquanto não define a senha + Dado que um usuário foi cadastrado com sucesso no sistema e recebeu um e-mail para definir a senha + E o usuário ainda não definiu sua senha + Então o sistema deve manter o status do usuário como "pendente" + E o usuário não deve ter acesso ao sistema até que a senha seja definida + + Cenário: [Feliz] Usuário define a senha e é ativado + Dado que um usuário foi cadastrado com sucesso no sistema e recebeu um e-mail para definir a senha + E o usuário definiu sua senha + Então o sistema deve atualizar o status do usuário para "ativo" + E o usuário deve conseguir acessar o sistema com suas credenciais + + Cenário: [Triste] Tentar cadastrar usuário com dados inválidos + Dado que estou logado no sistema com o perfil de "administrador" + E que eu acesso a opção de "Gerenciamento" no menu lateral + Quando eu clico em "Importar Usuários" + E seleciono um arquivo JSON contendo os dados de novos usuários + E os dados estão inválidos no arquivo importado + Então o sistema deve exibir uma mensagem de erro "Erro: Dados inválidos" + E o sistema não deve criar solicitações de definição de senha para os usuários + + Cenário: [Triste] Tentar cadastrar usuário já existente + Dado que estou logado no sistema com o perfil de "administrador" + E que eu acesso a opção de "Gerenciamento" no menu lateral + Quando eu clico em "Importar Usuários" + E seleciono um arquivo JSON contendo os dados de novos usuários + E os dados estão válidos mas correspondem a usuários já existentes no sistema + Então o sistema deve exibir uma mensagem de aviso "Aviso: Usuário já existe" + E o sistema não deve criar solicitações de definição de senha para os usuários duplicados \ No newline at end of file diff --git a/features/criar_formulario_avaliacao.feature b/features/criar_formulario_avaliacao.feature new file mode 100644 index 0000000000..768c9f05c5 --- /dev/null +++ b/features/criar_formulario_avaliacao.feature @@ -0,0 +1,52 @@ +# language: pt + +#Issue-14 + +Funcionalidade: Criar formulário de avaliação + Como administrador + Quero criar um formulário de avaliação a partir de um template + A fim de enviá-lo para as turmas do meu departamento responderem + + Contexto: + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de criação de formulários de avaliação + + Cenário: [Feliz] Criar um formulário de avaliação com template e turma selecionados + Dado o template "Avaliação Docente 2024.1" está cadastrado no sistema + E a turma "CIC0097 - BANCOS DE DADOS" pertence ao meu departamento + E o formulário possui um público-alvo definido + Quando crio um formulário com o template "Avaliação Docente 2024.1" para a turma "CIC0097 - BANCOS DE DADOS" + Então o formulário deve ser criado com sucesso + E deve estar vinculado à turma "CIC0097 - BANCOS DE DADOS" + E deve conter as questões do template "Avaliação Docente 2024.1" + + Cenário: [Feliz] Criar um formulário de avaliação vinculado a múltiplas turmas + Dado o template "Avaliação Semestral" está cadastrado no sistema + E as turmas "CIC0097 - BANCOS DE DADOS", "CIC0105 - ENGENHARIA DE SOFTWARE" e "CIC0202 - PROGRAMAÇÃO CONCORRENTE" pertencem ao meu departamento + E o formulário possui um público-alvo definido + Quando crio um formulário com o template "Avaliação Semestral" para as turmas "CIC0097 - BANCOS DE DADOS", "CIC0105 - ENGENHARIA DE SOFTWARE" e "CIC0202 - PROGRAMAÇÃO CONCORRENTE" + Então o formulário deve ser criado com sucesso + E deve estar vinculado às turmas "CIC0097 - BANCOS DE DADOS", "CIC0105 - ENGENHARIA DE SOFTWARE" e "CIC0202 - PROGRAMAÇÃO CONCORRENTE" + E deve conter as questões do template "Avaliação Semestral" + + Cenário: [Triste] Tentar criar um formulário sem selecionar um template + Dado a turma "CIC0097 - BANCOS DE DADOS" pertence ao meu departamento + Quando crio um formulário sem template para a turma "CIC0097 - BANCOS DE DADOS" + Então o sistema deve exibir a mensagem de erro "Selecione um template para criar o formulário" + + Cenário: [Triste] Tentar criar um formulário sem selecionar nenhuma turma + Dado o template "Avaliação Docente 2024.1" está cadastrado no sistema + Quando crio um formulário com o template "Avaliação Docente 2024.1" sem turma + Então o sistema deve exibir a mensagem de erro "Selecione ao menos uma turma para criar o formulário" + + Cenário: [Triste] Administrador tenta selecionar uma turma de outro departamento + Dado o template "Avaliação Docente 2024.1" está cadastrado no sistema + E a turma "MAT0026 - CÁLCULO 1" não pertence ao meu departamento + Quando tento selecionar a turma "MAT0026 - CÁLCULO 1" no formulário + Então a turma "MAT0026 - CÁLCULO 1" não deve estar disponível para seleção + + Cenário: [Triste] Participante tenta acessar a página de criação de formulários + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + Quando eu tento acessar a página de criação de formulários de avaliação + Então o sistema deve exibir a mensagem "Você não tem permissão para acessar esta página" + E eu devo ser redirecionado para a página inicial do meu perfil diff --git a/features/criar_formulario_docentes_discentes.feature b/features/criar_formulario_docentes_discentes.feature new file mode 100644 index 0000000000..8b8b1cfe2d --- /dev/null +++ b/features/criar_formulario_docentes_discentes.feature @@ -0,0 +1,56 @@ +# language: pt + +#Issue-4 + +Funcionalidade: Criar formulário para docentes ou discentes + Como administrador + Quero definir o público-alvo de um formulário de avaliação + A fim de garantir que apenas os participantes corretos visualizem e respondam o formulário + + + Cenário: [Feliz] Criar formulário com público-alvo definido como discentes + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um template de formulário cadastrado no sistema + E existe uma turma do meu departamento disponível para seleção + Quando crio um formulário com o template selecionado para a turma com público-alvo "Discentes" + Então o formulário deve ser criado com sucesso + E o acesso deve estar restrito ao público-alvo "Discentes" + + Cenário: [Feliz] Criar formulário com público-alvo definido como docentes + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um template de formulário cadastrado no sistema + E existe uma turma do meu departamento disponível para seleção + Quando crio um formulário com o template selecionado para a turma com público-alvo "Docentes" + Então o formulário deve ser criado com sucesso + E o acesso deve estar restrito ao público-alvo "Docentes" + + Cenário: [Feliz] Discente visualiza formulário destinado a discentes + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E existe um formulário destinado a "Discentes" para a turma "CIC0097 - BANCOS DE DADOS" + E eu estou matriculado na turma "CIC0097 - BANCOS DE DADOS" + Quando eu acesso a lista de formulários disponíveis + Então devo ver o formulário da turma "CIC0097 - BANCOS DE DADOS" na lista + + Cenário: [Triste] Discente não visualiza formulário destinado apenas a docentes + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E que existe um formulário destinado a "Docentes" para a turma "CIC0097 - BANCOS DE DADOS" + E eu estou matriculado na turma "CIC0097 - BANCOS DE DADOS" + Quando eu acesso a lista de formulários disponíveis + Então não devo ver o formulário da turma "CIC0097 - BANCOS DE DADOS" na lista + + Cenário: [Triste] Docente não visualiza formulário destinado apenas a discentes + Dado que eu estou logado no sistema CAMAAR com o perfil de "docente" da turma "CIC0097 - BANCOS DE DADOS" + E que existe um formulário destinado a "Discentes" para a turma "CIC0097 - BANCOS DE DADOS" + Quando eu acesso a lista de formulários disponíveis + Então não devo ver o formulário da turma "CIC0097 - BANCOS DE DADOS" na lista + + Cenário: [Triste] Tentar criar um formulário sem definir o público-alvo + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + Quando crio um formulário com o template selecionado para a turma sem público-alvo + Então o sistema deve exibir a mensagem de erro "Defina o público-alvo do formulário" + + Cenário: [Feliz] Formulário permanece associado à turma após definição do público-alvo + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + Quando crio um formulário com o template selecionado para a turma "CIC0097 - BANCOS DE DADOS" com público-alvo "Discentes" + Então o formulário deve ser criado com sucesso + E deve permanecer vinculado à turma "CIC0097 - BANCOS DE DADOS" diff --git a/features/criar_template_formulario.feature b/features/criar_template_formulario.feature new file mode 100644 index 0000000000..502e74325d --- /dev/null +++ b/features/criar_template_formulario.feature @@ -0,0 +1,64 @@ +# language: pt + +#Issue-15 + +Funcionalidade: Criar template de formulários + Como administrador + Quero criar um novo template de formulário + A fim de utilizar este template para criar novos formulários + + Cenário: [Feliz] Criar um novo template com questão do tipo Texto e questão do tipo Radio + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + Quando seleciono a opção de criar um novo template + E preencho o campo "Nome do template" com "Avaliação Docente 2024.1" + E adiciono uma questão do tipo "Texto" com o enunciado "Deixe seu comentário sobre a disciplina" + E adiciono uma questão do tipo "Radio" com o enunciado "Como você avalia o docente?" e as opções "Ótimo", "Bom" e "Regular" + E clico no botão "Criar" + Então o template "Avaliação Docente 2024.1" deve aparecer na listagem de templates + E deve estar disponível para uso em novos formulários + + Cenário: [Triste] Tentar criar um template sem preencher o nome + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + Quando seleciono a opção de criar um novo template + E deixo o campo "Nome do template" em branco + E adiciono uma questão do tipo "Texto" com o enunciado "Comentários gerais" + E clico no botão "Criar" + Então o sistema deve exibir a mensagem de erro "O nome do template é obrigatório" + E o template não deve ser salvo + + Cenário: [Triste] Tentar criar um template sem adicionar nenhuma questão + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + Quando seleciono a opção de criar um novo template + E preencho o campo "Nome do template" com "Template Vazio" + E clico no botão "Criar" sem adicionar nenhuma questão + Então o sistema deve exibir a mensagem de erro "O template deve conter ao menos uma questão" + E o template não deve ser salvo + + Cenário: [Triste] Tentar criar uma questão do tipo Radio sem adicionar opções de resposta + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + Quando seleciono a opção de criar um novo template + E preencho o campo "Nome do template" com "Avaliação Semestral" + E adiciono uma questão do tipo "Radio" com o enunciado "Como você avalia a disciplina?" sem opções de resposta + E clico no botão "Criar" + Então o sistema deve exibir a mensagem de erro "Questões do tipo Radio devem ter ao menos uma opção de resposta" + E o template não deve ser salvo + + Cenário: [Triste] Tentar criar uma questão com enunciado vazio + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + Quando seleciono a opção de criar um novo template + E preencho o campo "Nome do template" com "Avaliação de Turma" + E adiciono uma questão do tipo "Texto" com o enunciado em branco + E clico no botão "Criar" + Então o sistema deve exibir a mensagem de erro "O enunciado da questão é obrigatório" + E o template não deve ser salvo + + Cenário: [Triste] Participante tenta acessar a página de gerenciamento de templates + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E eu acesso a página de gerenciamento de templates + Então o sistema deve exibir a mensagem "Você não tem permissão para acessar esta página" + E eu devo ser redirecionado para a página inicial do meu perfil diff --git a/features/definicao_senha.feature b/features/definicao_senha.feature new file mode 100644 index 0000000000..a3e3228bb8 --- /dev/null +++ b/features/definicao_senha.feature @@ -0,0 +1,37 @@ +# language: pt + +@Issue-12 + +Funcionalidade: Sistema de definição de senha + Eu como Usuário + Quero definir uma senha para o meu usuário a partir do e-mail do sistema de solicitação de cadastro + A fim de acessar o sistema + + Cenário: [Feliz] Definir senha com link válido + Dado que recebo um e-mail com um link de definição de senha válido + Quando eu acesso o link e preencho o campo "Nova Senha" com uma senha válida + E preencho o campo "Confirmar Senha" com a mesma senha informada no campo "Nova Senha" + E clico em "Salvar" + Então a senha deve ser definida com sucesso + E eu devo conseguir acessar o sistema utilizando a nova senha + + Cenário: [Triste] Tentar definir senha com link inválido + Dado que recebo um e-mail com um link de definição de senha inválido ou expirado + Quando eu tento acessar o link para definir minha senha + Então devo ver uma mensagem "Link de definição de senha inválido ou expirado" + E eu não devo conseguir definir minha senha + + Cenário: [Triste] Tentar definir senha com campos vazios + Dado que recebo um e-mail com um link de definição de senha válido + Quando eu acesso o link e não preencho os campos de senha + E clico em "Salvar" + Então devo ver a mensagem "Senha inválida" + E eu não devo conseguir acessar o sistema + + Cenário: [Triste] Tentar definir senhas que não correspondem + Dado que recebo um e-mail com um link de definição de senha válido + Quando eu acesso o link e preencho com senhas que não correspondem + E clico em "Salvar" + Então devo ver a mensagem "Senha inválida" + E eu não devo conseguir acessar o sistema + diff --git a/features/edit_delete_template.feature b/features/edit_delete_template.feature new file mode 100644 index 0000000000..fa77c207c4 --- /dev/null +++ b/features/edit_delete_template.feature @@ -0,0 +1,107 @@ +# language: pt + +#Issue-5 + +Funcionalidade: Edição e deleção de templates + Como administrador + Quero editar e deletar templates de formulário existentes + A fim de manter os templates atualizados e remover os que não são mais necessários + + Cenário: [Feliz] Editar o nome de um template existente com sucesso + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Docente 2024.1" + E altero o campo "Nome do template" para "Avaliação Docente 2024.2" + E clico no botão "Confirmar" + Então o template "Avaliação Docente 2024.2" deve aparecer na listagem de templates + E o template "Avaliação Docente 2024.1" não deve aparecer na listagem de templates + + Cenário: [Feliz] Editar o enunciado de uma questão existente com sucesso + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Semestral" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Semestral" + E altero o enunciado da questão "Como você avalia o docente?" para "Como você avalia a atuação do docente na disciplina?" + E clico no botão "Confirmar" + Então a questão "Como você avalia a atuação do docente na disciplina?" deve aparecer no template "Avaliação Semestral" + + Cenário: [Feliz] Adicionar uma nova questão a um template existente com sucesso + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Semestral" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Semestral" + E adiciono uma questão do tipo "Texto" com o enunciado "Sugestões de melhoria para o semestre" + E clico no botão "Confirmar" + Então o template "Avaliação Semestral" deve conter a questão "Sugestões de melhoria para o semestre" + + Cenário: [Feliz] Editar um template não afeta formulários já criados a partir dele + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + E que existe um formulário criado a partir do template "Avaliação Docente 2024.1" + Quando eu abro o editor do template "Avaliação Docente 2024.1" + E altero o campo "Nome do template" para "Avaliação Docente 2024.2" + E clico no botão "Confirmar" + Então o formulário criado anteriormente deve manter as questões originais do template "Avaliação Docente 2024.1" + + Cenário: [Feliz] Deletar um template não afeta formulários já criados a partir dele + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + E que existe um formulário criado a partir do template "Avaliação Docente 2024.1" + Quando eu clico no ícone de deletar do card "Avaliação Docente 2024.1" + E confirmo a exclusão do template + Então o formulário criado anteriormente deve continuar disponível e inalterado + + Cenário: [Triste] Tentar salvar a edição com o nome do template vazio + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Docente 2024.1" + E deixo o campo "Nome do template" em branco + E clico no botão "Confirmar" + Então o sistema deve exibir a mensagem de erro "O nome do template é obrigatório" + E as alterações não devem ser salvas + + Cenário: [Triste] Tentar salvar a edição com enunciado de questão vazio + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Semestral" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Semestral" + E apago o enunciado de uma das questões existentes + E clico no botão "Confirmar" + Então o sistema deve exibir a mensagem de erro "O enunciado da questão é obrigatório" + E as alterações não devem ser salvas + + Cenário: [Triste] Tentar salvar a edição de questão do tipo Radio sem opções de resposta + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Semestral" está cadastrado no sistema + Quando eu abro o editor do template "Avaliação Semestral" + E removo todas as opções de resposta de uma questão do tipo "Radio" + E clico no botão "Confirmar" + Então o sistema deve exibir a mensagem de erro "Questões do tipo Radio devem ter ao menos uma opção de resposta" + E as alterações não devem ser salvas + + Cenário: [Feliz] Deletar um template existente com sucesso após confirmação + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + Quando eu clico no ícone de deletar do card "Avaliação Docente 2024.1" + E confirmo a exclusão do template + Então o template "Avaliação Docente 2024.1" não deve aparecer na listagem de templates + + Cenário: [Alternativo] Cancelar a deleção mantém o template na listagem + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E eu acesso a página de gerenciamento de templates + E que o template "Avaliação Docente 2024.1" está cadastrado no sistema + Quando eu clico no ícone de deletar do card "Avaliação Docente 2024.1" + E cancelo a exclusão do template + Então o template "Avaliação Docente 2024.1" deve permanecer na listagem de templates + + Cenário: [Triste] Participante tenta editar um template existente + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + Quando eu acesso a URL de gerenciamento de templates + Então o sistema deve exibir a mensagem "Você não tem permissão para acessar esta página" + E eu devo ser redirecionado para a página inicial do meu perfil diff --git a/features/gerar_relatorio.feature b/features/gerar_relatorio.feature new file mode 100644 index 0000000000..26a2969714 --- /dev/null +++ b/features/gerar_relatorio.feature @@ -0,0 +1,30 @@ +# language: pt + +Funcionalidade: Gerar relatório do administrador + Como administrador + Quero baixar um arquivo CSV com os resultados de um formulário específico + A fim de analisar os dados e métricas de avaliação detalhadamente + + Cenário: [Feliz] Baixar CSV com resultados de um formulário com respostas + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um formulário criado para a turma "CIC0097 - BANCOS DE DADOS" com respostas submetidas + Quando eu acesso a página de "Gerar Relatórios" + E eu seleciono o formulário da turma "CIC0097 - BANCOS DE DADOS" + E eu aciono a opção "Exportar para CSV" + Então o sistema deve gerar o arquivo de CSV resultados + E iniciar automaticamente o download do arquivo ".csv" correspondente + + Cenário: [Triste] Tentar baixar CSV de um formulário sem respostas submetidas + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um formulário criado para a turma "CIC0105 - ENGENHARIA DE SOFTWARE" sem respostas submetidas + Quando eu acesso a página de "Gerar Relatórios" + E eu seleciono o formulário da turma "CIC0105 - ENGENHARIA DE SOFTWARE" + E eu tento acionar a opção "Exportar para CSV" + Então o sistema deve exibir a mensagem de erro "Não há dados suficientes para exportar este formulário" + E o download não deve ser iniciado + + Cenário: [Triste] Tentar baixar CSV com resultados de um formulário sem permissão de administrador + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + Quando eu tento acessar diretamente à URL de exportação de dados em CSV de um formulário + Então o sistema deve bloquear a ação + E exibir a mensagem de erro "Acesso negado: você não tem permissão para exportar dados" diff --git a/features/gerenciamento_departamento.feature b/features/gerenciamento_departamento.feature new file mode 100644 index 0000000000..e3268a46da --- /dev/null +++ b/features/gerenciamento_departamento.feature @@ -0,0 +1,18 @@ +# language: pt + +#Issue-11 + +Funcionalidade: Sistema de gerenciamento por departamento + Como administrador + Quero gerenciar os dados de turmas + A fim de organizar as informações acadêmicas + + Cenário: Caminho feliz + Dado que existem turmas no departamento do administrador + Quando o administrador selecionar uma dessas turmas + Então o sistema deve exibir os dados correspondentes + + Cenário: Caminho triste + Dado que não existem turmas no departamento ou turma não pertence ao departamento + Quando o administrador realizar a consulta + Então o sistema deve informar que não há dados disponíveis diff --git a/features/importar_dados_SIGAA.feature b/features/importar_dados_SIGAA.feature new file mode 100644 index 0000000000..cc599f9e04 --- /dev/null +++ b/features/importar_dados_SIGAA.feature @@ -0,0 +1,21 @@ +# language: pt + +#Issue-19 + +Funcionalidade: Importar dados do SIGAA + Como administrador + Quero importar dados do SIGAA + A fim de cadastrar informações acadêmicas no sistema + + Cenário: Caminho feliz + Dado que o arquivo JSON é válido + E existem dados disponíveis para importação + Quando o administrador solicitar a importação + Então os dados devem ser importados com sucesso + E armazenados na base de dados + + Cenário: Caminho triste + Dado que o JSON está inválido, ausente ou mal formatado + Quando o administrador solicitar a importação + Então o sistema deve exibir uma mensagem de erro + E nenhum dado deve ser salvo diff --git a/features/redefinicao_senha.feature b/features/redefinicao_senha.feature new file mode 100644 index 0000000000..bc8881f63e --- /dev/null +++ b/features/redefinicao_senha.feature @@ -0,0 +1,47 @@ +# language: pt + +@Issue-10 + +Funcionalidade: Redefinição de senha + Eu como Usuário + Quero redefinir uma senha para o meu usuário a partir do e-mail recebido após a solicitação da troca de senha + A fim de recuperar o meu acesso ao sistema + + Cenário: [Feliz] Solicitar redefinição de senha + Dado que eu estou na página de Login + Quando eu clico em "Redefinir senha" + E preencho o campo "E-mail" com um e-mail cadastrado + E clico em "Confirmar" + Então o link de redefinição deve ser gerado e enviado para o e-mail cadastrado + + Cenário: [Feliz] Redefinir senha com link válido + Dado que recebo um e-mail com um link de redefinição de senha válido + Quando eu acesso o link e preencho o campo "Nova Senha" com uma senha válida + E preencho o campo "Confirmar Senha" com a mesma senha informada no campo "Nova Senha" + E clico em "Salvar" + Então a senha deve ser redefinida com sucesso + E eu devo conseguir acessar o sistema utilizando a nova senha + E não devo conseguir acessar o sistema com a senha anterior + + Cenário: [Triste] Tentar redefinir senha com campos vazios + Dado que recebo um e-mail com um link de redefinição de senha válido + Quando eu acesso o link e não preencho os campos de senha + E clico em "Salvar" + Então devo ver a mensagem "Senha inválida" + E eu não devo conseguir acessar o sistema + + Cenário: [Triste] Tentar redefinir senhas que não correspondem + Dado que recebo um e-mail com um link de redefinição de senha válido + Quando eu acesso o link e preencho com senhas que não correspondem + E clico em "Salvar" + Então devo ver a mensagem "Senha inválida" + E eu não devo conseguir acessar o sistema + + Cenário: [Triste] Tentar redefinir senha com link inválido + Dado que recebo um e-mail com um link de redefinição de senha inválido ou expirado + Quando eu tento acessar o link para redefinir minha senha + Então devo ver uma mensagem "Link de redefinição de senha inválido ou expirado" + E não devo conseguir redefinir minha senha + + + diff --git a/features/responder_formulario.feature b/features/responder_formulario.feature new file mode 100644 index 0000000000..de09a152b0 --- /dev/null +++ b/features/responder_formulario.feature @@ -0,0 +1,37 @@ +# language: pt + +Funcionalidade: Responder formulário + Com o perfil de discente + Quero preencher e enviar os formulários de avaliação + A fim de registrar meu feedback sobre as disciplinas e docentes + + Cenário: [Feliz] Responder um formulário com todos os dados válidos + Dado que eu estou logado no sistema CAMAAR como "discente" e matriculado na turma "CIC0097 - BANCOS DE DADOS" + E eu estou na página de resposta do formulário desta turma + Quando eu preencho todas as perguntas com respostas válidas + E eu envio o formulário + Então o sistema deve exibir a mensagem "Avaliação enviada com sucesso" + E o formulário deve deixar de aparecer na minha lista de pendentes + + Cenário: [Triste] Tentar enviar um formulário com campos obrigatórios vazios + Dado que eu estou logado no sistema CAMAAR como "discente" e matriculado na turma "CIC0105 - ENGENHARIA DE SOFTWARE" + E eu estou na página de resposta do formulário desta turma + Quando eu deixo a pergunta "Avaliação do Docente" em branco + E eu tento enviar o formulário + Então o sistema deve exibir a mensagem de erro "Todos os campos obrigatórios devem ser preenchidos" + E o formulário não deve ser computado como respondido + + Cenário: [Triste] Tentar preencher o formulário com notas fora do intervalo permitido + Dado que eu estou logado no sistema CAMAAR como "discente" e matriculado na turma "CIC0202 - PROGRAMAÇÃO CONCORRENTE" + E eu estou na página de resposta do formulário desta turma + Quando eu insiro o valor "6" em uma das perguntas de nota + E eu tento enviar o formulário + Então o sistema deve exibir a mensagem de erro "Por favor, insira um valor válido entre 1 e 5" + E o formulário não deve ser computado como respondido + + Cenário: [Triste] Tentar responder novamente um formulário já enviado + Dado que eu estou logado no sistema CAMAAR como "discente" e matriculado na turma "CIC0097 - BANCOS DE DADOS" + E eu já enviei o formulário de avaliação desta turma anteriormente + Quando eu tento acessar diretamente à página de resposta deste formulário + Então o sistema deve exibir a mensagem de erro "Este formulário já foi respondido" + E por fim não deve permitir nova submissão diff --git a/features/sistema_login.feature b/features/sistema_login.feature new file mode 100644 index 0000000000..923fee0c09 --- /dev/null +++ b/features/sistema_login.feature @@ -0,0 +1,38 @@ +# language: pt + +@Issue-13 + +Funcionalidade: Sistema de Login + Eu como Usuário do sistema + Quero acessar o sistema utilizando um e-mail ou matrícula e uma senha já cadastrada + A fim de responder formulários ou gerenciar o sistema + + Cenário: [Feliz] Credenciais de usuário com perfil "Discente" válido + Dado que acesso o formulário de "Login" + Quando eu preencho o campo de "E-mail ou matrícula" com um e-mail ou matrícula de um "Discente" cadastrado + E preencho o campo "Senha" com a senha correspondente válida + E clico no botão "Entrar" + Então devo ser redirecionado para a página com perfil de "Discente" + E não devo ver a opção de "Gerenciamento" no menu lateral + + Cenário: [Feliz] Credenciais de usuário com perfil "Administrador" válido + Dado que acesso o formulário de "Login" + Quando eu preencho o campo de "E-mail ou matrícula" com um e-mail ou matrícula de um "Administrador" cadastrado + E preencho o campo "Senha" com a senha correspondente válida + E clico no botão "Entrar" + Então devo ser redirecionado para a página com perfil de "Administrador" + E devo ver a opção de "Gerenciamento" no menu lateral + + Cenário: [Triste] Usuário inexistente + Dado que acesso o formulário de "Login" + Quando eu preencho o campo de "E-mail ou matrícula" com um e-mail ou matrícula não cadastrado + E preencho o campo "Senha" com qualquer senha + E clico no botão "Entrar" + Então devo ver uma mensagem "Usuário e/ou senha inválidos" + + Cenário: [Triste] Usuário cadastrado com senha incorreta + Dado que acesso o formulário de "Login" + Quando eu preencho o campo de "E-mail ou matrícula" com um e-mail ou matrícula cadastrado + E preencho o campo "Senha" com uma senha não correspondente + E clico no botão "Entrar" + Então devo ver uma mensagem "Usuário e/ou senha inválidos" \ No newline at end of file diff --git a/features/step_definitions/.keep b/features/step_definitions/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/features/step_definitions/responder_formulario_steps.rb b/features/step_definitions/responder_formulario_steps.rb new file mode 100644 index 0000000000..66af709315 --- /dev/null +++ b/features/step_definitions/responder_formulario_steps.rb @@ -0,0 +1,209 @@ +# features/step_definitions/responder_formulario_steps.rb + +# ── CONTEXTO / DADO ─────────────────────────────────────────────────────────── + +Dado("que eu estou logado no sistema CAMAAR com o perfil de {string}") do |perfil| + case perfil + when "discente" + @usuario = create(:usuario, perfil: :discente, primeiro_acesso: false) + @discente = create(:discente, usuario: @usuario) + when "docente" + @usuario = create(:usuario, perfil: :docente, primeiro_acesso: false) + @docente = create(:docente, usuario: @usuario, departamento: create(:departamento)) + end + + visit login_path + fill_in "Login", with: @usuario.login + fill_in "Senha", with: "Senha123!" + click_button "Entrar" + expect(page).to have_current_path(root_path) +end + +Dado("que eu não estou logado no sistema") do + # não faz login — sessão vazia +end + +Dado("estou matriculado na turma {string}") do |nome_turma| + @turma = encontrar_ou_criar_turma(nome_turma) + create(:matricula, discente: @discente, turma: @turma) +end + +Dado("existe um formulário de avaliação disponível para a turma {string}") do |nome_turma| + @turma ||= encontrar_ou_criar_turma(nome_turma) + @docente ||= create(:docente, usuario: create(:usuario, perfil: :docente), + departamento: create(:departamento)) + @template = create(:template, docente: @docente) + @questao_txt = create(:questao_template, template: @template, tipo: :aberta, + enunciado: "Deixe seu comentário sobre a disciplina") + @questao_rad = create(:questao_template, template: @template, tipo: :multipla, + enunciado: "Como você avalia o docente?") + create(:opcao_questao, questao_template: @questao_rad, texto: "Ótimo") + create(:opcao_questao, questao_template: @questao_rad, texto: "Bom") + create(:opcao_questao, questao_template: @questao_rad, texto: "Regular") + + @formulario = create(:formulario, turma: @turma, template: @template, + titulo: "Avaliação Docente 2024.1", prazo: 7.days.from_now) + # instancia questões no formulário + @q1 = create(:questao, formulario: @formulario, questao_template: @questao_txt, + enunciado: @questao_txt.enunciado, tipo: :aberta) + @q2 = create(:questao, formulario: @formulario, questao_template: @questao_rad, + enunciado: @questao_rad.enunciado, tipo: :multipla) +end + +Dado("que o formulário contém uma questão do tipo {string} e uma do tipo {string}") do |_tipo1, _tipo2| + # as questões já foram criadas no passo anterior — nada a fazer +end + +Dado("que o formulário contém questões obrigatórias") do + # questões já criadas — todas são obrigatórias por definição +end + +Dado("que já respondi o formulário de avaliação da turma {string}") do |nome_turma| + @turma ||= encontrar_ou_criar_turma(nome_turma) + + # garante que formulário e questões existam + unless @formulario + step "existe um formulário de avaliação disponível para a turma \"#{nome_turma}\"" + end + + @envio = create(:envio_formulario, formulario: @formulario, discente: @discente, + enviado_em: Time.current) + create(:resposta, envio_formulario: @envio, questao: @q1, + conteudo: "Ótima disciplina") + create(:resposta, envio_formulario: @envio, questao: @q2, + conteudo: "Ótimo") +end + +Dado("que o formulário de avaliação da turma {string} está encerrado") do |nome_turma| + @turma ||= encontrar_ou_criar_turma(nome_turma) + unless @formulario + step "existe um formulário de avaliação disponível para a turma \"#{nome_turma}\"" + end + @formulario.update!(prazo: 2.days.ago) +end + +Dado("existe um formulário disponível para a turma {string}") do |nome_turma| + turma_outra = encontrar_ou_criar_turma(nome_turma) + @docente ||= create(:docente, usuario: create(:usuario, perfil: :docente), + departamento: create(:departamento)) + template = create(:template, docente: @docente) + @formulario_outro = create(:formulario, turma: turma_outra, template: template, + titulo: "Formulário outra turma", prazo: 7.days.from_now) +end + +Dado("eu não estou matriculado na turma {string}") do |_nome_turma| + # discente não tem matrícula nessa turma — estado padrão +end + +# ── QUANDO ─────────────────────────────────────────────────────────────────── + +Quando("eu acesso o formulário e preencho todas as questões") do + visit formulario_path(@formulario) + click_link "Responder →" + + # preenche questão aberta + within "[data-questao-id='#{@q1.id}']" do + fill_in "resposta[questao_#{@q1.id}]", with: "Ótima disciplina, recomendo!" + end + + # seleciona opção de múltipla escolha + within "[data-questao-id='#{@q2.id}']" do + choose "Ótimo" + end +end + +Quando("eu acesso o formulário e deixo uma questão sem resposta") do + visit formulario_path(@formulario) + click_link "Responder →" + # preenche apenas a primeira, deixa a segunda em branco + within "[data-questao-id='#{@q1.id}']" do + fill_in "resposta[questao_#{@q1.id}]", with: "Comentário parcial" + end + # não preenche @q2 +end + +Quando("eu acesso o formulário respondido") do + visit formulario_path(@formulario) +end + +Quando("eu tento acessar o formulário novamente para responder") do + visit formulario_path(@formulario) +end + +Quando("eu tento acessar o formulário para responder") do + visit formulario_path(@formulario) +end + +Quando("eu tento acessar o formulário diretamente pela URL") do + visit formulario_path(@formulario_outro) +end + +Quando("eu tento acessar a página de resposta de um formulário") do + formulario_qualquer = create(:formulario, + turma: create(:turma, disciplina: create(:disciplina), + docente: create(:docente, + usuario: create(:usuario, perfil: :docente), + departamento: create(:departamento))), + template: create(:template, + docente: create(:docente, + usuario: create(:usuario, perfil: :docente), + departamento: create(:departamento)))) + visit new_envio_formulario_path(formulario_id: formulario_qualquer.id) +end + +Quando("clico em {string}") do |botao| + click_button botao +end + +# ── ENTÃO ───────────────────────────────────────────────────────────────────── + +Então("o sistema deve registrar meu envio com sucesso") do + expect(EnvioFormulario.where(formulario: @formulario, discente: @discente)).to exist + expect(Resposta.joins(:envio_formulario) + .where(envio_formularios: { formulario: @formulario, discente: @discente }).count).to eq(2) +end + +Então("devo ver a mensagem {string}") do |mensagem| + expect(page).to have_content(mensagem) +end + +Então("devo ser redirecionado para o meu dashboard") do + expect(page).to have_current_path(root_path) +end + +Então("devo ser redirecionado para a lista de formulários") do + expect(page).to have_current_path(formularios_path) +end + +Então("devo ser redirecionado para a página de login") do + expect(page).to have_current_path(login_path) +end + +Então("devo ver minhas respostas em modo somente leitura") do + expect(page).to have_content("Esta é sua resposta enviada") + expect(page).not_to have_field("resposta") + expect(page).not_to have_button("Enviar Respostas") +end + +Então("não devo ver o botão {string}") do |botao| + expect(page).not_to have_button(botao) +end + +Então("o formulário não deve ser submetido") do + expect(EnvioFormulario.where(formulario: @formulario, discente: @discente)).not_to exist +end + +# ── HELPER ─────────────────────────────────────────────────────────────────── + +def encontrar_ou_criar_turma(nome_turma) + codigo = nome_turma.split(" - ").first.strip + disciplina = Disciplina.find_by(codigo: codigo) || + create(:disciplina, codigo: codigo, + nome: nome_turma.split(" - ").last.strip) + docente = @docente || create(:docente, + usuario: create(:usuario, perfil: :docente), + departamento: create(:departamento)) + Turma.find_by(codigo: "TA", disciplina: disciplina) || + create(:turma, codigo: "TA", semestre: "2021.2", + disciplina: disciplina, docente: docente) +end diff --git a/features/support/env.rb b/features/support/env.rb new file mode 100644 index 0000000000..f2ab1f926b --- /dev/null +++ b/features/support/env.rb @@ -0,0 +1,78 @@ +# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. +# It is recommended to regenerate this file in the future when you upgrade to a +# newer version of cucumber-rails. Consider adding your own code to a new file +# instead of editing this one. Cucumber will automatically load all features/**/*.rb +# files. + + +require 'cucumber/rails' + +# By default, any exception happening in your Rails application will bubble up +# to Cucumber so that your scenario will fail. This is a different from how +# your application behaves in the production environment, where an error page will +# be rendered instead. +# +# Sometimes we want to override this default behaviour and allow Rails to rescue +# exceptions and display an error page (just like when the app is running in production). +# Typical scenarios where you want to do this is when you test your error pages. +# There are two ways to allow Rails to rescue exceptions: +# +# 1) Tag your scenario (or feature) with @allow-rescue +# +# 2) Set the value below to true. Beware that doing this globally is not +# recommended as it will mask a lot of errors for you! +# +ActionController::Base.allow_rescue = false + +# Remove/comment out the lines below if your app doesn't have a database. +# For some databases (like MongoDB and CouchDB) you may need to use :truncation instead. +begin + DatabaseCleaner.strategy = :transaction +rescue NameError + raise "You need to add database_cleaner to your Gemfile (in the :test group) if you wish to use it." +end + +# You may also want to configure DatabaseCleaner to use different strategies for certain features and scenarios. +# See the DatabaseCleaner documentation for details. Example: +# +# Before('@no-txn,@selenium,@culerity,@celerity,@javascript') do +# # { except: [:widgets] } may not do what you expect here +# # as Cucumber::Rails::Database.javascript_strategy overrides +# # this setting. +# DatabaseCleaner.strategy = :truncation +# end +# +# Before('not @no-txn', 'not @selenium', 'not @culerity', 'not @celerity', 'not @javascript') do +# DatabaseCleaner.strategy = :transaction +# end +# + +# Possible values are :truncation and :transaction +# The :transaction strategy is faster, but might give you threading problems. +# See https://github.com/cucumber/cucumber-rails/blob/master/features/choose_javascript_database_strategy.feature +Cucumber::Rails::Database.javascript_strategy = :truncation + + +require 'capybara/cucumber' +require 'capybara/dsl' +require 'rspec/expectations' +require 'selenium-webdriver' + +Capybara.configure do |config| + config.default_driver = :selenium_chrome_headless + config.default_max_wait_time = 5 + config.ignore_hidden_elements = true +end + +Capybara.register_driver :selenium_chrome_headless do |app| + options = Selenium::WebDriver::Chrome::Options.new + options.add_argument('--headless=new') + options.add_argument('--no-sandbox') + options.add_argument('--disable-dev-shm-usage') + options.add_argument('--window-size=1280,900') + + Capybara::Selenium::Driver.new(app, browser: :chrome, options: options) +end + +# World(Capybara::DSL) -- já incluso por capybara/cucumber +World(RSpec::Matchers) diff --git a/features/support/hooks.rb b/features/support/hooks.rb new file mode 100644 index 0000000000..c2ef98a81a --- /dev/null +++ b/features/support/hooks.rb @@ -0,0 +1,13 @@ +Before('@limpar_sessao') do + Capybara.reset_sessions! +end + +After do |cenario| + if cenario.failed? + nome = cenario.name.gsub(/[^a-z0-9]/i, '_').downcase + caminho = "tmp/screenshots/#{nome}_#{Time.now.strftime('%Y%m%d_%H%M%S')}.png" + FileUtils.mkdir_p('tmp/screenshots') + page.save_screenshot(caminho) + attach(File.read(caminho), 'image/png') + end +end diff --git a/features/visualizar_resultados.feature b/features/visualizar_resultados.feature new file mode 100644 index 0000000000..cf97ae35e5 --- /dev/null +++ b/features/visualizar_resultados.feature @@ -0,0 +1,26 @@ +# language: pt + +Funcionalidade: Visualização de resultados dos formulários + Como administrador + Quero visualizar os resultados dos formulários criados + A fim de acompanhar o andamento e o consolidado das avaliações anonimamente + + Cenário: [Feliz] Visualizar resultados de um formulário com respostas submetidas + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um formulário de avaliação criado para a turma "CIC0097 - BANCOS DE DADOS" com respostas submetidas + Quando eu acesso a página de "Resultados das Avaliações" + E eu seleciono para visualizar os resultados deste formulário + Então eu devo visualizar um painel com a média das notas e os comentários anonimizados + + Cenário: [Triste] Tentar visualizar resultados de um formulário sem avaliações submetidas + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E existe um formulário de avaliação criado para a turma "CIC0105 - ENGENHARIA DE SOFTWARE" sem respostas submetidas + Quando eu acesso a página de "Resultados das Avaliações" + E eu seleciono para visualizar os resultados deste formulário + Então eu devo ver a mensagem "Ainda não há respostas suficientes para gerar a visualização deste formulário" + + Cenário: [Triste] Tentar acessar os resultados dos formulários sem permissão + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + Quando eu tento acessar a página de Resultados das Avaliações + Então o sistema deve bloquear o acesso + E exibir a mensagem de erro "Acesso negado: você não tem permissão para visualizar esta página" diff --git a/features/visualizar_templates.feature b/features/visualizar_templates.feature new file mode 100644 index 0000000000..96865903a2 --- /dev/null +++ b/features/visualizar_templates.feature @@ -0,0 +1,31 @@ +# language: pt + +#Issue-6 + +Funcionalidade: Visualização dos templates criados + Como administrador + Quero visualizar os templates de formulário que eu criei + A fim de gerenciar e utilizar os templates disponíveis + + Cenário: [Feliz] Administrador visualiza listagem de templates cadastrados + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E que os seguintes templates estão cadastrados no sistema: + | nome | semestre | + | Avaliação Docente | 2024.1 | + | Avaliação de Infraestrutura | 2024.2 | + Quando eu acesso a página de gerenciamento de templates + Então eu devo ver uma grade com os templates cadastrados + E cada card deve exibir o nome, o semestre, o ícone de editar e o ícone de deletar + + Cenário: [Alternativo] Administrador acessa a tela sem nenhum template cadastrado + Dado que eu estou logado no sistema CAMAAR com o perfil de "administrador" + E não há nenhum template cadastrado no sistema + Quando eu acesso a página de gerenciamento de templates + Então eu não devo ver nenhum card de template na grade + E eu devo ver apenas a opção de criação de um novo template + + Cenário: [Triste] Discente recebe mensagem de erro ao tentar acessar templates + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + Quando eu acesso a URL de gerenciamento de templates + Então o sistema deve exibir a mensagem "Você não tem permissão para acessar esta página" + E eu devo ser redirecionado para a página inicial do meu perfil diff --git a/features/vizualisar_formularios.feature b/features/vizualisar_formularios.feature new file mode 100644 index 0000000000..ace395ebb4 --- /dev/null +++ b/features/vizualisar_formularios.feature @@ -0,0 +1,34 @@ +# language: pt + +Funcionalidade: Visualização de formulários para responder + Como discente + Quero visualizar a lista de formulários não respondidos das turmas em que estou matriculado + A fim de saber quais avaliações eu preciso responder no semestre letivo + + Cenário: [Feliz] Visualizar a lista de formulários disponíveis para resposta + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E eu estou matriculado na turma "CIC0097 - BANCOS DE DADOS" + E existe um formulário aberto e não respondido para esta turma + Quando eu acesso a aba de "Formulários Pendentes" + Então eu devo ver o formulário da turma "CIC0097 - BANCOS DE DADOS" na lista + + Cenário: [Triste] Tentar visualizar formulários não estando matriculado em disciplinas + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E o sistema registra que eu não possuo matrícula ativa no semestre atual + Quando eu acesso a aba de "Formulários Pendentes" + Então eu devo ver a mensagem "Você não possui formulários pendentes para este semestre" + + Cenário: [Triste] Não visualizar formulários quando não há matrícula ativa + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E eu não estou matriculado na turma "CIC0105 - ENGENHARIA DE SOFTWARE" + E existe um formulário aberto para esta turma + Quando eu acesso a aba de "Formulários Pendentes" + Então eu não devo ver o formulário da turma "CIC0105 - ENGENHARIA DE SOFTWARE" na lista + + Cenário: [Triste] Não visualizar formulário que já foi respondido + Dado que eu estou logado no sistema CAMAAR com o perfil de "discente" + E eu estou matriculado na turma "CIC0202 - PROGRAMAÇÃO CONCORRENTE" + E eu já respondi ao formulário de avaliação desta turma + Quando eu acesso a aba de "Formulários Pendentes" + Então eu não devo ver o formulário da turma "CIC0202 - PROGRAMAÇÃO CONCORRENTE" na lista + E devo ver que não tem formulario pendente. \ No newline at end of file diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/lib/tasks/cucumber.rake b/lib/tasks/cucumber.rake new file mode 100644 index 0000000000..0caa4d2553 --- /dev/null +++ b/lib/tasks/cucumber.rake @@ -0,0 +1,69 @@ +# IMPORTANT: This file is generated by cucumber-rails - edit at your own peril. +# It is recommended to regenerate this file in the future when you upgrade to a +# newer version of cucumber-rails. Consider adding your own code to a new file +# instead of editing this one. Cucumber will automatically load all features/**/*.rb +# files. + + +unless ARGV.any? {|a| a =~ /^gems/} # Don't load anything when running the gems:* tasks + +vendored_cucumber_bin = Dir["#{Rails.root}/vendor/{gems,plugins}/cucumber*/bin/cucumber"].first +$LOAD_PATH.unshift(File.dirname(vendored_cucumber_bin) + '/../lib') unless vendored_cucumber_bin.nil? + +begin + require 'cucumber/rake/task' + + namespace :cucumber do + Cucumber::Rake::Task.new({ok: 'test:prepare'}, 'Run features that should pass') do |t| + t.binary = vendored_cucumber_bin # If nil, the gem's binary is used. + t.fork = true # You may get faster startup if you set this to false + t.profile = 'default' + end + + Cucumber::Rake::Task.new({wip: 'test:prepare'}, 'Run features that are being worked on') do |t| + t.binary = vendored_cucumber_bin + t.fork = true # You may get faster startup if you set this to false + t.profile = 'wip' + end + + Cucumber::Rake::Task.new({rerun: 'test:prepare'}, 'Record failing features and run only them if any exist') do |t| + t.binary = vendored_cucumber_bin + t.fork = true # You may get faster startup if you set this to false + t.profile = 'rerun' + end + + desc 'Run all features' + task all: [:ok, :wip] + + task :statsetup do + require 'rails/code_statistics' + ::STATS_DIRECTORIES << %w(Cucumber\ features features) if File.exist?('features') + ::CodeStatistics::TEST_TYPES << "Cucumber features" if File.exist?('features') + end + + end + + desc 'Alias for cucumber:ok' + task cucumber: 'cucumber:ok' + + task default: :cucumber + + task features: :cucumber do + STDERR.puts "*** The 'features' task is deprecated. See rake -T cucumber ***" + end + + # In case we don't have the generic Rails test:prepare hook, append a no-op task that we can depend upon. + task 'test:prepare' do + end + + task stats: 'cucumber:statsetup' + + +rescue LoadError + desc 'cucumber rake task not available (cucumber not installed)' + task :cucumber do + abort 'Cucumber rake task is not available. Be sure to install cucumber as a gem or plugin' + end +end + +end diff --git a/log/.keep b/log/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/public/400.html b/public/400.html new file mode 100644 index 0000000000..640de03397 --- /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 0000000000..d7f0f14222 --- /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 0000000000..43d2811e8c --- /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 0000000000..f12fb4aa17 --- /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 0000000000..e4eb18a759 --- /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 0000000000..c4c9dbfbbd 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 0000000000..04b34bf83f --- /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 0000000000..c19f78ab68 --- /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 0000000000..e69de29bb2 diff --git a/spec/controllers/envio_formularios_controller_spec.rb b/spec/controllers/envio_formularios_controller_spec.rb new file mode 100644 index 0000000000..8e8fd06ec1 --- /dev/null +++ b/spec/controllers/envio_formularios_controller_spec.rb @@ -0,0 +1,174 @@ +# spec/controllers/envio_formularios_controller_spec.rb +require "rails_helper" + +RSpec.describe EnvioFormulariosController, type: :controller do + let(:depto) { create(:departamento) } + let(:usr_doc) { create(:usuario, perfil: :docente) } + let(:docente) { create(:docente, usuario: usr_doc, departamento: depto) } + let(:disciplina) { create(:disciplina) } + let(:turma) { create(:turma, disciplina: disciplina, docente: docente) } + let(:template) { create(:template, docente: docente) } + + let(:usr_disc) { create(:usuario, perfil: :discente, primeiro_acesso: false) } + let(:discente) { create(:discente, usuario: usr_disc) } + + let(:qt_aberta) { create(:questao_template, template: template, tipo: :aberta) } + let(:qt_multi) { create(:questao_template, template: template, tipo: :multipla) } + let!(:opcao1) { create(:opcao_questao, questao_template: qt_multi, texto: "Ótimo") } + let!(:opcao2) { create(:opcao_questao, questao_template: qt_multi, texto: "Bom") } + + let!(:formulario) { create(:formulario, turma: turma, template: template, prazo: 7.days.from_now) } + let!(:q1) { create(:questao, formulario: formulario, questao_template: qt_aberta, tipo: :aberta) } + let!(:q2) { create(:questao, formulario: formulario, questao_template: qt_multi, tipo: :multipla) } + + before do + session[:usuario_id] = usr_disc.id + create(:matricula, discente: discente, turma: turma) + end + + # ── GET #new ────────────────────────────────────────────────────────────── + describe "GET #new" do + it "retorna 200 para discente matriculado com formulário aberto" do + get :new, params: { formulario_id: formulario.id } + expect(response).to have_http_status(:ok) + end + + it "atribui o formulário correto" do + get :new, params: { formulario_id: formulario.id } + expect(assigns(:formulario)).to eq(formulario) + end + + it "lista as questões do formulário" do + get :new, params: { formulario_id: formulario.id } + expect(assigns(:questoes)).to match_array([q1, q2]) + end + + context "discente já respondeu" do + before { create(:envio_formulario, formulario: formulario, discente: discente) } + + it "redireciona para minha_resposta" do + get :new, params: { formulario_id: formulario.id } + expect(response).to redirect_to(minha_resposta_formulario_path(formulario)) + end + end + + context "formulário com prazo encerrado" do + before { formulario.update!(prazo: 1.day.ago) } + + it "redireciona para formularios_path com alerta de prazo" do + get :new, params: { formulario_id: formulario.id } + expect(response).to redirect_to(formularios_path) + expect(flash[:alert]).to match(/prazo/i) + end + end + + context "discente não matriculado na turma" do + before { discente.matriculas.destroy_all } + + it "redireciona com alerta de acesso" do + get :new, params: { formulario_id: formulario.id } + expect(response).to redirect_to(formularios_path) + expect(flash[:alert]).to be_present + end + end + + context "sem autenticação" do + before { session[:usuario_id] = nil } + + it "redireciona para login" do + get :new, params: { formulario_id: formulario.id } + expect(response).to redirect_to(login_path) + end + end + + context "logado como docente" do + before { session[:usuario_id] = usr_doc.id } + + it "redireciona para root" do + get :new, params: { formulario_id: formulario.id } + expect(response).to redirect_to(root_path) + end + end + end + + # ── POST #create ────────────────────────────────────────────────────────── + describe "POST #create" do + let(:respostas_validas) do + { q1.id.to_s => "Ótima disciplina!", q2.id.to_s => "Ótimo" } + end + + it "cria EnvioFormulario com respostas completas" do + expect { + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + }.to change(EnvioFormulario, :count).by(1) + .and change(Resposta, :count).by(2) + end + + it "redireciona para dashboard com mensagem de sucesso" do + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + expect(response).to redirect_to(root_path) + expect(flash[:notice]).to match(/sucesso/i) + end + + it "registra enviado_em" do + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + envio = EnvioFormulario.last + expect(envio.enviado_em).not_to be_nil + end + + it "salva o conteúdo correto em cada Resposta" do + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + envio = EnvioFormulario.find_by(formulario: formulario, discente: discente) + expect(envio.respostas.find_by(questao: q1).conteudo).to eq("Ótima disciplina!") + expect(envio.respostas.find_by(questao: q2).conteudo).to eq("Ótimo") + end + + context "resposta faltando em uma questão" do + it "não cria envio e renderiza :new" do + expect { + post :create, params: { + formulario_id: formulario.id, + respostas: { q1.id.to_s => "Comentário", q2.id.to_s => "" } + } + }.not_to change(EnvioFormulario, :count) + + expect(response).to have_http_status(:unprocessable_entity) + expect(flash[:alert]).to match(/obrigatórias/i) + end + end + + context "tentativa de envio duplicado" do + before { create(:envio_formulario, formulario: formulario, discente: discente) } + + it "redireciona para minha_resposta sem criar novo envio" do + expect { + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + }.not_to change(EnvioFormulario, :count) + + expect(response).to redirect_to(minha_resposta_formulario_path(formulario)) + end + end + + context "formulário encerrado" do + before { formulario.update!(prazo: 1.day.ago) } + + it "redireciona para formularios_path sem criar envio" do + expect { + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + }.not_to change(EnvioFormulario, :count) + + expect(response).to redirect_to(formularios_path) + end + end + + context "discente de outra turma" do + before { discente.matriculas.destroy_all } + + it "redireciona com alerta de acesso" do + post :create, params: { formulario_id: formulario.id, respostas: respostas_validas } + expect(response).to redirect_to(formularios_path) + expect(flash[:alert]).to be_present + end + end + end +end diff --git a/spec/models/envio_formulario_spec.rb b/spec/models/envio_formulario_spec.rb new file mode 100644 index 0000000000..97638ce045 --- /dev/null +++ b/spec/models/envio_formulario_spec.rb @@ -0,0 +1,60 @@ +# spec/models/envio_formulario_spec.rb +require "rails_helper" + +RSpec.describe EnvioFormulario, type: :model do + let(:depto) { create(:departamento) } + let(:usr_doc) { create(:usuario, perfil: :docente) } + let(:docente) { create(:docente, usuario: usr_doc, departamento: depto) } + let(:disciplina) { create(:disciplina) } + let(:turma) { create(:turma, disciplina: disciplina, docente: docente) } + let(:template) { create(:template, docente: docente) } + let(:formulario) { create(:formulario, turma: turma, template: template, prazo: 7.days.from_now) } + let(:usr_disc) { create(:usuario, perfil: :discente) } + let(:discente) { create(:discente, usuario: usr_disc) } + + describe "associações" do + it { is_expected.to belong_to(:formulario) } + it { is_expected.to belong_to(:discente) } + it { is_expected.to have_many(:respostas).dependent(:destroy) } + end + + describe "validações" do + it "é inválido com par formulario+discente duplicado" do + create(:envio_formulario, formulario: formulario, discente: discente) + duplicado = build(:envio_formulario, formulario: formulario, discente: discente) + expect(duplicado).not_to be_valid + expect(duplicado.errors[:formulario_id]).to be_present + end + + it "é válido com par formulario+discente único" do + envio = build(:envio_formulario, formulario: formulario, discente: discente) + expect(envio).to be_valid + end + + it "é inválido quando formulário está encerrado" do + formulario.update!(prazo: 1.day.ago) + envio = build(:envio_formulario, formulario: formulario, discente: discente) + expect(envio).not_to be_valid + expect(envio.errors[:base]).to include(match(/prazo/i)) + end + end + + describe "callbacks" do + it "registra enviado_em automaticamente no create" do + envio = create(:envio_formulario, formulario: formulario, discente: discente, enviado_em: nil) + expect(envio.reload.enviado_em).not_to be_nil + end + end +end + +# spec/models/resposta_spec.rb +RSpec.describe Resposta, type: :model do + describe "associações" do + it { is_expected.to belong_to(:envio_formulario) } + it { is_expected.to belong_to(:questao) } + end + + describe "validações" do + it { is_expected.to validate_presence_of(:conteudo) } + end +end diff --git a/spec/rails_helper.rb b/spec/rails_helper.rb new file mode 100644 index 0000000000..ef75d46770 --- /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/spec_helper.rb b/spec/spec_helper.rb new file mode 100644 index 0000000000..327b58ea1f --- /dev/null +++ b/spec/spec_helper.rb @@ -0,0 +1,94 @@ +# This file was generated by the `rails generate rspec:install` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# See https://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + + # This option will default to `:apply_to_host_groups` in RSpec 4 (and will + # have no way to turn it off -- the option exists only for backwards + # compatibility in RSpec 3). It causes shared 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 + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # 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 +end diff --git a/spec/system/login_spec.rb b/spec/system/login_spec.rb new file mode 100644 index 0000000000..16484a2f30 --- /dev/null +++ b/spec/system/login_spec.rb @@ -0,0 +1,73 @@ +require "rails_helper" + +RSpec.describe "Sistema de Login", type: :system do + before do + driven_by(:rack_test) + end + + it "permite login de discente e não mostra gerenciamento" do + User.create!( + nome: "Discente Teste", + email: "discente_teste@camaar.com", + matricula: "202400002", + perfil: "Discente", + password: "123456" + ) + + visit login_path + + fill_in "E-mail ou matrícula", with: "discente_teste@camaar.com" + fill_in "Senha", with: "123456" + click_button "Entrar" + + expect(page).to have_content("Perfil de Discente") + expect(page).not_to have_content("Gerenciamento") + end + + it "permite login de administrador e mostra gerenciamento" do + User.create!( + nome: "Administrador Teste", + email: "admin_teste@camaar.com", + matricula: "000000002", + perfil: "Administrador", + password: "123456" + ) + + visit login_path + + fill_in "E-mail ou matrícula", with: "admin_teste@camaar.com" + fill_in "Senha", with: "123456" + click_button "Entrar" + + expect(page).to have_content("Perfil de Administrador") + expect(page).to have_content("Gerenciamento") + end + + it "exibe erro para usuário inexistente" do + visit login_path + + fill_in "E-mail ou matrícula", with: "naoexiste@camaar.com" + fill_in "Senha", with: "qualquer" + click_button "Entrar" + + expect(page).to have_content("Usuário e/ou senha inválidos") + end + + it "exibe erro para senha incorreta" do + User.create!( + nome: "Discente Teste", + email: "discente_senha_errada@camaar.com", + matricula: "202400003", + perfil: "Discente", + password: "123456" + ) + + visit login_path + + fill_in "E-mail ou matrícula", with: "discente_senha_errada@camaar.com" + fill_in "Senha", with: "senhaerrada" + click_button "Entrar" + + expect(page).to have_content("Usuário e/ou senha inválidos") + end +end \ No newline at end of file diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tmp/pids/.keep b/tmp/pids/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tmp/storage/.keep b/tmp/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 0000000000..e69de29bb2