From d6dc3d3a3fde1a00d9617cb76e93a47166baa936 Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 16 Nov 2025 18:29:03 -0300 Subject: [PATCH 01/19] =?UTF-8?q?:sparkles:=20feat:=20adi=C3=A7=C3=A3o=20d?= =?UTF-8?q?a=20estrutura=20inicial=20do=20projeto=20rails?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/.dockerignore | 51 ++ app/.gitattributes | 9 + app/.github/dependabot.yml | 12 + app/.github/workflows/ci.yml | 124 +++++ app/.gitignore | 38 ++ app/.kamal/hooks/docker-setup.sample | 3 + app/.kamal/hooks/post-app-boot.sample | 3 + app/.kamal/hooks/post-deploy.sample | 14 + app/.kamal/hooks/post-proxy-reboot.sample | 3 + app/.kamal/hooks/pre-app-boot.sample | 3 + app/.kamal/hooks/pre-build.sample | 51 ++ app/.kamal/hooks/pre-connect.sample | 47 ++ app/.kamal/hooks/pre-deploy.sample | 122 +++++ app/.kamal/hooks/pre-proxy-reboot.sample | 3 + app/.kamal/secrets | 20 + app/.rubocop.yml | 8 + app/.ruby-version | 1 + app/Dockerfile | 76 +++ app/Gemfile | 68 +++ app/Gemfile.lock | 434 ++++++++++++++++++ app/Procfile.dev | 2 + app/README.md | 24 + app/Rakefile | 6 + app/app/assets/builds/.keep | 0 app/app/assets/images/.keep | 0 app/app/assets/stylesheets/application.css | 10 + app/app/assets/tailwind/application.css | 1 + app/app/controllers/application_controller.rb | 7 + app/app/controllers/concerns/.keep | 0 app/app/helpers/application_helper.rb | 2 + app/app/javascript/application.js | 3 + app/app/javascript/controllers/application.js | 9 + .../controllers/hello_controller.js | 7 + app/app/javascript/controllers/index.js | 4 + app/app/jobs/application_job.rb | 7 + app/app/mailers/application_mailer.rb | 4 + app/app/models/application_record.rb | 3 + app/app/models/concerns/.keep | 0 app/app/views/layouts/application.html.erb | 31 ++ app/app/views/layouts/mailer.html.erb | 13 + app/app/views/layouts/mailer.text.erb | 1 + app/app/views/pwa/manifest.json.erb | 22 + app/app/views/pwa/service-worker.js | 26 ++ app/bin/brakeman | 7 + app/bin/bundler-audit | 6 + app/bin/ci | 6 + app/bin/dev | 16 + app/bin/docker-entrypoint | 8 + app/bin/importmap | 4 + app/bin/jobs | 6 + app/bin/kamal | 27 ++ app/bin/rails | 4 + app/bin/rake | 4 + app/bin/rubocop | 8 + app/bin/setup | 35 ++ app/bin/thrust | 5 + app/config.ru | 6 + app/config/application.rb | 27 ++ app/config/boot.rb | 4 + app/config/bundler-audit.yml | 5 + app/config/cable.yml | 17 + app/config/cache.yml | 16 + app/config/ci.rb | 23 + app/config/credentials.yml.enc | 1 + app/config/database.yml | 41 ++ app/config/deploy.yml | 120 +++++ app/config/environment.rb | 5 + app/config/environments/development.rb | 78 ++++ app/config/environments/production.rb | 90 ++++ app/config/environments/test.rb | 53 +++ app/config/importmap.rb | 7 + app/config/initializers/assets.rb | 7 + .../initializers/content_security_policy.rb | 29 ++ .../initializers/filter_parameter_logging.rb | 8 + app/config/initializers/inflections.rb | 16 + app/config/locales/en.yml | 31 ++ app/config/puma.rb | 42 ++ app/config/queue.yml | 18 + app/config/recurring.yml | 15 + app/config/routes.rb | 14 + app/config/storage.yml | 27 ++ app/db/cable_schema.rb | 11 + app/db/cache_schema.rb | 12 + app/db/queue_schema.rb | 129 ++++++ app/db/seeds.rb | 9 + app/lib/tasks/.keep | 0 app/log/.keep | 0 app/public/400.html | 135 ++++++ app/public/404.html | 135 ++++++ app/public/406-unsupported-browser.html | 135 ++++++ app/public/422.html | 135 ++++++ app/public/500.html | 135 ++++++ app/public/icon.png | Bin 0 -> 4166 bytes app/public/icon.svg | 3 + app/public/robots.txt | 1 + app/script/.keep | 0 app/storage/.keep | 0 app/test/application_system_test_case.rb | 5 + app/test/controllers/.keep | 0 app/test/fixtures/files/.keep | 0 app/test/helpers/.keep | 0 app/test/integration/.keep | 0 app/test/mailers/.keep | 0 app/test/models/.keep | 0 app/test/system/.keep | 0 app/test/test_helper.rb | 15 + app/tmp/.keep | 0 app/tmp/pids/.keep | 0 app/tmp/storage/.keep | 0 app/vendor/.keep | 0 app/vendor/javascript/.keep | 0 111 files changed, 2968 insertions(+) create mode 100644 app/.dockerignore create mode 100644 app/.gitattributes create mode 100644 app/.github/dependabot.yml create mode 100644 app/.github/workflows/ci.yml create mode 100644 app/.gitignore create mode 100644 app/.kamal/hooks/docker-setup.sample create mode 100644 app/.kamal/hooks/post-app-boot.sample create mode 100644 app/.kamal/hooks/post-deploy.sample create mode 100644 app/.kamal/hooks/post-proxy-reboot.sample create mode 100644 app/.kamal/hooks/pre-app-boot.sample create mode 100644 app/.kamal/hooks/pre-build.sample create mode 100644 app/.kamal/hooks/pre-connect.sample create mode 100644 app/.kamal/hooks/pre-deploy.sample create mode 100644 app/.kamal/hooks/pre-proxy-reboot.sample create mode 100644 app/.kamal/secrets create mode 100644 app/.rubocop.yml create mode 100644 app/.ruby-version create mode 100644 app/Dockerfile create mode 100644 app/Gemfile create mode 100644 app/Gemfile.lock create mode 100644 app/Procfile.dev create mode 100644 app/README.md create mode 100644 app/Rakefile create mode 100644 app/app/assets/builds/.keep create mode 100644 app/app/assets/images/.keep create mode 100644 app/app/assets/stylesheets/application.css create mode 100644 app/app/assets/tailwind/application.css create mode 100644 app/app/controllers/application_controller.rb create mode 100644 app/app/controllers/concerns/.keep create mode 100644 app/app/helpers/application_helper.rb create mode 100644 app/app/javascript/application.js create mode 100644 app/app/javascript/controllers/application.js create mode 100644 app/app/javascript/controllers/hello_controller.js create mode 100644 app/app/javascript/controllers/index.js create mode 100644 app/app/jobs/application_job.rb create mode 100644 app/app/mailers/application_mailer.rb create mode 100644 app/app/models/application_record.rb create mode 100644 app/app/models/concerns/.keep create mode 100644 app/app/views/layouts/application.html.erb create mode 100644 app/app/views/layouts/mailer.html.erb create mode 100644 app/app/views/layouts/mailer.text.erb create mode 100644 app/app/views/pwa/manifest.json.erb create mode 100644 app/app/views/pwa/service-worker.js create mode 100644 app/bin/brakeman create mode 100644 app/bin/bundler-audit create mode 100644 app/bin/ci create mode 100644 app/bin/dev create mode 100644 app/bin/docker-entrypoint create mode 100644 app/bin/importmap create mode 100644 app/bin/jobs create mode 100644 app/bin/kamal create mode 100644 app/bin/rails create mode 100644 app/bin/rake create mode 100644 app/bin/rubocop create mode 100644 app/bin/setup create mode 100644 app/bin/thrust create mode 100644 app/config.ru create mode 100644 app/config/application.rb create mode 100644 app/config/boot.rb create mode 100644 app/config/bundler-audit.yml create mode 100644 app/config/cable.yml create mode 100644 app/config/cache.yml create mode 100644 app/config/ci.rb create mode 100644 app/config/credentials.yml.enc create mode 100644 app/config/database.yml create mode 100644 app/config/deploy.yml create mode 100644 app/config/environment.rb create mode 100644 app/config/environments/development.rb create mode 100644 app/config/environments/production.rb create mode 100644 app/config/environments/test.rb create mode 100644 app/config/importmap.rb create mode 100644 app/config/initializers/assets.rb create mode 100644 app/config/initializers/content_security_policy.rb create mode 100644 app/config/initializers/filter_parameter_logging.rb create mode 100644 app/config/initializers/inflections.rb create mode 100644 app/config/locales/en.yml create mode 100644 app/config/puma.rb create mode 100644 app/config/queue.yml create mode 100644 app/config/recurring.yml create mode 100644 app/config/routes.rb create mode 100644 app/config/storage.yml create mode 100644 app/db/cable_schema.rb create mode 100644 app/db/cache_schema.rb create mode 100644 app/db/queue_schema.rb create mode 100644 app/db/seeds.rb create mode 100644 app/lib/tasks/.keep create mode 100644 app/log/.keep create mode 100644 app/public/400.html create mode 100644 app/public/404.html create mode 100644 app/public/406-unsupported-browser.html create mode 100644 app/public/422.html create mode 100644 app/public/500.html create mode 100644 app/public/icon.png create mode 100644 app/public/icon.svg create mode 100644 app/public/robots.txt create mode 100644 app/script/.keep create mode 100644 app/storage/.keep create mode 100644 app/test/application_system_test_case.rb create mode 100644 app/test/controllers/.keep create mode 100644 app/test/fixtures/files/.keep create mode 100644 app/test/helpers/.keep create mode 100644 app/test/integration/.keep create mode 100644 app/test/mailers/.keep create mode 100644 app/test/models/.keep create mode 100644 app/test/system/.keep create mode 100644 app/test/test_helper.rb create mode 100644 app/tmp/.keep create mode 100644 app/tmp/pids/.keep create mode 100644 app/tmp/storage/.keep create mode 100644 app/vendor/.keep create mode 100644 app/vendor/javascript/.keep diff --git a/app/.dockerignore b/app/.dockerignore new file mode 100644 index 0000000000..325bfc036d --- /dev/null +++ b/app/.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/app/.gitattributes b/app/.gitattributes new file mode 100644 index 0000000000..8dc4323435 --- /dev/null +++ b/app/.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/app/.github/dependabot.yml b/app/.github/dependabot.yml new file mode 100644 index 0000000000..83610cfa4c --- /dev/null +++ b/app/.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/app/.github/workflows/ci.yml b/app/.github/workflows/ci.yml new file mode 100644 index 0000000000..4adf8d4f8b --- /dev/null +++ b/app/.github/workflows/ci.yml @@ -0,0 +1,124 @@ +name: CI + +on: + pull_request: + push: + branches: [ main ] + +jobs: + scan_ruby: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - 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@v5 + + - 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@v5 + + - 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 + + # services: + # redis: + # image: valkey/valkey:8 + # ports: + # - 6379:6379 + # options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Run tests + env: + RAILS_ENV: test + # RAILS_MASTER_KEY: ${{ secrets.RAILS_MASTER_KEY }} + # REDIS_URL: redis://localhost:6379/0 + run: bin/rails db:test:prepare test + + system-test: + runs-on: ubuntu-latest + + # services: + # redis: + # image: valkey/valkey:8 + # ports: + # - 6379:6379 + # options: --health-cmd "redis-cli ping" --health-interval 10s --health-timeout 5s --health-retries 5 + steps: + - name: Checkout code + uses: actions/checkout@v5 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Run System Tests + env: + RAILS_ENV: test + # RAILS_MASTER_KEY: ${{ secrets.RAILS_MASTER_KEY }} + # REDIS_URL: redis://localhost:6379/0 + run: bin/rails db:test:prepare test:system + + - name: Keep screenshots from failed system tests + uses: actions/upload-artifact@v4 + if: failure() + with: + name: screenshots + path: ${{ github.workspace }}/tmp/screenshots + if-no-files-found: ignore diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000000..e953825f71 --- /dev/null +++ b/app/.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 + + +/app/assets/builds/* +!/app/assets/builds/.keep diff --git a/app/.kamal/hooks/docker-setup.sample b/app/.kamal/hooks/docker-setup.sample new file mode 100644 index 0000000000..2fb07d7d7a --- /dev/null +++ b/app/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/app/.kamal/hooks/post-app-boot.sample b/app/.kamal/hooks/post-app-boot.sample new file mode 100644 index 0000000000..70f9c4bc95 --- /dev/null +++ b/app/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/app/.kamal/hooks/post-deploy.sample b/app/.kamal/hooks/post-deploy.sample new file mode 100644 index 0000000000..fd364c2a77 --- /dev/null +++ b/app/.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/app/.kamal/hooks/post-proxy-reboot.sample b/app/.kamal/hooks/post-proxy-reboot.sample new file mode 100644 index 0000000000..1435a677f2 --- /dev/null +++ b/app/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/app/.kamal/hooks/pre-app-boot.sample b/app/.kamal/hooks/pre-app-boot.sample new file mode 100644 index 0000000000..45f7355045 --- /dev/null +++ b/app/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/app/.kamal/hooks/pre-build.sample b/app/.kamal/hooks/pre-build.sample new file mode 100644 index 0000000000..c5a55678b2 --- /dev/null +++ b/app/.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/app/.kamal/hooks/pre-connect.sample b/app/.kamal/hooks/pre-connect.sample new file mode 100644 index 0000000000..77744bdca8 --- /dev/null +++ b/app/.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/app/.kamal/hooks/pre-deploy.sample b/app/.kamal/hooks/pre-deploy.sample new file mode 100644 index 0000000000..05b3055b72 --- /dev/null +++ b/app/.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/app/.kamal/hooks/pre-proxy-reboot.sample b/app/.kamal/hooks/pre-proxy-reboot.sample new file mode 100644 index 0000000000..061f8059e6 --- /dev/null +++ b/app/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/bin/sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/app/.kamal/secrets b/app/.kamal/secrets new file mode 100644 index 0000000000..b3089d6f5a --- /dev/null +++ b/app/.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/app/.rubocop.yml b/app/.rubocop.yml new file mode 100644 index 0000000000..f9d86d4a54 --- /dev/null +++ b/app/.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/app/.ruby-version b/app/.ruby-version new file mode 100644 index 0000000000..5f6fc5edc2 --- /dev/null +++ b/app/.ruby-version @@ -0,0 +1 @@ +3.3.10 diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000000..cb471caad7 --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,76 @@ +# 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 app . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name app app + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=3.3.10 +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 libyaml-dev pkg-config && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install application gems +COPY Gemfile Gemfile.lock vendor ./ + +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/app/Gemfile b/app/Gemfile new file mode 100644 index 0000000000..d2334c4cc0 --- /dev/null +++ b/app/Gemfile @@ -0,0 +1,68 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.1" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use sqlite3 as the database for Active Record +gem "sqlite3", ">= 2.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails] +gem "importmap-rails" +# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev] +gem "turbo-rails" +# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev] +gem "stimulus-rails" +# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails] +gem "tailwindcss-rails" +# 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 +end + +group :development do + # Use console on exceptions pages [https://github.com/rails/web-console] + gem "web-console" +end + +group :test do + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" +end diff --git a/app/Gemfile.lock b/app/Gemfile.lock new file mode 100644 index 0000000000..15e51e6b0c --- /dev/null +++ b/app/Gemfile.lock @@ -0,0 +1,434 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.15) + railties + actioncable (8.1.1) + actionpack (= 8.1.1) + activesupport (= 8.1.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.1) + actionpack (= 8.1.1) + activejob (= 8.1.1) + activerecord (= 8.1.1) + activestorage (= 8.1.1) + activesupport (= 8.1.1) + mail (>= 2.8.0) + actionmailer (8.1.1) + actionpack (= 8.1.1) + actionview (= 8.1.1) + activejob (= 8.1.1) + activesupport (= 8.1.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.1) + actionview (= 8.1.1) + activesupport (= 8.1.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.1) + activerecord (= 8.1.1) + activestorage (= 8.1.1) + activesupport (= 8.1.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.1) + activesupport (= 8.1.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.1) + activesupport (= 8.1.1) + globalid (>= 0.3.6) + activemodel (8.1.1) + activesupport (= 8.1.1) + activerecord (8.1.1) + activemodel (= 8.1.1) + activesupport (= 8.1.1) + timeout (>= 0.4.0) + activestorage (8.1.1) + actionpack (= 8.1.1) + activejob (= 8.1.1) + activerecord (= 8.1.1) + activesupport (= 8.1.1) + marcel (~> 1.0) + activesupport (8.1.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.8.7) + public_suffix (>= 2.0.2, < 7.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt_pbkdf (1.1.1) + bcrypt_pbkdf (1.1.1-arm64-darwin) + bcrypt_pbkdf (1.1.1-x86_64-darwin) + bigdecimal (3.3.1) + bindex (0.8.1) + bootsnap (1.19.0) + msgpack (~> 1.2) + brakeman (7.1.1) + racc + builder (3.3.0) + bundler-audit (0.9.2) + bundler (>= 1.2.0, < 3) + 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.5) + connection_pool (2.5.4) + crass (1.0.6) + date (3.5.0) + debug (1.11.0) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.1.8) + drb (2.2.3) + ed25519 (1.4.0) + erb (6.0.0) + erubi (1.13.1) + et-orbi (1.4.0) + tzinfo + ffi (1.17.2-aarch64-linux-gnu) + ffi (1.17.2-aarch64-linux-musl) + ffi (1.17.2-arm-linux-gnu) + ffi (1.17.2-arm-linux-musl) + ffi (1.17.2-arm64-darwin) + ffi (1.17.2-x86_64-darwin) + ffi (1.17.2-x86_64-linux-gnu) + ffi (1.17.2-x86_64-linux-musl) + fugit (1.12.1) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.3.0) + activesupport (>= 6.1) + i18n (1.14.7) + concurrent-ruby (~> 1.0) + image_processing (1.14.0) + mini_magick (>= 4.9.5, < 6) + ruby-vips (>= 2.0.17, < 3) + importmap-rails (2.2.2) + actionpack (>= 6.0.0) + activesupport (>= 6.0.0) + railties (>= 6.0.0) + io-console (0.8.1) + irb (1.15.3) + pp (>= 0.6.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.14.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.16.0) + kamal (2.8.2) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + language_server-protocol (3.17.0.5) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.24.1) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.0) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.1.0) + matrix (0.4.3) + mini_magick (5.3.1) + logger + mini_mime (1.1.5) + minitest (5.26.1) + msgpack (1.8.0) + net-imap (0.5.12) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.2.2) + timeout + net-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.0) + nio4r (2.7.5) + nokogiri (1.18.10-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.18.10-arm64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-darwin) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.18.10-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (1.27.0) + parser (3.3.10.0) + ast (~> 2.4.1) + racc + pp (0.6.3) + prettyprint + prettyprint (0.2.0) + prism (1.6.0) + propshaft (1.3.1) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + psych (5.2.6) + date + stringio + public_suffix (6.0.2) + puma (7.1.0) + nio4r (~> 2.0) + raabro (1.4.0) + racc (1.8.1) + rack (3.2.4) + rack-session (2.1.1) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.2.1) + rack (>= 3) + rails (8.1.1) + actioncable (= 8.1.1) + actionmailbox (= 8.1.1) + actionmailer (= 8.1.1) + actionpack (= 8.1.1) + actiontext (= 8.1.1) + actionview (= 8.1.1) + activejob (= 8.1.1) + activemodel (= 8.1.1) + activerecord (= 8.1.1) + activestorage (= 8.1.1) + activesupport (= 8.1.1) + bundler (>= 1.15.0) + railties (= 8.1.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.6.2) + loofah (~> 2.21) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.1) + actionpack (= 8.1.1) + activesupport (= 8.1.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.3.1) + rdoc (6.15.1) + erb + psych (>= 4.0.0) + tsort + regexp_parser (2.11.3) + reline (0.6.3) + io-console (~> 0.5) + rexml (3.4.4) + rubocop (1.81.7) + json (~> 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (~> 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.47.1, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.48.0) + parser (>= 3.3.7.2) + prism (~> 1.4) + rubocop-performance (1.26.1) + lint_roller (~> 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.34.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.75.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + ruby-vips (2.2.5) + ffi (~> 1.12) + logger + rubyzip (3.2.2) + securerandom (0.4.1) + selenium-webdriver (4.38.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + solid_cable (3.0.12) + 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.2.4) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sqlite3 (2.8.0-aarch64-linux-gnu) + sqlite3 (2.8.0-aarch64-linux-musl) + sqlite3 (2.8.0-arm-linux-gnu) + sqlite3 (2.8.0-arm-linux-musl) + sqlite3 (2.8.0-arm64-darwin) + sqlite3 (2.8.0-x86_64-darwin) + sqlite3 (2.8.0-x86_64-linux-gnu) + sqlite3 (2.8.0-x86_64-linux-musl) + sshkit (1.24.0) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + stimulus-rails (1.3.4) + railties (>= 6.0.0) + stringio (3.1.8) + tailwindcss-rails (4.4.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.1.16) + tailwindcss-ruby (4.1.16-aarch64-linux-gnu) + tailwindcss-ruby (4.1.16-aarch64-linux-musl) + tailwindcss-ruby (4.1.16-arm64-darwin) + tailwindcss-ruby (4.1.16-x86_64-darwin) + tailwindcss-ruby (4.1.16-x86_64-linux-gnu) + tailwindcss-ruby (4.1.16-x86_64-linux-musl) + thor (1.4.0) + thruster (0.1.16) + thruster (0.1.16-aarch64-linux) + thruster (0.1.16-arm64-darwin) + thruster (0.1.16-x86_64-darwin) + thruster (0.1.16-x86_64-linux) + timeout (0.4.4) + tsort (0.2.0) + turbo-rails (2.0.20) + actionpack (>= 7.1.0) + railties (>= 7.1.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.1.0) + uri (1.1.1) + useragent (0.16.11) + web-console (4.2.1) + actionview (>= 6.0.0) + activemodel (>= 6.0.0) + bindex (>= 0.4.0) + railties (>= 6.0.0) + websocket (1.2.11) + websocket-driver (0.8.0) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.7.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin + x86_64-darwin + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + bootsnap + brakeman + bundler-audit + capybara + debug + image_processing (~> 1.2) + importmap-rails + jbuilder + kamal + propshaft + puma (>= 5.0) + rails (~> 8.1.1) + rubocop-rails-omakase + selenium-webdriver + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + tailwindcss-rails + thruster + turbo-rails + tzinfo-data + web-console + +BUNDLED WITH + 2.5.22 diff --git a/app/Procfile.dev b/app/Procfile.dev new file mode 100644 index 0000000000..da151fee94 --- /dev/null +++ b/app/Procfile.dev @@ -0,0 +1,2 @@ +web: bin/rails server +css: bin/rails tailwindcss:watch diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000000..7db80e4ca1 --- /dev/null +++ b/app/README.md @@ -0,0 +1,24 @@ +# README + +This README would normally document whatever steps are necessary to get the +application up and running. + +Things you may want to cover: + +* Ruby version + +* System dependencies + +* Configuration + +* Database creation + +* Database initialization + +* How to run the test suite + +* Services (job queues, cache servers, search engines, etc.) + +* Deployment instructions + +* ... diff --git a/app/Rakefile b/app/Rakefile new file mode 100644 index 0000000000..9a5ea7383a --- /dev/null +++ b/app/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/app/assets/builds/.keep b/app/app/assets/builds/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/app/assets/images/.keep b/app/app/assets/images/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/app/assets/stylesheets/application.css b/app/app/assets/stylesheets/application.css new file mode 100644 index 0000000000..fe93333c0f --- /dev/null +++ b/app/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/app/assets/tailwind/application.css b/app/app/assets/tailwind/application.css new file mode 100644 index 0000000000..f1d8c73cdc --- /dev/null +++ b/app/app/assets/tailwind/application.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/app/app/controllers/application_controller.rb b/app/app/controllers/application_controller.rb new file mode 100644 index 0000000000..c3537563da --- /dev/null +++ b/app/app/controllers/application_controller.rb @@ -0,0 +1,7 @@ +class ApplicationController < ActionController::Base + # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. + allow_browser versions: :modern + + # Changes to the importmap will invalidate the etag for HTML responses + stale_when_importmap_changes +end diff --git a/app/app/controllers/concerns/.keep b/app/app/controllers/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/app/helpers/application_helper.rb b/app/app/helpers/application_helper.rb new file mode 100644 index 0000000000..de6be7945c --- /dev/null +++ b/app/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/app/javascript/application.js b/app/app/javascript/application.js new file mode 100644 index 0000000000..0d7b49404c --- /dev/null +++ b/app/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/app/javascript/controllers/application.js b/app/app/javascript/controllers/application.js new file mode 100644 index 0000000000..1213e85c7a --- /dev/null +++ b/app/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/app/javascript/controllers/hello_controller.js b/app/app/javascript/controllers/hello_controller.js new file mode 100644 index 0000000000..5975c0789d --- /dev/null +++ b/app/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/app/javascript/controllers/index.js b/app/app/javascript/controllers/index.js new file mode 100644 index 0000000000..1156bf8362 --- /dev/null +++ b/app/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/app/jobs/application_job.rb b/app/app/jobs/application_job.rb new file mode 100644 index 0000000000..d394c3d106 --- /dev/null +++ b/app/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/app/mailers/application_mailer.rb b/app/app/mailers/application_mailer.rb new file mode 100644 index 0000000000..3c34c8148f --- /dev/null +++ b/app/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/app/models/application_record.rb b/app/app/models/application_record.rb new file mode 100644 index 0000000000..b63caeb8a5 --- /dev/null +++ b/app/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/app/models/concerns/.keep b/app/app/models/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/app/views/layouts/application.html.erb b/app/app/views/layouts/application.html.erb new file mode 100644 index 0000000000..f3e935a25c --- /dev/null +++ b/app/app/views/layouts/application.html.erb @@ -0,0 +1,31 @@ + + + + <%= content_for(:title) || "App" %> + + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + <%# Enable PWA manifest for installable apps (make sure to enable in config/routes.rb too!) %> + <%#= tag.link rel: "manifest", href: pwa_manifest_path(format: :json) %> + + + + + + <%# Includes all stylesheet files in app/assets/stylesheets %> + <%= stylesheet_link_tag :app, "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + +
+ <%= yield %> +
+ + diff --git a/app/app/views/layouts/mailer.html.erb b/app/app/views/layouts/mailer.html.erb new file mode 100644 index 0000000000..3aac9002ed --- /dev/null +++ b/app/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/app/views/layouts/mailer.text.erb b/app/app/views/layouts/mailer.text.erb new file mode 100644 index 0000000000..37f0bddbd7 --- /dev/null +++ b/app/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/app/views/pwa/manifest.json.erb b/app/app/views/pwa/manifest.json.erb new file mode 100644 index 0000000000..c295730cd4 --- /dev/null +++ b/app/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "App", + "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": "App.", + "theme_color": "red", + "background_color": "red" +} diff --git a/app/app/views/pwa/service-worker.js b/app/app/views/pwa/service-worker.js new file mode 100644 index 0000000000..b3a13fb7bb --- /dev/null +++ b/app/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/bin/brakeman b/app/bin/brakeman new file mode 100644 index 0000000000..ace1c9ba08 --- /dev/null +++ b/app/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/app/bin/bundler-audit b/app/bin/bundler-audit new file mode 100644 index 0000000000..e2ef22690c --- /dev/null +++ b/app/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/app/bin/ci b/app/bin/ci new file mode 100644 index 0000000000..4137ad5bb0 --- /dev/null +++ b/app/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/app/bin/dev b/app/bin/dev new file mode 100644 index 0000000000..ad72c7d53c --- /dev/null +++ b/app/bin/dev @@ -0,0 +1,16 @@ +#!/usr/bin/env sh + +if ! gem list foreman -i --silent; then + echo "Installing foreman..." + gem install foreman +fi + +# Default to port 3000 if not specified +export PORT="${PORT:-3000}" + +# Let the debug gem allow remote connections, +# but avoid loading until `debugger` is called +export RUBY_DEBUG_OPEN="true" +export RUBY_DEBUG_LAZY="true" + +exec foreman start -f Procfile.dev "$@" diff --git a/app/bin/docker-entrypoint b/app/bin/docker-entrypoint new file mode 100644 index 0000000000..ed31659f40 --- /dev/null +++ b/app/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/app/bin/importmap b/app/bin/importmap new file mode 100644 index 0000000000..36502ab16c --- /dev/null +++ b/app/bin/importmap @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby + +require_relative "../config/application" +require "importmap/commands" diff --git a/app/bin/jobs b/app/bin/jobs new file mode 100644 index 0000000000..dcf59f309a --- /dev/null +++ b/app/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/app/bin/kamal b/app/bin/kamal new file mode 100644 index 0000000000..cbe59b95ed --- /dev/null +++ b/app/bin/kamal @@ -0,0 +1,27 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +bundle_binstub = File.expand_path("bundle", __dir__) + +if File.file?(bundle_binstub) + if File.read(bundle_binstub, 300).include?("This file was generated by Bundler") + load(bundle_binstub) + else + abort("Your `bin/bundle` was not generated by Bundler, so this binstub cannot run. +Replace `bin/bundle` by running `bundle binstubs bundler --force`, then run this command again.") + end +end + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/app/bin/rails b/app/bin/rails new file mode 100644 index 0000000000..efc0377492 --- /dev/null +++ b/app/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/app/bin/rake b/app/bin/rake new file mode 100644 index 0000000000..4fbf10b960 --- /dev/null +++ b/app/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/app/bin/rubocop b/app/bin/rubocop new file mode 100644 index 0000000000..5a20504716 --- /dev/null +++ b/app/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/app/bin/setup b/app/bin/setup new file mode 100644 index 0000000000..81be011e87 --- /dev/null +++ b/app/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/app/bin/thrust b/app/bin/thrust new file mode 100644 index 0000000000..36bde2d832 --- /dev/null +++ b/app/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/app/config.ru b/app/config.ru new file mode 100644 index 0000000000..4a3c09a688 --- /dev/null +++ b/app/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/app/config/application.rb b/app/config/application.rb new file mode 100644 index 0000000000..a7c0e56c69 --- /dev/null +++ b/app/config/application.rb @@ -0,0 +1,27 @@ +require_relative "boot" + +require "rails/all" + +# Require the gems listed in Gemfile, including any gems +# you've limited to :test, :development, or :production. +Bundler.require(*Rails.groups) + +module App + 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") + end +end diff --git a/app/config/boot.rb b/app/config/boot.rb new file mode 100644 index 0000000000..988a5ddc46 --- /dev/null +++ b/app/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/app/config/bundler-audit.yml b/app/config/bundler-audit.yml new file mode 100644 index 0000000000..e74b3af949 --- /dev/null +++ b/app/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/app/config/cable.yml b/app/config/cable.yml new file mode 100644 index 0000000000..b9adc5aa3a --- /dev/null +++ b/app/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/app/config/cache.yml b/app/config/cache.yml new file mode 100644 index 0000000000..19d490843b --- /dev/null +++ b/app/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/app/config/ci.rb b/app/config/ci.rb new file mode 100644 index 0000000000..e56a92e418 --- /dev/null +++ b/app/config/ci.rb @@ -0,0 +1,23 @@ +# 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" + + step "Tests: Rails", "bin/rails test" + step "Tests: System", "bin/rails test:system" + step "Tests: Seeds", "env RAILS_ENV=test bin/rails db:seed:replant" + + # 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/app/config/credentials.yml.enc b/app/config/credentials.yml.enc new file mode 100644 index 0000000000..0c92eb88c7 --- /dev/null +++ b/app/config/credentials.yml.enc @@ -0,0 +1 @@ +MTfpXCotsLi/o4SRIqzhTAZKU0CzJ326fPWJIFdlP60Ci2l2b7e/WmPANbuEsdop4Y/KfCY+mbPVEEY/zc9DkxopxAlRBxO5q0LTvr4fZZRP5+jwUBlY0eJBeSVWYnCMu8TR4C5A0I2iH9BSgKHPCExrPlTtkcb9tLZfWOOXJGkyg+ppdDaDh40uy9thds80CLBy0hybd3VYuoipsIH69kfnZ92kY2DoDrPdFbA0/eIUIGRZYjRRzO+O49VpU1hm1/K7v30tsUvVk/Mw79HSvtqJphR7+nx2AaaaZb9wGZg2kba7xlI8Ub1yqQPJRdAVrwKQcpWnEjtZKKt8D8Z6SFnvkfy3zlDE7NXGf3wGtIxuvCf8w+KA4D9dzscKO4KotsrRBZjY3iXSMtw7s0Uen1DVfTcX76ihPijxjgj+tTPIPsmBGEn3a3yl4j4Itvhm0/fSwVOLkKcCsN2/DUVojzYhSTNUjF+YTBENoO6EQ4uln0V1Hzzptr0V--qk9HAtHwYlFpp7nz--nceolNR7jFvtesZLazdbLg== \ No newline at end of file diff --git a/app/config/database.yml b/app/config/database.yml new file mode 100644 index 0000000000..693252b7c3 --- /dev/null +++ b/app/config/database.yml @@ -0,0 +1,41 @@ +# 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/app/config/deploy.yml b/app/config/deploy.yml new file mode 100644 index 0000000000..92e0aacd7f --- /dev/null +++ b/app/config/deploy.yml @@ -0,0 +1,120 @@ +# Name of your application. Used to uniquely configure containers. +service: app + +# Name of the container image (use your-user/app-name on external registries). +image: app + +# Deploy to these servers. +servers: + web: + - 192.168.0.1 + # job: + # hosts: + # - 192.168.0.1 + # cmd: bin/jobs + +# Enable SSL auto certification via Let's Encrypt and allow for multiple apps on a single web server. +# 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 app-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation: +# "bin/kamal logs -r job" will tail logs from the first server in the job section. +aliases: + console: app exec --interactive --reuse "bin/rails console" + shell: app exec --interactive --reuse "bash" + logs: app logs -f + dbc: app exec --interactive --reuse "bin/rails dbconsole --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: + - "app_storage:/rails/storage" + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: 3.3.10 + # 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/app/config/environment.rb b/app/config/environment.rb new file mode 100644 index 0000000000..cac5315775 --- /dev/null +++ b/app/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/app/config/environments/development.rb b/app/config/environments/development.rb new file mode 100644 index 0000000000..75243c3d0f --- /dev/null +++ b/app/config/environments/development.rb @@ -0,0 +1,78 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # 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/app/config/environments/production.rb b/app/config/environments/production.rb new file mode 100644 index 0000000000..f5763e04e5 --- /dev/null +++ b/app/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/app/config/environments/test.rb b/app/config/environments/test.rb new file mode 100644 index 0000000000..c2095b1174 --- /dev/null +++ b/app/config/environments/test.rb @@ -0,0 +1,53 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/app/config/importmap.rb b/app/config/importmap.rb new file mode 100644 index 0000000000..909dfc542d --- /dev/null +++ b/app/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/app/config/initializers/assets.rb b/app/config/initializers/assets.rb new file mode 100644 index 0000000000..487324424f --- /dev/null +++ b/app/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/app/config/initializers/content_security_policy.rb b/app/config/initializers/content_security_policy.rb new file mode 100644 index 0000000000..d51d713979 --- /dev/null +++ b/app/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/app/config/initializers/filter_parameter_logging.rb b/app/config/initializers/filter_parameter_logging.rb new file mode 100644 index 0000000000..c0b717f7ec --- /dev/null +++ b/app/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/app/config/initializers/inflections.rb b/app/config/initializers/inflections.rb new file mode 100644 index 0000000000..3860f659ea --- /dev/null +++ b/app/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/app/config/locales/en.yml b/app/config/locales/en.yml new file mode 100644 index 0000000000..6c349ae5e3 --- /dev/null +++ b/app/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/app/config/puma.rb b/app/config/puma.rb new file mode 100644 index 0000000000..38c4b86596 --- /dev/null +++ b/app/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/app/config/queue.yml b/app/config/queue.yml new file mode 100644 index 0000000000..9eace59c41 --- /dev/null +++ b/app/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/app/config/recurring.yml b/app/config/recurring.yml new file mode 100644 index 0000000000..b4207f9b07 --- /dev/null +++ b/app/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/app/config/routes.rb b/app/config/routes.rb new file mode 100644 index 0000000000..48254e88ed --- /dev/null +++ b/app/config/routes.rb @@ -0,0 +1,14 @@ +Rails.application.routes.draw do + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "rails/health#show", as: :rails_health_check + + # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) + # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker + + # Defines the root path route ("/") + # root "posts#index" +end diff --git a/app/config/storage.yml b/app/config/storage.yml new file mode 100644 index 0000000000..927dc537c8 --- /dev/null +++ b/app/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/app/db/cable_schema.rb b/app/db/cable_schema.rb new file mode 100644 index 0000000000..23666604a5 --- /dev/null +++ b/app/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/app/db/cache_schema.rb b/app/db/cache_schema.rb new file mode 100644 index 0000000000..81a410d188 --- /dev/null +++ b/app/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/app/db/queue_schema.rb b/app/db/queue_schema.rb new file mode 100644 index 0000000000..85194b6a88 --- /dev/null +++ b/app/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/app/db/seeds.rb b/app/db/seeds.rb new file mode 100644 index 0000000000..4fbd6ed970 --- /dev/null +++ b/app/db/seeds.rb @@ -0,0 +1,9 @@ +# This file should ensure the existence of records required to run the application in every environment (production, +# development, test). The code here should be idempotent so that it can be executed at any point in every environment. +# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). +# +# Example: +# +# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| +# MovieGenre.find_or_create_by!(name: genre_name) +# end diff --git a/app/lib/tasks/.keep b/app/lib/tasks/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/log/.keep b/app/log/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/public/400.html b/app/public/400.html new file mode 100644 index 0000000000..640de03397 --- /dev/null +++ b/app/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/app/public/404.html b/app/public/404.html new file mode 100644 index 0000000000..d7f0f14222 --- /dev/null +++ b/app/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/app/public/406-unsupported-browser.html b/app/public/406-unsupported-browser.html new file mode 100644 index 0000000000..43d2811e8c --- /dev/null +++ b/app/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/app/public/422.html b/app/public/422.html new file mode 100644 index 0000000000..f12fb4aa17 --- /dev/null +++ b/app/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/app/public/500.html b/app/public/500.html new file mode 100644 index 0000000000..e4eb18a759 --- /dev/null +++ b/app/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/app/public/icon.png b/app/public/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..c4c9dbfbbd2f7c1421ffd5727188146213abbcef GIT binary patch literal 4166 zcmd6qU;WFw?|v@m)Sk^&NvB8tcujdV-r1b=i(NJxn&7{KTb zX$3(M+3TP2o^#KAo{#tIjl&t~(8D-k004kqPglzn0HFG(Q~(I*AKsD#M*g7!XK0T7 zN6P7j>HcT8rZgKl$v!xr806dyN19Bd4C0x_R*I-a?#zsTvb_89cyhuC&T**i|Rc zq5b8M;+{8KvoJ~uj9`u~d_f6`V&3+&ZX9x5pc8s)d175;@pjm(?dapmBcm0&vl9+W zx1ZD2o^nuyUHWj|^A8r>lUorO`wFF;>9XL-Jy!P}UXC{(z!FO%SH~8k`#|9;Q|eue zqWL0^Bp(fg_+Pkm!fDKRSY;+^@BF?AJE zCUWpXPst~hi_~u)SzYBDZroR+Z4xeHIlm_3Yc_9nZ(o_gg!jDgVa=E}Y8uDgem9`b zf=mfJ_@(BXSkW53B)F2s!&?_R4ptb1fYXlF++@vPhd=marQgEGRZS@B4g1Mu?euknL= z67P~tZ?*>-Hmi7GwlisNHHJDku-dSm7g@!=a}9cSL6Pa^w^2?&?$Oi8ibrr>w)xqx zOH_EMU@m05)9kuNR>>4@H%|){U$^yvVQ(YgOlh;5oU_-vivG-p4=LrN-k7D?*?u1u zsWly%tfAzKd6Fb=`eU2un_uaTXmcT#tlOL+aRS=kZZf}A7qT8lvcTx~7j` z*b>=z)mwg7%B2_!D0!1IZ?Nq{^Y$uI4Qx*6T!E2Col&2{k?ImCO=dD~A&9f9diXy^$x{6CwkBimn|1E09 zAMSezYtiL?O6hS37KpvDM?22&d{l)7h-!F)C-d3j8Z`c@($?mfd{R82)H>Qe`h{~G z!I}(2j(|49{LR?w4Jspl_i!(4T{31|dqCOpI52r5NhxYV+cDAu(xp*4iqZ2e-$YP= zoFOPmm|u*7C?S{Fp43y+V;>~@FFR76bCl@pTtyB93vNWy5yf;HKr8^0d7&GVIslYm zo3Tgt@M!`8B6IW&lK{Xk>%zp41G%`(DR&^u z5^pwD4>E6-w<8Kl2DzJ%a@~QDE$(e87lNhy?-Qgep!$b?5f7+&EM7$e>|WrX+=zCb z=!f5P>MxFyy;mIRxjc(H*}mceXw5a*IpC0PEYJ8Y3{JdoIW)@t97{wcUB@u+$FCCO z;s2Qe(d~oJC^`m$7DE-dsha`glrtu&v&93IZadvl_yjp!c89>zo;Krk+d&DEG4?x$ zufC1n+c1XD7dolX1q|7}uelR$`pT0Z)1jun<39$Sn2V5g&|(j~Z!wOddfYiZo7)A< z!dK`aBHOOk+-E_xbWCA3VR-+o$i5eO9`rMI#p_0xQ}rjEpGW;U!&&PKnivOcG(|m9 z!C8?WC6nCXw25WVa*eew)zQ=h45k8jSIPbq&?VE{oG%?4>9rwEeB4&qe#?-y_es4c|7ufw%+H5EY#oCgv!Lzv291#-oNlX~X+Jl5(riC~r z=0M|wMOP)Tt8@hNg&%V@Z9@J|Q#K*hE>sr6@oguas9&6^-=~$*2Gs%h#GF@h)i=Im z^iKk~ipWJg1VrvKS;_2lgs3n1zvNvxb27nGM=NXE!D4C!U`f*K2B@^^&ij9y}DTLB*FI zEnBL6y{jc?JqXWbkIZd7I16hA>(f9T!iwbIxJj~bKPfrO;>%*5nk&Lf?G@c2wvGrY&41$W{7HM9+b@&XY@>NZM5s|EK_Dp zQX60CBuantx>|d#DsaZ*8MW(we|#KTYZ=vNa#d*DJQe6hr~J6{_rI#?wi@s|&O}FR zG$kfPxheXh1?IZ{bDT-CWB4FTvO-k5scW^mi8?iY5Q`f8JcnnCxiy@m@D-%lO;y0pTLhh6i6l@x52j=#^$5_U^os}OFg zzdHbo(QI`%9#o*r8GCW~T3UdV`szO#~)^&X_(VW>o~umY9-ns9-V4lf~j z`QBD~pJ4a#b`*6bJ^3RS5y?RAgF7K5$ll97Y8#WZduZ`j?IEY~H(s^doZg>7-tk*t z4_QE1%%bb^p~4F5SB$t2i1>DBG1cIo;2(xTaj*Y~hlM{tSDHojL-QPg%Mo%6^7FrpB*{ z4G0@T{-77Por4DCMF zB_5Y~Phv%EQ64W8^GS6h?x6xh;w2{z3$rhC;m+;uD&pR74j+i22P5DS-tE8ABvH(U~indEbBUTAAAXfHZg5QpB@TgV9eI<)JrAkOI z8!TSOgfAJiWAXeM&vR4Glh;VxH}WG&V$bVb`a`g}GSpwggti*&)taV1@Ak|{WrV|5 zmNYx)Ans=S{c52qv@+jmGQ&vd6>6yX6IKq9O$3r&0xUTdZ!m1!irzn`SY+F23Rl6# zFRxws&gV-kM1NX(3(gnKpGi0Q)Dxi~#?nyzOR9!en;Ij>YJZVFAL*=R%7y%Mz9hU% zs>+ZB?qRmZ)nISx7wxY)y#cd$iaC~{k0avD>BjyF1q^mNQ1QcwsxiTySe<6C&cC6P zE`vwO9^k-d`9hZ!+r@Jnr+MF*2;2l8WjZ}DrwDUHzSF{WoG zucbSWguA!3KgB3MU%HH`R;XqVv0CcaGq?+;v_A5A2kpmk5V%qZE3yzQ7R5XWhq=eR zyUezH=@V)y>L9T-M-?tW(PQYTRBKZSVb_!$^H-Pn%ea;!vS_?M<~Tm>_rWIW43sPW z=!lY&fWc1g7+r?R)0p8(%zp&vl+FK4HRkns%BW+Up&wK8!lQ2~bja|9bD12WrKn#M zK)Yl9*8$SI7MAwSK$%)dMd>o+1UD<2&aQMhyjS5R{-vV+M;Q4bzl~Z~=4HFj_#2V9 zB)Gfzx3ncy@uzx?yzi}6>d%-?WE}h7v*w)Jr_gBl!2P&F3DX>j_1#--yjpL%<;JMR z*b70Gr)MMIBWDo~#<5F^Q0$VKI;SBIRneuR7)yVsN~A9I@gZTXe)E?iVII+X5h0~H zx^c(fP&4>!*q>fb6dAOC?MI>Cz3kld#J*;uik+Ps49cwm1B4 zZc1|ZxYyTv;{Z!?qS=D)sgRKx^1AYf%;y_V&VgZglfU>d+Ufk5&LV$sKv}Hoj+s; xK3FZRYdhbXT_@RW*ff3@`D1#ps#~H)p+y&j#(J|vk^lW{fF9OJt5(B-_&*Xgn9~3N literal 0 HcmV?d00001 diff --git a/app/public/icon.svg b/app/public/icon.svg new file mode 100644 index 0000000000..04b34bf83f --- /dev/null +++ b/app/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/app/public/robots.txt b/app/public/robots.txt new file mode 100644 index 0000000000..c19f78ab68 --- /dev/null +++ b/app/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/app/script/.keep b/app/script/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/storage/.keep b/app/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/application_system_test_case.rb b/app/test/application_system_test_case.rb new file mode 100644 index 0000000000..cee29fd214 --- /dev/null +++ b/app/test/application_system_test_case.rb @@ -0,0 +1,5 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 1400 ] +end diff --git a/app/test/controllers/.keep b/app/test/controllers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/fixtures/files/.keep b/app/test/fixtures/files/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/helpers/.keep b/app/test/helpers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/integration/.keep b/app/test/integration/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/mailers/.keep b/app/test/mailers/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/models/.keep b/app/test/models/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/system/.keep b/app/test/system/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/test/test_helper.rb b/app/test/test_helper.rb new file mode 100644 index 0000000000..0c22470ec1 --- /dev/null +++ b/app/test/test_helper.rb @@ -0,0 +1,15 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" +require "rails/test_help" + +module ActiveSupport + class TestCase + # Run tests in parallel with specified workers + parallelize(workers: :number_of_processors) + + # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. + fixtures :all + + # Add more helper methods to be used by all tests here... + end +end diff --git a/app/tmp/.keep b/app/tmp/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/tmp/pids/.keep b/app/tmp/pids/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/tmp/storage/.keep b/app/tmp/storage/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/vendor/.keep b/app/vendor/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/vendor/javascript/.keep b/app/vendor/javascript/.keep new file mode 100644 index 0000000000..e69de29bb2 From a80bf514c376bd636df463a903abec80f7a03c8c Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Mon, 17 Nov 2025 20:27:40 -0300 Subject: [PATCH 02/19] =?UTF-8?q?:memo:=20docs:=20adi=C3=A7=C3=A3o=20do=20?= =?UTF-8?q?.txt=20e=20do=20wiki?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- sprint1.txt | 7 ++++ wiki.md | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+) create mode 100644 sprint1.txt create mode 100644 wiki.md diff --git a/sprint1.txt b/sprint1.txt new file mode 100644 index 0000000000..3ff4192ca8 --- /dev/null +++ b/sprint1.txt @@ -0,0 +1,7 @@ +Grupo composto por: +- Caio Medeiros Balaniuk - 231025190 +- Davi Henrique Vieira Lima - 231013529 +- Lucca Schoen de Almeida - 231018900 + +Link para o repositório do GitHub: +https://github.com/DaviHVL/CAMAAR.git diff --git a/wiki.md b/wiki.md new file mode 100644 index 0000000000..ca094af35a --- /dev/null +++ b/wiki.md @@ -0,0 +1,105 @@ +# Wiki da Sprint 1 - CAMAAR + +## 1. Informações Gerais + +### Resumo +A aplicação **CAMAAR** consiste em um sistema desenvolvido com o framework *Ruby on Rails* para fins acadêmicos. Essa aplicação facilita a gestão, coleta e análise de formulários de avaliação acerca de disciplinas ofertadas pela Universidade de Brasília (UnB), que podem ser respondidos tanto por alunos quanto por professores + +### Integrantes + +| Nome Completo | Matrícula | +|---------------|-----------| +| Caio Medeiros Balaniuk | 231025190 | +| Davi Henrique Vieira Lima | 231013529 | +| Lucca Schoen de Almeida | 231018900 | + +## 2. Papéis da Equipe (Scrum) + +**Product Owner (PO):** Davi Henrique Vieira Lima +**Scrum Master (SM):** Lucca Schoen de Almeida + +## 3. Funcionalidades Desenvolvidas (Histórias de Usuário) + +As funcionalidades desenvolvidas foram estabelecidas com base nas histórias de usuário apresentadas nas issues. Desse modo, a seguir temos as funcionalidades com suas respectivas pontuações e regras de negócio: + +| Issue | Funcionalidade | Descrição / Regras de Negócio (Resumo) | Responsável | Pontos | +|:---:|---|---|---|:---:| +| **098** | Importar dados do SIGAA | Deve ler CSV/JSON do SIGAA e popular o banco. Validar duplicidade. | Lucca | 5 | +| **099** | Responder formulário | Permitir que usuário logado envie respostas. | Caio | 3 | +| **100** | Cadastrar usuários do sistema | CRUD de usuários. Deve exigir email válido. | Davi | 3 | +| **101** | Gerar relatório do administrador | Compilar dados de avaliações em formato visual/exportável para o Admin. | Davi | 5 | +| **102** | Criar template de formulário | Permitir criação de perguntas para avaliações. | Caio | 8 | +| **103** | Criar formulário de avaliação | Instanciar um formulário a partir de um template para uma disciplina. | Lucca | 5 | +| **104** | Sistema de login | Autenticação via email/senha. Bloquear acesso sem login. | Davi | 5 | +| **105** | Sistema de definição de senha | Fluxo de criação ou recuperação de senha segura. | Caio | 3 | +| **108** | Atualizar base com dados do SIGAA | Sincronização de dados existentes. Não deve sobrescrever dados manuais. | Lucca | 3 | +| **109** | Visualização de forms (Responder) | Listagem de formulários pendentes disponíveis para o usuário atual. | Davi | 3 | +| **110** | Visualização de resultados | Exibição gráfica ou tabular das respostas coletadas (apenas Admin/Prof). | Caio | 5 | +| **111** | Visualização dos templates criados | Listagem de todos os templates com opções de gestão. | Davi | 2 | +| **112** | Edição e deleção de templates | Alterar perguntas de templates. A deleção não deve alterar formulários já instanciados. | Lucca | 5 | + +## 4. Política de Branching + +Para garantir a rastreabilidade do código e a organização durante os ciclos de desenvolvimento, estabelecemos as seguintes diretrizes técnicas para commits, nomeação de branches e fluxo de trabalho. + +## 4.1. Convenções de Commits +Tanto as mensagens de commit quanto os nomes das branches compartilham os seguintes prefixos: +* `feat`: Para novas funcionalidades. + +* `fix`: Para correção de bugs. + +* `refactor`: Para refatoração de código + +* `test`: Para criação ou alteração de testes + +* `docs`: Para documentação + +Os commits devem ser atômicos e descritivos, seguindo o formato: + + `{prefixo}: {mensagem com verbo na 3ª pessoa do presente}` + +As branches devem ser nomeadas em **kebab-case**, sempre categorizadas pelo prefixo da tarefa: + + `{prefixo}/{nome-da-branch}` + +## 4.2. Estratégia de Branching (Fluxo de Trabalho) + +Adotamos um modelo híbrido focado em Sprints, garantindo que a branch principal (`main`) permaneça estável. Contendo, assim, as seguintes características: +- **`main`**: A fonte da verdade e versão estável do projeto +- **Branch da Sprint** (ex: `sprint-1`, `sprint-2`): Uma branch intermediária, criada a cada ciclo, para inserir os arquivos obrigatórios da entrega. +- **Branches de Tarefa** (Features/Fixes): Branches individuais criadas pelos desenvolvedores para modificações específicas + +Com base nisso, o ciclo de desenvolvimento é dado por: + +1. **Criação**: Cada membro cria uma branch para sua tarefa específica (ex: `feat/form-creation`), partindo da branch correta (geralmente a branch da Sprint atual ou `main`, conforme o início do ciclo) + +2. **Desenvolvimento e Merge**: Ao concluir a tarefa, o desenvolvedor não faz o merge direto na `main`. O código deve ser fundido na Branch da Sprint vigente + +3. **Quality Assurance**: Para que o merge seja aceito na branch da Sprint, é obrigatório: + - Abrir um Pull Request + - Passar nos testes automáticos + - Obter a aprovação de pelo menos 1 revisor + +4. **Finalização**: Apenas ao encerrar a sprint, a "Branch da Sprint" (com todas as features acumuladas e testadas) será fundida via Pull Request na branch `main` + +## 5. Pontuação (Velocity) + +A equipe atribuiu pontos (Story Points) para cada história de usuário especificada nesta sprint, para o cálculo da métrica velocity. + +| História de Usuário (Feature) | Pontos (Story Points) | +|-------------------------------|----------------------:| +| Importar dados do SIGAA | 5 | +| Responder formulário | 3 | +| Cadastrar usuários do sistema | 3 | +| Gerar relatório do administrador | 5 | +| Criar template de formulário | 8 | +| Criar formulário de avaliação | 5 | +| Sistema de login | 5 | +| Sistema de definição de senha | 3 | +| Atualizar base de dados com os dados do SIGAA | 3 | +| Visualização de formulários para responder | 3 | +| Visualização de resultados dos formulários | 5 | +| Visualização dos templates criados | 2 | +| Edição e deleção de templates | 5 | + +**Velocity Total Planejada (Sprint 1):** 55 \ No newline at end of file From b9763738949bd2481b4ddae690490925c9e6613f Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Tue, 18 Nov 2025 21:50:08 -0300 Subject: [PATCH 03/19] feat: adicionando BDDs --- features/atualizar_base_de_dados.feature | 27 +++++++++ features/autenticacao_usuario.feature | 58 +++++++++++++++++++ features/criacao_de_template.feature | 45 ++++++++++++++ ...iar_formulario_baseado_em_template.feature | 44 ++++++++++++++ features/criar_formulario_para_turma.feature | 40 +++++++++++++ .../definir_senha_primeiro_acesso.feature | 39 +++++++++++++ features/download_resultados_csv.feature | 32 ++++++++++ features/editar_deletar_template.feature | 31 ++++++++++ .../gerenciar_turmas_do_departamento.feature | 37 ++++++++++++ features/importar_dados_sigaa.feature | 41 +++++++++++++ features/importar_participantes_sigaa.feature | 40 +++++++++++++ features/redefinir_senha.feature | 50 ++++++++++++++++ features/responder_questionario_turma.feature | 42 ++++++++++++++ features/visualizar_formularios.feature | 31 ++++++++++ ...alizar_formularios_nao_respondidos.feature | 32 ++++++++++ features/visualizar_templates.feature | 32 ++++++++++ 16 files changed, 621 insertions(+) create mode 100644 features/atualizar_base_de_dados.feature create mode 100644 features/autenticacao_usuario.feature create mode 100644 features/criacao_de_template.feature create mode 100644 features/criar_formulario_baseado_em_template.feature create mode 100644 features/criar_formulario_para_turma.feature create mode 100644 features/definir_senha_primeiro_acesso.feature create mode 100644 features/download_resultados_csv.feature create mode 100644 features/editar_deletar_template.feature create mode 100644 features/gerenciar_turmas_do_departamento.feature create mode 100644 features/importar_dados_sigaa.feature create mode 100644 features/importar_participantes_sigaa.feature create mode 100644 features/redefinir_senha.feature create mode 100644 features/responder_questionario_turma.feature create mode 100644 features/visualizar_formularios.feature create mode 100644 features/visualizar_formularios_nao_respondidos.feature create mode 100644 features/visualizar_templates.feature diff --git a/features/atualizar_base_de_dados.feature b/features/atualizar_base_de_dados.feature new file mode 100644 index 0000000000..d172afd66f --- /dev/null +++ b/features/atualizar_base_de_dados.feature @@ -0,0 +1,27 @@ +Feature: Atualização da base de dados com informações do SIGAA + Como Administrador + Quero atualizar a base de dados já existente com os dados atuais do SIGAA + A fim de corrigir a base de dados do sistema + + Background: + Given que existe um administrador autenticado + + Scenario: Atualizar base de dados com sucesso + Given que o sistema está conectado à integração com o SIGAA + When o administrador acessa a funcionalidade de atualização de dados + And solicita a atualização da base + Then o sistema deve buscar os dados atuais no SIGAA + And atualizar a base de dados local com as informações recebidas + And exibir uma mensagem de sucesso informando que a atualização foi concluída + + Scenario: Falha na comunicação com o SIGAA + Given que o sistema não consegue acessar o SIGAA + When o administrador solicita a atualização da base + Then o sistema deve informar que não foi possível se conectar ao SIGAA + And exibir uma mensagem orientando a tentar novamente mais tarde + + Scenario: Dados recebidos estão incompletos ou inconsistentes + Given que o SIGAA retorna dados inconsistentes ou incompletos + When o administrador solicita a atualização da base + Then o sistema deve impedir a atualização + And exibir uma mensagem indicando o problema nos dados recebidos \ No newline at end of file diff --git a/features/autenticacao_usuario.feature b/features/autenticacao_usuario.feature new file mode 100644 index 0000000000..81a33390d3 --- /dev/null +++ b/features/autenticacao_usuario.feature @@ -0,0 +1,58 @@ +Feature: Autenticação de usuário no sistema + 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 + + Background: + Given que existem usuários cadastrados no sistema + And que alguns usuários possuem perfil de administrador + And que outros usuários possuem perfil de participante + + Scenario: Login com e-mail válido e senha correta + When o usuário acessa a página de login + And informa um e-mail válido cadastrado no sistema + And informa a senha correta correspondente + Then o sistema deve autenticar o usuário + And deve redirecioná-lo para a página inicial do sistema + + Scenario: Login com matrícula válida e senha correta + When o usuário acessa a página de login + And informa uma matrícula válida cadastrada no sistema + And informa a senha correta correspondente + Then o sistema deve autenticar o usuário + And deve redirecioná-lo para a página inicial do sistema + + Scenario: Exibir opção de gerenciamento para administrador + Given que o usuário autenticado possui perfil de administrador + When o usuário acessa o sistema após o login + Then o sistema deve exibir no menu lateral a opção de gerenciamento + + Scenario: Não exibir opção de gerenciamento para usuário comum + Given que o usuário autenticado não é administrador + When o usuário acessa o sistema após o login + Then o sistema não deve exibir a opção de gerenciamento no menu lateral + + Scenario: Login com senha incorreta + When o usuário acessa a página de login + And informa um e-mail ou matrícula válida + And informa uma senha incorreta + Then o sistema deve negar o acesso + And exibir uma mensagem informando que a senha está incorreta + + Scenario: Login com usuário inexistente + When o usuário acessa a página de login + And informa um e-mail ou matrícula que não está cadastrada + Then o sistema deve negar o acesso + And exibir uma mensagem informando que o usuário não foi encontrado + + Scenario: Tentativa de login com campos vazios + When o usuário tenta realizar login sem preencher e-mail/matrícula ou senha + Then o sistema deve impedir o login + And exibir uma mensagem informando que os campos são obrigatórios + + Scenario: Erro inesperado ao tentar autenticar + When o usuário tenta fazer login + And ocorre um erro interno inesperado + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o usuário a tentar novamente mais tarde + diff --git a/features/criacao_de_template.feature b/features/criacao_de_template.feature new file mode 100644 index 0000000000..c32142d1a3 --- /dev/null +++ b/features/criacao_de_template.feature @@ -0,0 +1,45 @@ +Feature: Criação de template de formulário + Como Administrador + Quero criar um template de formulário contendo as questões do formulário + A fim de gerar formulários de avaliações para avaliar o desempenho das turmas + + Background: + Given que o administrador está autenticado no sistema + And que o administrador possui permissão para gerenciar templates + + Scenario: Criar template com título e questões válidas + When o administrador acessa a página de criação de templates + And informa um título válido para o template + And adiciona uma ou mais questões válidas + And confirma a criação do template + Then o sistema deve salvar o template + And deve exibir uma mensagem confirmando a criação com sucesso + + Scenario: Criar template sem informar título + When o administrador acessa a página de criação de templates + And não informa um título + And tenta confirmar a criação + Then o sistema deve impedir a criação do template + And deve exibir uma mensagem informando que o título é obrigatório + + Scenario: Criar template sem adicionar questões + When o administrador acessa a página de criação de templates + And informa um título válido + And não adiciona nenhuma questão + And tenta confirmar a criação + Then o sistema deve impedir a criação do template + And deve exibir uma mensagem informando que é necessário adicionar ao menos uma questão + + Scenario: Criar template com questões inválidas ou duplicadas + When o administrador acessa a página de criação de templates + And informa um título válido + And adiciona questões inválidas ou duplicadas + And tenta confirmar a criação + Then o sistema deve impedir a criação + And deve exibir uma mensagem informando que existem questões inválidas ou duplicadas + + Scenario: Erro inesperado ao criar template + When o administrador tenta confirmar a criação do template + And ocorre um erro interno inesperado + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o administrador a tentar novamente mais tarde diff --git a/features/criar_formulario_baseado_em_template.feature b/features/criar_formulario_baseado_em_template.feature new file mode 100644 index 0000000000..aebee914b7 --- /dev/null +++ b/features/criar_formulario_baseado_em_template.feature @@ -0,0 +1,44 @@ +Feature: Criação de formulário a partir de um template + Como Administrador + Quero criar um formulário baseado em um template para as turmas que eu escolher + A fim de avaliar o desempenho das turmas no semestre atual + + Background: + Given que existem templates cadastrados no sistema + And que existem turmas disponíveis para o administrador + And que o administrador está autenticado no sistema + + Scenario: Criar formulário com um template válido para múltiplas turmas + When o administrador acessa a página de criação de formulários + And seleciona um template válido da lista de templates disponíveis + And seleciona uma ou mais turmas válidas + And confirma a criação do formulário + Then o sistema deve criar um formulário para cada turma selecionada + And deve exibir uma mensagem confirmando a criação com sucesso + + Scenario: Criar formulário sem selecionar template + When o administrador acessa a página de criação de formulários + And não seleciona nenhum template + And tenta confirmar a criação do formulário + Then o sistema deve impedir a criação + And deve exibir uma mensagem informando que a seleção de template é obrigatória + + Scenario: Criar formulário sem selecionar turmas + When o administrador acessa a página de criação de formulários + And seleciona um template válido + And não seleciona nenhuma turma + And tenta confirmar a criação + Then o sistema deve impedir a criação + And deve exibir uma mensagem informando que é necessário selecionar ao menos uma turma + + Scenario: Criar formulário com template inexistente + When o administrador tenta criar um formulário + And seleciona um template que não existe mais ou foi removido + Then o sistema deve impedir a criação + And deve exibir uma mensagem informando que o template selecionado é inválido + + Scenario: Erro inesperado ao criar formulário + When o administrador tenta confirmar a criação do formulário + And ocorre um erro interno inesperado + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o administrador a tentar novamente mais tarde diff --git a/features/criar_formulario_para_turma.feature b/features/criar_formulario_para_turma.feature new file mode 100644 index 0000000000..eda2ab043a --- /dev/null +++ b/features/criar_formulario_para_turma.feature @@ -0,0 +1,40 @@ +Feature: Criação de formulário para docentes ou discentes + Como Administrador + Quero escolher criar um formulário para os docentes ou os discentes de uma turma + A fim de avaliar o desempenho de uma matéria + + Background: + Given que existe um administrador autenticado + And que existe ao menos uma turma cadastrada no sistema + + Scenario: Criar formulário para docentes de uma turma + When o administrador acessa a página de criação de formulário + And seleciona um template + And seleciona a turma desejada + And escolhe criar um formulário destinado aos docentes + And confirma a criação do formulário + Then o sistema deve registrar o formulário associado aos docentes da turma selecionada + And exibir uma mensagem de sucesso + + Scenario: Criar formulário para discentes de uma turma + When o administrador acessa a página de criação de formulário + And seleciona um template + And seleciona a turma desejada + And escolhe criar um formulário destinado aos discentes + And confirma a criação do formulário + Then o sistema deve registrar o formulário associado aos discentes da turma selecionada + And exibir uma mensagem de sucesso + + Scenario: Criar formulário sem selecionar uma turma + When o administrador acessa a página de criação de formulário + And não seleciona nenhuma turma + And tenta prosseguir com a criação + Then o sistema deve impedir a criação do formulário + And exibir uma mensagem informando que a turma é obrigatória + + Scenario: Criar formulário sem definir template + When o administrador seleciona a turma desejada + And escolhe criar um formulário para docentes ou discentes + And não define um template + And tenta finalizar a criação + Then o sistema deve exibir uma mensagem indicando que o formulário precisa ter conteúdo diff --git a/features/definir_senha_primeiro_acesso.feature b/features/definir_senha_primeiro_acesso.feature new file mode 100644 index 0000000000..857e2e694f --- /dev/null +++ b/features/definir_senha_primeiro_acesso.feature @@ -0,0 +1,39 @@ +Feature: Definição de senha para o usuário a partir do e-mail do sistema de solicitação de cadastro + 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 + + Background: + Given que o usuário possui um cadastro pendente de ativação + And que o sistema enviou um e-mail contendo um link para definição de senha + + Scenario: Acessar link de definição de senha com sucesso + When o usuário clica no link recebido por e-mail + Then o sistema deve exibir a página para criação da senha inicial + And o link deve ser validado como autêntico e dentro do prazo de validade + + Scenario: Definir senha inicial com sucesso + Given que o usuário está na página de criação de senha + When o usuário informa uma senha válida + And confirma a senha corretamente + Then o sistema deve registrar a nova senha + And ativar o cadastro do usuário + And exibir uma mensagem informando que o acesso foi liberado + + Scenario: Senhas não coincidem + Given que o usuário está na página de criação de senha + When o usuário informa uma senha e uma confirmação que não coincidem + Then o sistema deve impedir a criação da senha + And exibir uma mensagem informando que as senhas devem ser iguais + + Scenario: Senha não atende aos critérios mínimos + Given que o usuário está na página de criação de senha + When o usuário informa uma senha que não atende às regras + Then o sistema deve impedir a criação da senha + And exibir uma mensagem explicando os critérios obrigatórios + + Scenario: Usuário já definiu a senha anteriormente + Given que o usuário já ativou sua conta e definiu uma senha previamente + When tenta acessar novamente o link de definição de senha + Then o sistema deve bloquear a ação + And exibir uma mensagem informando que a conta já foi ativada \ No newline at end of file diff --git a/features/download_resultados_csv.feature b/features/download_resultados_csv.feature new file mode 100644 index 0000000000..ae19a73817 --- /dev/null +++ b/features/download_resultados_csv.feature @@ -0,0 +1,32 @@ +Feature: Download dos resultados de um formulário em CSV + Como Administrador + Quero baixar um arquivo CSV contendo os resultados de um formulário + A fim de avaliar o desempenho das turmas + + Background: + Given que o administrador está autenticado no sistema + And que existem formulários já respondidos pelas turmas + And que o administrador possui permissão para visualizar os resultados + + Scenario: Download bem-sucedido do arquivo CSV + When o administrador acessa a página de resultados de um formulário + And solicita o download do arquivo CSV + Then o sistema deve gerar o arquivo CSV contendo todas as respostas do formulário + And deve iniciar automaticamente o download do arquivo + + Scenario: Tentar baixar CSV de formulário sem respostas + Given que o formulário selecionado não possui respostas registradas + When o administrador solicita o download do arquivo CSV + Then o sistema deve impedir a geração do arquivo + And deve exibir uma mensagem informando que o formulário não possui respostas + + Scenario: Tentar baixar CSV de um formulário inexistente + When o administrador tenta acessar os resultados de um formulário que não existe mais + And solicita o download do arquivo CSV + Then o sistema deve exibir uma mensagem informando que o formulário é inválido ou não encontrado + + Scenario: Erro inesperado ao gerar o CSV + When o administrador solicita o download do arquivo CSV + And ocorre um erro interno inesperado durante a geração do arquivo + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o administrador a tentar novamente mais tarde diff --git a/features/editar_deletar_template.feature b/features/editar_deletar_template.feature new file mode 100644 index 0000000000..a131b77f82 --- /dev/null +++ b/features/editar_deletar_template.feature @@ -0,0 +1,31 @@ +Feature: Edição e exclusão de templates + Como Administrador + Quero editar e/ou deletar um template que eu criei sem afetar os formulários já criados + A fim de organizar os templates existentes + + Background: + Given que existe um administrador autenticado + And que existe um template previamente criado pelo administrador + + Scenario: Editar um template com sucesso + When o administrador acessa a lista de templates + And seleciona a opção de editar um template existente + And realiza alterações válidas no template + And confirma a edição + Then o sistema deve salvar o template atualizado + And os formulários já criados a partir desse template não devem ser alterados + And o sistema deve exibir uma mensagem de sucesso + + Scenario: Editar um template com dados inválidos + When o administrador tenta editar um template + And insere informações inválidas ou incompletas + Then o sistema deve impedir a edição + And exibir uma mensagem de erro indicando o problema + + Scenario: Deletar um template com sucesso + When o administrador acessa a lista de templates + And seleciona a opção de deletar um template existente + And confirma a exclusão do template + Then o sistema deve remover o template da lista + And os formulários já criados a partir do template removido devem permanecer intactos + And o sistema deve exibir uma mensagem de sucesso diff --git a/features/gerenciar_turmas_do_departamento.feature b/features/gerenciar_turmas_do_departamento.feature new file mode 100644 index 0000000000..71f5efc3e1 --- /dev/null +++ b/features/gerenciar_turmas_do_departamento.feature @@ -0,0 +1,37 @@ +Feature: Gerenciamento de turmas por departamento + Como Administrador + Quero gerenciar somente as turmas do departamento ao qual eu pertenço + A fim de avaliar o desempenho das turmas no semestre atual + + Background: + Given que existe um administrador autenticado + And que o administrador pertence a um departamento específico + And que existem turmas cadastradas em vários departamentos + + Scenario: Visualizar apenas as turmas do próprio departamento + When o administrador acessa a página de gerenciamento de turmas + Then o sistema deve exibir somente as turmas pertencentes ao departamento do administrador + And não deve exibir turmas de outros departamentos + + Scenario: Tentar acessar turma de outro departamento + Given que existe uma turma de outro departamento + When o administrador tenta acessar os detalhes dessa turma + Then o sistema deve negar o acesso + And deve exibir uma mensagem informando permissão insuficiente + + Scenario: Gerenciar turmas do próprio departamento + Given que existem turmas vinculadas ao departamento do administrador + When o administrador seleciona uma turma da lista + Then o sistema deve permitir visualizar dados da turma + And deve permitir ações como gerar relatórios, visualizar formulários ou acompanhar desempenho + + Scenario: Não há turmas no departamento do administrador + Given que o departamento do administrador não possui turmas cadastradas para o semestre atual + When o administrador acessa a página de gerenciamento de turmas + Then o sistema deve informar que não existem turmas disponíveis para o departamento + + Scenario: Usuário não autenticado tenta acessar gerenciamento de turmas + Given que o usuário não está autenticado + When tenta acessar a página de gerenciamento de turmas + Then o sistema deve negar o acesso + And exibir uma mensagem informando que a autenticação é necessária diff --git a/features/importar_dados_sigaa.feature b/features/importar_dados_sigaa.feature new file mode 100644 index 0000000000..4a92bfb2d9 --- /dev/null +++ b/features/importar_dados_sigaa.feature @@ -0,0 +1,41 @@ +Feature: Importação de dados do SIGAA + Como Administrador + Quero importar dados de turmas, matérias e participantes do SIGAA (caso não existam na base de dados atual) + A fim de alimentar a base de dados do sistema + + Background: + Given que o administrador está autenticado no sistema + And que o administrador possui permissão para importar dados do SIGAA + And que os arquivos seguem o formato esperado pelo sistema + + Scenario: Importar dados válidos de turmas, matérias e participantes + When o administrador acessa a página de importação de dados do SIGAA + And seleciona os arquivos válidos presentes no repositório + And confirma a importação + Then o sistema deve importar as turmas que ainda não existem na base + And deve importar as matérias que ainda não existem na base + And deve importar os participantes que ainda não existem na base + And deve exibir uma mensagem confirmando a importação com sucesso + + Scenario: Importar dados onde alguns itens já existem na base + Given que algumas turmas, matérias ou participantes já estão cadastrados no sistema + When o administrador realiza a importação dos arquivos + Then o sistema deve ignorar os itens duplicados + And deve cadastrar apenas os dados novos + And deve exibir uma mensagem informando que alguns dados já existiam na base + + Scenario: Tentar importar arquivos inválidos + When o administrador tenta importar arquivos que não seguem o formato esperado + Then o sistema deve impedir a importação + And deve exibir uma mensagem informando que o arquivo é inválido + + Scenario: Tentar importar arquivos vazios + When o administrador seleciona vazios para importação + Then o sistema deve impedir a importação + And deve exibir uma mensagem informando que os arquivos não contêm dados + + Scenario: Erro inesperado durante a importação + When o administrador confirma a importação dos arquivos + And ocorre um erro interno inesperado + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o administrador a tentar novamente mais tarde diff --git a/features/importar_participantes_sigaa.feature b/features/importar_participantes_sigaa.feature new file mode 100644 index 0000000000..8e3385a832 --- /dev/null +++ b/features/importar_participantes_sigaa.feature @@ -0,0 +1,40 @@ +Feature: Importação de participantes de turmas do SIGAA + 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 + + Background: + Given que o administrador está autenticado no sistema + And que o administrador possui permissão para importar dados do SIGAA + And que o sistema possui integração com os dados exportados do SIGAA + + Scenario: Importar arquivo válido com novos participantes + When o administrador acessa a página de importação de usuários + And seleciona um arquivo válido exportado do SIGAA + And confirma a importação + Then o sistema deve cadastrar os novos participantes + And deve associá-los corretamente às suas respectivas turmas + And deve exibir uma mensagem confirmando a importação com sucesso + + Scenario: Importar arquivo contendo usuários já cadastrados + Given que alguns usuários presentes no arquivo já existem no sistema + When o administrador realiza a importação do arquivo + Then o sistema deve ignorar os usuários duplicados + And deve cadastrar somente os usuários novos + And deve exibir uma mensagem informando que alguns usuários já estavam cadastrados + + Scenario: Tentar importar arquivo com formato inválido + When o administrador tenta importar um arquivo que não segue o formato esperado do SIGAA + Then o sistema deve impedir a importação + And deve exibir uma mensagem informando que o arquivo é inválido + + Scenario: Tentar importar arquivo vazio + When o administrador seleciona um arquivo vazio para importação + Then o sistema deve impedir a importação + And deve exibir uma mensagem informando que o arquivo não contém dados + + Scenario: Erro inesperado durante a importação + When o administrador confirma a importação de um arquivo + And ocorre um erro interno inesperado + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o administrador a tentar novamente mais tarde diff --git a/features/redefinir_senha.feature b/features/redefinir_senha.feature new file mode 100644 index 0000000000..933d0270a3 --- /dev/null +++ b/features/redefinir_senha.feature @@ -0,0 +1,50 @@ +Feature: Redefinição de senha via e-mail + Como Usuário + Quero redefinir minha senha a partir do e-mail recebido após a solicitação + A fim de recuperar meu acesso ao sistema + + Background: + Given que o usuário possui um cadastro válido no sistema + + Scenario: Solicitar redefinição de senha com sucesso + When o usuário acessa a página de recuperação de senha + And informa um e-mail válido associado à sua conta + Then o sistema deve enviar um e-mail contendo um link para redefinição de senha + And deve exibir uma mensagem informando que o e-mail foi enviado + + Scenario: Solicitar redefinição com e-mail não cadastrado + When o usuário acessa a página de recuperação de senha + And informa um e-mail que não está cadastrado no sistema + Then o sistema deve exibir uma mensagem informando que o e-mail não foi encontrado + And não deve enviar nenhum link de redefinição + + Scenario: Acessar link de redefinição válido + Given que o usuário recebeu o e-mail de recuperação com um link válido + When o usuário clica no link de redefinição dentro do prazo de validade + Then o sistema deve exibir a página de criação de nova senha + + Scenario: Redefinir senha com sucesso + Given que o usuário está na página de redefinição de senha + When o usuário informa uma nova senha válida + And confirma a nova senha corretamente + Then o sistema deve atualizar a senha do usuário + And deve exibir uma mensagem de sucesso + And o usuário deve poder acessar o sistema com a nova senha + + Scenario: Link de redefinição expirado + Given que o usuário recebeu o e-mail, mas o link já expirou + When o usuário tenta acessar o link de redefinição + Then o sistema deve informar que o link não é mais válido + And deve instruir o usuário a solicitar um novo link + + Scenario: Erro ao redefinir devido a senhas não coincidentes + Given que o usuário está na página de redefinição de senha + When o usuário informa uma senha e uma confirmação que não coincidem + Then o sistema deve impedir a atualização + And exibir uma mensagem informando que as senhas devem ser iguais + + Scenario: Usuário tenta redefinir senha com critérios inválidos + Given que o usuário está na página de redefinição de senha + When o usuário informa uma senha que não atende aos requisitos mínimos + Then o sistema deve impedir a redefinição + And exibir uma mensagem explicando as regras de senha diff --git a/features/responder_questionario_turma.feature b/features/responder_questionario_turma.feature new file mode 100644 index 0000000000..f96dde6f5e --- /dev/null +++ b/features/responder_questionario_turma.feature @@ -0,0 +1,42 @@ +Feature: Responder questionário da turma + Como Participante de uma turma + Quero responder o questionário sobre a turma em que estou matriculado + A fim de submeter minha avaliação da turma + + Background: + Given que o participante está autenticado no sistema + And que o participante está matriculado em uma ou mais turmas + + Scenario: Responder questionário com todas as respostas válidas + Given que existem formulários pendentes de resposta para as turmas do participante + When o participante acessa a lista de formulários pendentes + And seleciona um formulário de uma turma + And responde todas as questões obrigatórias com respostas válidas + And envia o questionário + Then o sistema deve registrar as respostas + And deve exibir uma mensagem confirmando o envio com sucesso + + Scenario: Tentar enviar o questionário com questões obrigatórias em branco + Given que existe um formulário pendente + When o participante o acessa + And deixa uma ou mais questões obrigatórias sem resposta + And tenta enviar o questionário + Then o sistema deve impedir o envio + And deve exibir uma mensagem informando que todas as questões obrigatórias devem ser respondidas + + Scenario: Tentar responder um formulário já respondido + Given que o participante já respondeu o formulário da turma + When o participante tenta acessá-lo novamente + Then o sistema deve impedir o acesso + And deve exibir uma mensagem informando que o formulário já foi respondido + + Scenario: Tentar responder um formulário de turma não matriculada + When o participante tenta acessar um formulário que não pertence às suas turmas + Then o sistema deve negar o acesso + And deve exibir uma mensagem informando que o formulário não está disponível + + Scenario: Erro inesperado ao enviar respostas + Given que existe um problema interno inesperado no sistema + When o participante tenta enviar o formulário + Then o sistema deve exibir uma mensagem genérica de erro + And instruir o participante a tentar novamente mais tarde diff --git a/features/visualizar_formularios.feature b/features/visualizar_formularios.feature new file mode 100644 index 0000000000..2d9e3a00fc --- /dev/null +++ b/features/visualizar_formularios.feature @@ -0,0 +1,31 @@ +Feature: Visualização de formulários criados + Como Administrador + Quero visualizar os formulários criados + A fim de poder gerar um relatório a partir das respostas + + Background: + Given que existe um administrador autenticado + + Scenario: Visualizar lista de formulários com sucesso + Given que existem formulários cadastrados no sistema + When o administrador acessa a página de formulários + Then o sistema deve exibir a lista de formulários existentes + And cada formulário deve exibir informações como nome, turma e data de criação + And cada formulário deve apresentar uma opção para gerar relatório + + Scenario: Visualizar lista de formulários vazia + Given que não existem formulários cadastrados no sistema + When o administrador acessa a página de formulários + Then o sistema deve informar que não há formulários disponíveis + + Scenario: Acessar detalhes de um formulário específico + Given que existe ao menos um formulário cadastrado + When o administrador seleciona um formulário na lista + Then o sistema deve exibir as informações completas do formulário + And deve disponibilizar uma opção para gerar o relatório a partir das respostas + + Scenario: Tentar acessar lista de formulários sem estar autenticado + Given que o usuário não está autenticado como administrador + When ele tenta acessar a página de formulários + Then o sistema deve negar o acesso + And exibir uma mensagem informando que a autenticação é necessária \ No newline at end of file diff --git a/features/visualizar_formularios_nao_respondidos.feature b/features/visualizar_formularios_nao_respondidos.feature new file mode 100644 index 0000000000..aee9953666 --- /dev/null +++ b/features/visualizar_formularios_nao_respondidos.feature @@ -0,0 +1,32 @@ +Feature: Visualização de formulários não respondidos pelo participante + Como Participante de uma turma + Quero visualizar os formulários não respondidos das turmas em que estou matriculado + A fim de poder escolher qual irei responder + + Background: + Given que existe um participante autenticado + And que o participante está matriculado em uma ou mais turmas + + Scenario: Visualizar formulários não respondidos com sucesso + Given que existem formulários disponíveis e não respondidos nas turmas do participante + When o participante acessa a página de formulários pendentes + Then o sistema deve exibir a lista de formulários não respondidos + And cada formulário deve mostrar informações como nome, turma e prazo (se houver) + And cada formulário deve apresentar uma opção para iniciar a resposta + + Scenario: Não há formulários pendentes + Given que o participante já respondeu todos os formulários disponíveis nas turmas em que está matriculado + When o participante acessa a página de formulários pendentes + Then o sistema deve informar que não existem formulários pendentes de resposta + + Scenario: Participante tenta acessar página sem estar autenticado + Given que o usuário não está autenticado + When o usuário tenta acessar a página de formulários pendentes + Then o sistema deve negar o acesso + And exibir uma mensagem informando que a autenticação é necessária + + Scenario: Erro ao carregar formulários pendentes + Given que existe um problema temporário no carregamento das informações + When o participante acessa a página de formulários pendentes + Then o sistema deve exibir uma mensagem de erro + And instruir o usuário a tentar novamente mais tarde \ No newline at end of file diff --git a/features/visualizar_templates.feature b/features/visualizar_templates.feature new file mode 100644 index 0000000000..14c6b7327a --- /dev/null +++ b/features/visualizar_templates.feature @@ -0,0 +1,32 @@ +Feature: Visualização de templates criados + Como Administrador + Quero visualizar os templates criados + A fim de poder editar e/ou deletar um template que eu criei + + # Cenários que exigem autenticação do administrador + Background: + Given que existe um administrador autenticado + + Scenario: Visualizar lista de templates com sucesso + Given que existem templates cadastrados no sistema + When o administrador acessa a página de templates + Then o sistema deve exibir a lista de templates existentes + And cada template deve apresentar opções para edição e exclusão + + Scenario: Visualizar lista de templates vazia + Given que não existem templates cadastrados no sistema + When o administrador acessa a página de templates + Then o sistema deve informar que não há templates disponíveis + + Scenario: Acessar detalhes de um template + Given que existe ao menos um template cadastrado + When o administrador seleciona um template da lista + Then o sistema deve exibir os detalhes do template + And deve disponibilizar opções para editar ou deletar o template + + # Cenário sem Background, pois não envolve administrador autenticado + Scenario: Tentar acessar lista de templates sem estar autenticado + Given que o usuário não está autenticado como administrador + When ele tenta acessar a página de templates + Then o sistema deve negar o acesso + And exibir uma mensagem indicando falta de permissão \ No newline at end of file From 1570455546f522b2d04410b740c4fe43d8efe66f Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 7 Dec 2025 08:45:48 -0300 Subject: [PATCH 04/19] =?UTF-8?q?:sparkles:=20feat:=20implementa=C3=A7?= =?UTF-8?q?=C3=A3o=20do=20sistema=20de=20login=20do=20usu=C3=A1rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/.rspec | 1 + app/Gemfile | 8 +- app/Gemfile.lock | 35 +++++++ .../components/brand_panel_component.html.erb | 7 ++ app/app/components/brand_panel_component.rb | 3 + app/app/components/button_component.html.erb | 3 + app/app/components/button_component.rb | 19 ++++ .../components/form_input_component.html.erb | 12 +++ app/app/components/form_input_component.rb | 9 ++ app/app/controllers/application_controller.rb | 14 ++- app/app/controllers/sessions_controller.rb | 21 +++++ app/app/helpers/sessions_helper.rb | 2 + app/app/models/usuario.rb | 7 ++ app/app/views/layouts/application.html.erb | 4 +- app/app/views/sessions/new.html.erb | 56 +++++++++++ app/config/routes.rb | 15 +-- .../migrate/20251207014407_create_usuarios.rb | 13 +++ app/db/schema.rb | 23 +++++ app/spec/features/login_spec.rb | 40 ++++++++ app/spec/rails_helper.rb | 72 ++++++++++++++ app/spec/spec_helper.rb | 94 +++++++++++++++++++ .../controllers/sessions_controller_test.rb | 7 ++ app/test/fixtures/usuarios.yml | 15 +++ app/test/models/usuario_test.rb | 7 ++ 24 files changed, 468 insertions(+), 19 deletions(-) create mode 100644 app/.rspec create mode 100644 app/app/components/brand_panel_component.html.erb create mode 100644 app/app/components/brand_panel_component.rb create mode 100644 app/app/components/button_component.html.erb create mode 100644 app/app/components/button_component.rb create mode 100644 app/app/components/form_input_component.html.erb create mode 100644 app/app/components/form_input_component.rb create mode 100644 app/app/controllers/sessions_controller.rb create mode 100644 app/app/helpers/sessions_helper.rb create mode 100644 app/app/models/usuario.rb create mode 100644 app/app/views/sessions/new.html.erb create mode 100644 app/db/migrate/20251207014407_create_usuarios.rb create mode 100644 app/db/schema.rb create mode 100644 app/spec/features/login_spec.rb create mode 100644 app/spec/rails_helper.rb create mode 100644 app/spec/spec_helper.rb create mode 100644 app/test/controllers/sessions_controller_test.rb create mode 100644 app/test/fixtures/usuarios.yml create mode 100644 app/test/models/usuario_test.rb diff --git a/app/.rspec b/app/.rspec new file mode 100644 index 0000000000..c99d2e7396 --- /dev/null +++ b/app/.rspec @@ -0,0 +1 @@ +--require spec_helper diff --git a/app/Gemfile b/app/Gemfile index d2334c4cc0..99962a2c75 100644 --- a/app/Gemfile +++ b/app/Gemfile @@ -20,7 +20,7 @@ gem "tailwindcss-rails" gem "jbuilder" # Use Active Model has_secure_password [https://guides.rubyonrails.org/active_model_basics.html#securepassword] -# gem "bcrypt", "~> 3.1.7" +gem "bcrypt", "~> 3.1.7" # Windows does not include zoneinfo files, so bundle the tzinfo-data gem gem "tzinfo-data", platforms: %i[ windows jruby ] @@ -66,3 +66,9 @@ group :test do gem "capybara" gem "selenium-webdriver" end + +group :development, :test do + gem 'rspec-rails' +end + +gem "view_component", "~> 4.1" diff --git a/app/Gemfile.lock b/app/Gemfile.lock index 15e51e6b0c..a115fba9ac 100644 --- a/app/Gemfile.lock +++ b/app/Gemfile.lock @@ -79,8 +79,10 @@ GEM public_suffix (>= 2.0.2, < 7.0) ast (2.4.3) base64 (0.3.0) + bcrypt (3.1.20) bcrypt_pbkdf (1.1.1) bcrypt_pbkdf (1.1.1-arm64-darwin) + bcrypt_pbkdf (1.1.1-x64-mingw-ucrt) bcrypt_pbkdf (1.1.1-x86_64-darwin) bigdecimal (3.3.1) bindex (0.8.1) @@ -108,6 +110,7 @@ GEM debug (1.11.0) irb (~> 1.10) reline (>= 0.3.8) + diff-lcs (1.6.2) dotenv (3.1.8) drb (2.2.3) ed25519 (1.4.0) @@ -120,6 +123,7 @@ GEM ffi (1.17.2-arm-linux-gnu) ffi (1.17.2-arm-linux-musl) ffi (1.17.2-arm64-darwin) + ffi (1.17.2-x64-mingw-ucrt) ffi (1.17.2-x86_64-darwin) ffi (1.17.2-x86_64-linux-gnu) ffi (1.17.2-x86_64-linux-musl) @@ -201,6 +205,8 @@ GEM racc (~> 1.4) nokogiri (1.18.10-arm64-darwin) racc (~> 1.4) + nokogiri (1.18.10-x64-mingw-ucrt) + racc (~> 1.4) nokogiri (1.18.10-x86_64-darwin) racc (~> 1.4) nokogiri (1.18.10-x86_64-linux-gnu) @@ -276,6 +282,23 @@ GEM 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.7) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.13.0) + rspec-rails (8.0.2) + actionpack (>= 7.2) + activesupport (>= 7.2) + railties (>= 7.2) + rspec-core (~> 3.13) + rspec-expectations (~> 3.13) + rspec-mocks (~> 3.13) + rspec-support (~> 3.13) + rspec-support (3.13.6) rubocop (1.81.7) json (~> 2.3) language_server-protocol (~> 3.17.0.2) @@ -337,6 +360,7 @@ GEM sqlite3 (2.8.0-arm-linux-gnu) sqlite3 (2.8.0-arm-linux-musl) sqlite3 (2.8.0-arm64-darwin) + sqlite3 (2.8.0-x64-mingw-ucrt) sqlite3 (2.8.0-x86_64-darwin) sqlite3 (2.8.0-x86_64-linux-gnu) sqlite3 (2.8.0-x86_64-linux-musl) @@ -357,6 +381,7 @@ GEM tailwindcss-ruby (4.1.16-aarch64-linux-gnu) tailwindcss-ruby (4.1.16-aarch64-linux-musl) tailwindcss-ruby (4.1.16-arm64-darwin) + tailwindcss-ruby (4.1.16-x64-mingw-ucrt) tailwindcss-ruby (4.1.16-x86_64-darwin) tailwindcss-ruby (4.1.16-x86_64-linux-gnu) tailwindcss-ruby (4.1.16-x86_64-linux-musl) @@ -373,11 +398,17 @@ GEM railties (>= 7.1.0) tzinfo (2.0.6) concurrent-ruby (~> 1.0) + tzinfo-data (1.2025.2) + tzinfo (>= 1.0.0) unicode-display_width (3.2.0) unicode-emoji (~> 4.1) unicode-emoji (4.1.0) uri (1.1.1) useragent (0.16.11) + view_component (4.1.1) + actionview (>= 7.1.0, < 8.2) + activesupport (>= 7.1.0, < 8.2) + concurrent-ruby (~> 1) web-console (4.2.1) actionview (>= 6.0.0) activemodel (>= 6.0.0) @@ -399,12 +430,14 @@ PLATFORMS arm-linux-gnu arm-linux-musl arm64-darwin + x64-mingw-ucrt x86_64-darwin x86_64-linux x86_64-linux-gnu x86_64-linux-musl DEPENDENCIES + bcrypt (~> 3.1.7) bootsnap brakeman bundler-audit @@ -417,6 +450,7 @@ DEPENDENCIES propshaft puma (>= 5.0) rails (~> 8.1.1) + rspec-rails rubocop-rails-omakase selenium-webdriver solid_cable @@ -428,6 +462,7 @@ DEPENDENCIES thruster turbo-rails tzinfo-data + view_component (~> 4.1) web-console BUNDLED WITH diff --git a/app/app/components/brand_panel_component.html.erb b/app/app/components/brand_panel_component.html.erb new file mode 100644 index 0000000000..7f960321c7 --- /dev/null +++ b/app/app/components/brand_panel_component.html.erb @@ -0,0 +1,7 @@ +
+

+ Bem vindo
+ ao + Camaar +

+
\ No newline at end of file diff --git a/app/app/components/brand_panel_component.rb b/app/app/components/brand_panel_component.rb new file mode 100644 index 0000000000..8347a523ef --- /dev/null +++ b/app/app/components/brand_panel_component.rb @@ -0,0 +1,3 @@ +# app/components/brand_panel_component.rb +class BrandPanelComponent < ViewComponent::Base +end \ No newline at end of file diff --git a/app/app/components/button_component.html.erb b/app/app/components/button_component.html.erb new file mode 100644 index 0000000000..8e1aa8b7ea --- /dev/null +++ b/app/app/components/button_component.html.erb @@ -0,0 +1,3 @@ + \ No newline at end of file diff --git a/app/app/components/button_component.rb b/app/app/components/button_component.rb new file mode 100644 index 0000000000..bd2adb3ee0 --- /dev/null +++ b/app/app/components/button_component.rb @@ -0,0 +1,19 @@ +# app/components/button_component.rb +class ButtonComponent < ViewComponent::Base + def initialize(text:, type: :submit, variant: :primary) + @text = text + @type = type + @variant = variant + end + + def classes + base = "w-full py-3 px-4 rounded text-sm font-medium focus:outline-none transition duration-150 shadow-sm" + + case @variant + when :primary + "#{base} bg-[#22C55E] hover:bg-green-600 text-white" + else + "#{base} bg-gray-500 hover:bg-gray-700 text-white" + end + end +end \ No newline at end of file diff --git a/app/app/components/form_input_component.html.erb b/app/app/components/form_input_component.html.erb new file mode 100644 index 0000000000..4903e9838c --- /dev/null +++ b/app/app/components/form_input_component.html.erb @@ -0,0 +1,12 @@ +
+ + +
\ No newline at end of file diff --git a/app/app/components/form_input_component.rb b/app/app/components/form_input_component.rb new file mode 100644 index 0000000000..5630c71970 --- /dev/null +++ b/app/app/components/form_input_component.rb @@ -0,0 +1,9 @@ +# app/components/form_input_component.rb +class FormInputComponent < ViewComponent::Base + def initialize(label:, name:, type: :text, placeholder: "") + @label = label + @name = name + @type = type + @placeholder = placeholder + end +end \ No newline at end of file diff --git a/app/app/controllers/application_controller.rb b/app/app/controllers/application_controller.rb index c3537563da..fad99c6ec9 100644 --- a/app/app/controllers/application_controller.rb +++ b/app/app/controllers/application_controller.rb @@ -1,7 +1,11 @@ class ApplicationController < ActionController::Base - # Only allow modern browsers supporting webp images, web push, badges, import maps, CSS nesting, and CSS :has. - allow_browser versions: :modern + helper_method :current_user, :logged_in? - # Changes to the importmap will invalidate the etag for HTML responses - stale_when_importmap_changes -end + def current_user + @current_user ||= Usuario.find(session[:user_id]) if session[:user_id] + end + + def logged_in? + !!current_user + end +end \ No newline at end of file diff --git a/app/app/controllers/sessions_controller.rb b/app/app/controllers/sessions_controller.rb new file mode 100644 index 0000000000..1b5cfc241a --- /dev/null +++ b/app/app/controllers/sessions_controller.rb @@ -0,0 +1,21 @@ +class SessionsController < ApplicationController + def new + + end + + def create + user = Usuario.find_by(email: params[:email]) + if user && user.authenticate(params[:password]) + session[:user_id] = user.id + redirect_to root_path, notice: 'Logado com sucesso!' + else + flash.now[:alert] = 'Email ou senha inválidos' + render :new, status: :unprocessable_entity + end + end + + def destroy + session[:user_id] = nil + redirect_to login_path, notice: 'Deslogado.' + end +end \ No newline at end of file diff --git a/app/app/helpers/sessions_helper.rb b/app/app/helpers/sessions_helper.rb new file mode 100644 index 0000000000..309f8b2eb3 --- /dev/null +++ b/app/app/helpers/sessions_helper.rb @@ -0,0 +1,2 @@ +module SessionsHelper +end diff --git a/app/app/models/usuario.rb b/app/app/models/usuario.rb new file mode 100644 index 0000000000..ae4d220cff --- /dev/null +++ b/app/app/models/usuario.rb @@ -0,0 +1,7 @@ +class Usuario < ApplicationRecord + has_secure_password + + validates :email, presence: true, uniqueness: true + validates :matricula, presence: true, uniqueness: true + validates :nome, presence: true +end \ No newline at end of file diff --git a/app/app/views/layouts/application.html.erb b/app/app/views/layouts/application.html.erb index f3e935a25c..440a69e8db 100644 --- a/app/app/views/layouts/application.html.erb +++ b/app/app/views/layouts/application.html.erb @@ -23,8 +23,8 @@ <%= javascript_importmap_tags %> - -
+ +
<%= yield %>
diff --git a/app/app/views/sessions/new.html.erb b/app/app/views/sessions/new.html.erb new file mode 100644 index 0000000000..4272016e45 --- /dev/null +++ b/app/app/views/sessions/new.html.erb @@ -0,0 +1,56 @@ +
+ +
+ +
+ +

LOGIN

+ + <%# --- INICIO DA ALTERAÇÃO --- %> + <%# Adicionamos este bloco para exibir mensagens de sucesso (verde) %> + <% if flash[:notice] %> +
+ <%= flash[:notice] %> +
+ <% end %> + <%# --- FIM DA ALTERAÇÃO --- %> + + <% if flash[:alert] %> +
+ <%= flash[:alert] %> +
+ <% end %> + + <%= form_with url: login_path, local: true, class: "space-y-6" do |form| %> + + <%= render(FormInputComponent.new( + label: "Email", + name: "email", + type: :email, + placeholder: "aluno@aluno.unb.br" + )) %> + + <%= render(FormInputComponent.new( + label: "Senha", + name: "password", + type: :password, + placeholder: "Password" + )) %> + +
+ <%= render(ButtonComponent.new( + text: "Entrar", + type: :submit, + variant: :primary + )) %> +
+ + <% end %> +
+ + + +
+
\ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index 48254e88ed..ad8cb0c77d 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -1,14 +1,7 @@ Rails.application.routes.draw do - # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + get 'login', to: 'sessions#new' + post 'login', to: 'sessions#create' + delete 'logout', to: 'sessions#destroy' - # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. - # Can be used by load balancers and uptime monitors to verify that the app is live. - get "up" => "rails/health#show", as: :rails_health_check - - # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) - # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest - # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker - - # Defines the root path route ("/") - # root "posts#index" + root to: 'sessions#new' end diff --git a/app/db/migrate/20251207014407_create_usuarios.rb b/app/db/migrate/20251207014407_create_usuarios.rb new file mode 100644 index 0000000000..162a90b695 --- /dev/null +++ b/app/db/migrate/20251207014407_create_usuarios.rb @@ -0,0 +1,13 @@ +class CreateUsuarios < ActiveRecord::Migration[8.1] + def change + create_table :usuarios do |t| + t.string :email + t.string :password_digest + t.string :nome + t.string :matricula + t.boolean :is_admin + + t.timestamps + end + end +end diff --git a/app/db/schema.rb b/app/db/schema.rb new file mode 100644 index 0000000000..8fdb836c08 --- /dev/null +++ b/app/db/schema.rb @@ -0,0 +1,23 @@ +# 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: 2025_12_07_014407) do + create_table "usuarios", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "email" + t.boolean "is_admin" + t.string "matricula" + t.string "nome" + t.string "password_digest" + t.datetime "updated_at", null: false + end +end diff --git a/app/spec/features/login_spec.rb b/app/spec/features/login_spec.rb new file mode 100644 index 0000000000..e627e8769a --- /dev/null +++ b/app/spec/features/login_spec.rb @@ -0,0 +1,40 @@ +# spec/system/login_spec.rb +require 'rails_helper' + +RSpec.describe "Autenticação", type: :system do + before do + # Garante que as rotas e componentes carreguem corretamente + driven_by(:rack_test) + end + + it "permite que um usuário existente faça login com sucesso" do + # 1. PREPARAR (Cria o dado no banco) + Usuario.create!( + nome: "Aluno Teste", + email: "aluno@unb.br", + password: "password123", + matricula: "231013529" + ) + + # 2. AGIR (Simula o navegador) + visit login_path + + fill_in "Email", with: "aluno@unb.br" + fill_in "Senha", with: "password123" + click_button "Entrar" + + # 3. VERIFICAR (Expectativas) + expect(page).to have_content("Logado com sucesso!") + expect(current_path).to eq(root_path) + end + + it "exibe erro com credenciais inválidas" do + visit login_path + + fill_in "Email", with: "errado@unb.br" + fill_in "Senha", with: "senhaerrada" + click_button "Entrar" + + expect(page).to have_content("Email ou senha inválidos") + end +end \ No newline at end of file diff --git a/app/spec/rails_helper.rb b/app/spec/rails_helper.rb new file mode 100644 index 0000000000..79811b8f6b --- /dev/null +++ b/app/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 this 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/app/spec/spec_helper.rb b/app/spec/spec_helper.rb new file mode 100644 index 0000000000..327b58ea1f --- /dev/null +++ b/app/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/app/test/controllers/sessions_controller_test.rb b/app/test/controllers/sessions_controller_test.rb new file mode 100644 index 0000000000..e5da4b3f3a --- /dev/null +++ b/app/test/controllers/sessions_controller_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class SessionsControllerTest < ActionDispatch::IntegrationTest + # test "the truth" do + # assert true + # end +end diff --git a/app/test/fixtures/usuarios.yml b/app/test/fixtures/usuarios.yml new file mode 100644 index 0000000000..c973c6a0f9 --- /dev/null +++ b/app/test/fixtures/usuarios.yml @@ -0,0 +1,15 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html + +one: + email: MyString + password_digest: MyString + nome: MyString + matricula: MyString + is_admin: false + +two: + email: MyString + password_digest: MyString + nome: MyString + matricula: MyString + is_admin: false diff --git a/app/test/models/usuario_test.rb b/app/test/models/usuario_test.rb new file mode 100644 index 0000000000..532e35097c --- /dev/null +++ b/app/test/models/usuario_test.rb @@ -0,0 +1,7 @@ +require "test_helper" + +class UsuarioTest < ActiveSupport::TestCase + # test "the truth" do + # assert true + # end +end From 7fc86d1375d76e90a8a0cdfd89a779d8f3dcbb18 Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 7 Dec 2025 16:09:25 -0300 Subject: [PATCH 05/19] =?UTF-8?q?:sparkles:=20feat:=20implementa=C3=A7?= =?UTF-8?q?=C3=A3o=20da=20importa=C3=A7=C3=A3o=20de=20dados=20de=20turmas,?= =?UTF-8?q?=20mat=C3=A9rias=20e=20participantes=20do=20SIGAA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/models/departamento.rb | 3 + app/app/models/formulario.rb | 2 + app/app/models/formulario_respondido.rb | 4 + app/app/models/formulario_turma.rb | 4 + app/app/models/materia.rb | 4 + app/app/models/opcao_formulario.rb | 3 + app/app/models/opcao_template.rb | 3 + app/app/models/questao_formulario.rb | 3 + app/app/models/questao_respondida.rb | 5 + app/app/models/questao_template.rb | 3 + app/app/models/template.rb | 3 + app/app/models/turma.rb | 5 + app/app/models/usuario.rb | 2 + app/app/models/usuario_turma.rb | 4 + app/app/services/sigaa_service.rb | 83 +++++++++++ .../20251207183251_create_departamentos.rb | 9 ++ .../migrate/20251207183254_create_materia.rb | 11 ++ .../migrate/20251207183255_create_turmas.rb | 11 ++ .../20251207183257_create_usuario_turmas.rb | 10 ++ .../20251207183258_create_templates.rb | 10 ++ ...20251207183300_create_questao_templates.rb | 11 ++ .../20251207183302_create_opcao_templates.rb | 11 ++ .../20251207183303_create_formularios.rb | 10 ++ ...20251207183305_create_formulario_turmas.rb | 10 ++ ...251207183307_create_questao_formularios.rb | 11 ++ ...20251207183309_create_opcao_formularios.rb | 11 ++ ...207183310_create_formulario_respondidos.rb | 10 ++ ...251207183312_create_questao_respondidas.rb | 12 ++ ...20251207190733_add_ocupacao_to_usuarios.rb | 5 + app/db/schema.rb | 134 +++++++++++++++++- app/spec/models/departamento_spec.rb | 5 + app/spec/models/formulario_respondido_spec.rb | 5 + app/spec/models/formulario_spec.rb | 5 + app/spec/models/formulario_turma_spec.rb | 5 + app/spec/models/materium_spec.rb | 5 + app/spec/models/opcao_formulario_spec.rb | 5 + app/spec/models/opcao_template_spec.rb | 5 + app/spec/models/questao_formulario_spec.rb | 5 + app/spec/models/questao_respondida_spec.rb | 5 + app/spec/models/questao_template_spec.rb | 5 + app/spec/models/template_spec.rb | 5 + app/spec/models/turma_spec.rb | 5 + app/spec/models/usuario_turma_spec.rb | 5 + app/spec/services/sigaa_service_spec.rb | 77 ++++++++++ 44 files changed, 548 insertions(+), 1 deletion(-) create mode 100644 app/app/models/departamento.rb create mode 100644 app/app/models/formulario.rb create mode 100644 app/app/models/formulario_respondido.rb create mode 100644 app/app/models/formulario_turma.rb create mode 100644 app/app/models/materia.rb create mode 100644 app/app/models/opcao_formulario.rb create mode 100644 app/app/models/opcao_template.rb create mode 100644 app/app/models/questao_formulario.rb create mode 100644 app/app/models/questao_respondida.rb create mode 100644 app/app/models/questao_template.rb create mode 100644 app/app/models/template.rb create mode 100644 app/app/models/turma.rb create mode 100644 app/app/models/usuario_turma.rb create mode 100644 app/app/services/sigaa_service.rb create mode 100644 app/db/migrate/20251207183251_create_departamentos.rb create mode 100644 app/db/migrate/20251207183254_create_materia.rb create mode 100644 app/db/migrate/20251207183255_create_turmas.rb create mode 100644 app/db/migrate/20251207183257_create_usuario_turmas.rb create mode 100644 app/db/migrate/20251207183258_create_templates.rb create mode 100644 app/db/migrate/20251207183300_create_questao_templates.rb create mode 100644 app/db/migrate/20251207183302_create_opcao_templates.rb create mode 100644 app/db/migrate/20251207183303_create_formularios.rb create mode 100644 app/db/migrate/20251207183305_create_formulario_turmas.rb create mode 100644 app/db/migrate/20251207183307_create_questao_formularios.rb create mode 100644 app/db/migrate/20251207183309_create_opcao_formularios.rb create mode 100644 app/db/migrate/20251207183310_create_formulario_respondidos.rb create mode 100644 app/db/migrate/20251207183312_create_questao_respondidas.rb create mode 100644 app/db/migrate/20251207190733_add_ocupacao_to_usuarios.rb create mode 100644 app/spec/models/departamento_spec.rb create mode 100644 app/spec/models/formulario_respondido_spec.rb create mode 100644 app/spec/models/formulario_spec.rb create mode 100644 app/spec/models/formulario_turma_spec.rb create mode 100644 app/spec/models/materium_spec.rb create mode 100644 app/spec/models/opcao_formulario_spec.rb create mode 100644 app/spec/models/opcao_template_spec.rb create mode 100644 app/spec/models/questao_formulario_spec.rb create mode 100644 app/spec/models/questao_respondida_spec.rb create mode 100644 app/spec/models/questao_template_spec.rb create mode 100644 app/spec/models/template_spec.rb create mode 100644 app/spec/models/turma_spec.rb create mode 100644 app/spec/models/usuario_turma_spec.rb create mode 100644 app/spec/services/sigaa_service_spec.rb diff --git a/app/app/models/departamento.rb b/app/app/models/departamento.rb new file mode 100644 index 0000000000..78b6c81e96 --- /dev/null +++ b/app/app/models/departamento.rb @@ -0,0 +1,3 @@ +class Departamento < ApplicationRecord + has_many :materias +end diff --git a/app/app/models/formulario.rb b/app/app/models/formulario.rb new file mode 100644 index 0000000000..50413ca5ea --- /dev/null +++ b/app/app/models/formulario.rb @@ -0,0 +1,2 @@ +class Formulario < ApplicationRecord +end diff --git a/app/app/models/formulario_respondido.rb b/app/app/models/formulario_respondido.rb new file mode 100644 index 0000000000..c857092ef6 --- /dev/null +++ b/app/app/models/formulario_respondido.rb @@ -0,0 +1,4 @@ +class FormularioRespondido < ApplicationRecord + belongs_to :formulario + belongs_to :usuario +end diff --git a/app/app/models/formulario_turma.rb b/app/app/models/formulario_turma.rb new file mode 100644 index 0000000000..06cda79278 --- /dev/null +++ b/app/app/models/formulario_turma.rb @@ -0,0 +1,4 @@ +class FormularioTurma < ApplicationRecord + belongs_to :formulario + belongs_to :turma +end diff --git a/app/app/models/materia.rb b/app/app/models/materia.rb new file mode 100644 index 0000000000..d90ad44ef1 --- /dev/null +++ b/app/app/models/materia.rb @@ -0,0 +1,4 @@ +class Materia < ApplicationRecord + belongs_to :departamento + has_many :turmas +end diff --git a/app/app/models/opcao_formulario.rb b/app/app/models/opcao_formulario.rb new file mode 100644 index 0000000000..bcfc029d2c --- /dev/null +++ b/app/app/models/opcao_formulario.rb @@ -0,0 +1,3 @@ +class OpcaoFormulario < ApplicationRecord + belongs_to :questao_formulario +end diff --git a/app/app/models/opcao_template.rb b/app/app/models/opcao_template.rb new file mode 100644 index 0000000000..e986955a3a --- /dev/null +++ b/app/app/models/opcao_template.rb @@ -0,0 +1,3 @@ +class OpcaoTemplate < ApplicationRecord + belongs_to :questao_template +end diff --git a/app/app/models/questao_formulario.rb b/app/app/models/questao_formulario.rb new file mode 100644 index 0000000000..4a1219b494 --- /dev/null +++ b/app/app/models/questao_formulario.rb @@ -0,0 +1,3 @@ +class QuestaoFormulario < ApplicationRecord + belongs_to :formulario +end diff --git a/app/app/models/questao_respondida.rb b/app/app/models/questao_respondida.rb new file mode 100644 index 0000000000..60ab813764 --- /dev/null +++ b/app/app/models/questao_respondida.rb @@ -0,0 +1,5 @@ +class QuestaoRespondida < ApplicationRecord + belongs_to :formulario_respondido + belongs_to :questao_formulario + belongs_to :opcao_formulario +end diff --git a/app/app/models/questao_template.rb b/app/app/models/questao_template.rb new file mode 100644 index 0000000000..cab4b68abf --- /dev/null +++ b/app/app/models/questao_template.rb @@ -0,0 +1,3 @@ +class QuestaoTemplate < ApplicationRecord + belongs_to :template +end diff --git a/app/app/models/template.rb b/app/app/models/template.rb new file mode 100644 index 0000000000..e86b7d70ad --- /dev/null +++ b/app/app/models/template.rb @@ -0,0 +1,3 @@ +class Template < ApplicationRecord + belongs_to :usuario +end diff --git a/app/app/models/turma.rb b/app/app/models/turma.rb new file mode 100644 index 0000000000..23b8de558e --- /dev/null +++ b/app/app/models/turma.rb @@ -0,0 +1,5 @@ +class Turma < ApplicationRecord + belongs_to :materia + has_many :usuario_turmas + has_many :usuarios, through: :usuario_turmas +end \ No newline at end of file diff --git a/app/app/models/usuario.rb b/app/app/models/usuario.rb index ae4d220cff..e8f39fb5f5 100644 --- a/app/app/models/usuario.rb +++ b/app/app/models/usuario.rb @@ -4,4 +4,6 @@ class Usuario < ApplicationRecord validates :email, presence: true, uniqueness: true validates :matricula, presence: true, uniqueness: true validates :nome, presence: true + has_many :usuario_turmas + has_many :turmas, through: :usuario_turmas end \ No newline at end of file diff --git a/app/app/models/usuario_turma.rb b/app/app/models/usuario_turma.rb new file mode 100644 index 0000000000..e52b052318 --- /dev/null +++ b/app/app/models/usuario_turma.rb @@ -0,0 +1,4 @@ +class UsuarioTurma < ApplicationRecord + belongs_to :usuario + belongs_to :turma +end diff --git a/app/app/services/sigaa_service.rb b/app/app/services/sigaa_service.rb new file mode 100644 index 0000000000..50709a8d75 --- /dev/null +++ b/app/app/services/sigaa_service.rb @@ -0,0 +1,83 @@ +require 'json' + +class SigaaService + def initialize(classes_path, members_path) + @classes_path = classes_path + @members_path = members_path + end + + def call + import_classes if File.exist?(@classes_path) + + import_members if File.exist?(@members_path) + end + + private + + def import_classes + file_content = File.read(@classes_path) + data = JSON.parse(file_content) + + data.each do |entry| + dept_code = entry['code'][0..2] + + departamento = Departamento.find_or_create_by!(nome: dept_code) # Usando o código como nome provisório + + materia = Materia.find_or_create_by!(codigo: entry['code']) do |m| + m.nome = entry['name'] + m.departamento = departamento + end + + Turma.find_or_create_by!( + num_turma: entry['class']['classCode'], + semestre: entry['class']['semester'], + materia: materia + ) + end + end + + def import_members + file_content = File.read(@members_path) + data = JSON.parse(file_content) + + data.each do |entry| + materia = Materia.find_by(codigo: entry['code']) + next unless materia # Pula se a matéria não existir + + turma = Turma.find_by( + num_turma: entry['classCode'], + semestre: entry['semester'], + materia: materia + ) + next unless turma # Pula se a turma não existir + + if entry['docente'] + process_user(entry['docente'], turma, 'Professor') + end + + entry['dicente']&.each do |student_data| + process_user(student_data, turma, 'Aluno') + end + end + end + + def process_user(user_data, turma, ocupacao_padrao) + usuario = Usuario.find_or_initialize_by(matricula: user_data['usuario']) + + if usuario.new_record? + usuario.nome = user_data['nome'] + usuario.email = user_data['email'] + usuario.ocupacao = ocupacao_padrao + + usuario.password = user_data['usuario'] + usuario.password_confirmation = user_data['usuario'] + usuario.is_admin = false + usuario.save! + end + + UsuarioTurma.find_or_create_by!( + usuario: usuario, + turma: turma + ) + end +end \ No newline at end of file diff --git a/app/db/migrate/20251207183251_create_departamentos.rb b/app/db/migrate/20251207183251_create_departamentos.rb new file mode 100644 index 0000000000..ef33630536 --- /dev/null +++ b/app/db/migrate/20251207183251_create_departamentos.rb @@ -0,0 +1,9 @@ +class CreateDepartamentos < ActiveRecord::Migration[8.1] + def change + create_table :departamentos do |t| + t.string :nome + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183254_create_materia.rb b/app/db/migrate/20251207183254_create_materia.rb new file mode 100644 index 0000000000..ef1e739944 --- /dev/null +++ b/app/db/migrate/20251207183254_create_materia.rb @@ -0,0 +1,11 @@ +class CreateMateria < ActiveRecord::Migration[8.1] + def change + create_table :materia do |t| + t.string :nome + t.string :codigo + t.references :departamento, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183255_create_turmas.rb b/app/db/migrate/20251207183255_create_turmas.rb new file mode 100644 index 0000000000..a00a572819 --- /dev/null +++ b/app/db/migrate/20251207183255_create_turmas.rb @@ -0,0 +1,11 @@ +class CreateTurmas < ActiveRecord::Migration[8.1] + def change + create_table :turmas do |t| + t.string :num_turma + t.string :semestre + t.references :materia, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183257_create_usuario_turmas.rb b/app/db/migrate/20251207183257_create_usuario_turmas.rb new file mode 100644 index 0000000000..53d2754606 --- /dev/null +++ b/app/db/migrate/20251207183257_create_usuario_turmas.rb @@ -0,0 +1,10 @@ +class CreateUsuarioTurmas < ActiveRecord::Migration[8.1] + def change + create_table :usuario_turmas do |t| + t.references :usuario, null: false, foreign_key: true + t.references :turma, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183258_create_templates.rb b/app/db/migrate/20251207183258_create_templates.rb new file mode 100644 index 0000000000..43c2b4f1d5 --- /dev/null +++ b/app/db/migrate/20251207183258_create_templates.rb @@ -0,0 +1,10 @@ +class CreateTemplates < ActiveRecord::Migration[8.1] + def change + create_table :templates do |t| + t.string :nome + t.references :usuario, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183300_create_questao_templates.rb b/app/db/migrate/20251207183300_create_questao_templates.rb new file mode 100644 index 0000000000..d1430c0f36 --- /dev/null +++ b/app/db/migrate/20251207183300_create_questao_templates.rb @@ -0,0 +1,11 @@ +class CreateQuestaoTemplates < ActiveRecord::Migration[8.1] + def change + create_table :questao_templates do |t| + t.text :texto_questao + t.string :tipo_resposta + t.references :template, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183302_create_opcao_templates.rb b/app/db/migrate/20251207183302_create_opcao_templates.rb new file mode 100644 index 0000000000..f7590944fa --- /dev/null +++ b/app/db/migrate/20251207183302_create_opcao_templates.rb @@ -0,0 +1,11 @@ +class CreateOpcaoTemplates < ActiveRecord::Migration[8.1] + def change + create_table :opcao_templates do |t| + t.string :texto_opcao + t.integer :numero_opcao + t.references :questao_template, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183303_create_formularios.rb b/app/db/migrate/20251207183303_create_formularios.rb new file mode 100644 index 0000000000..793b30627b --- /dev/null +++ b/app/db/migrate/20251207183303_create_formularios.rb @@ -0,0 +1,10 @@ +class CreateFormularios < ActiveRecord::Migration[8.1] + def change + create_table :formularios do |t| + t.string :titulo + t.boolean :so_alunos + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183305_create_formulario_turmas.rb b/app/db/migrate/20251207183305_create_formulario_turmas.rb new file mode 100644 index 0000000000..a6beb5a945 --- /dev/null +++ b/app/db/migrate/20251207183305_create_formulario_turmas.rb @@ -0,0 +1,10 @@ +class CreateFormularioTurmas < ActiveRecord::Migration[8.1] + def change + create_table :formulario_turmas do |t| + t.references :formulario, null: false, foreign_key: true + t.references :turma, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183307_create_questao_formularios.rb b/app/db/migrate/20251207183307_create_questao_formularios.rb new file mode 100644 index 0000000000..f0edb9809d --- /dev/null +++ b/app/db/migrate/20251207183307_create_questao_formularios.rb @@ -0,0 +1,11 @@ +class CreateQuestaoFormularios < ActiveRecord::Migration[8.1] + def change + create_table :questao_formularios do |t| + t.text :texto_questao + t.string :tipo_resposta + t.references :formulario, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183309_create_opcao_formularios.rb b/app/db/migrate/20251207183309_create_opcao_formularios.rb new file mode 100644 index 0000000000..19afd94abf --- /dev/null +++ b/app/db/migrate/20251207183309_create_opcao_formularios.rb @@ -0,0 +1,11 @@ +class CreateOpcaoFormularios < ActiveRecord::Migration[8.1] + def change + create_table :opcao_formularios do |t| + t.string :texto_opcao + t.integer :numero_opcao + t.references :questao_formulario, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183310_create_formulario_respondidos.rb b/app/db/migrate/20251207183310_create_formulario_respondidos.rb new file mode 100644 index 0000000000..778793eee0 --- /dev/null +++ b/app/db/migrate/20251207183310_create_formulario_respondidos.rb @@ -0,0 +1,10 @@ +class CreateFormularioRespondidos < ActiveRecord::Migration[8.1] + def change + create_table :formulario_respondidos do |t| + t.references :formulario, null: false, foreign_key: true + t.references :usuario, null: false, foreign_key: true + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207183312_create_questao_respondidas.rb b/app/db/migrate/20251207183312_create_questao_respondidas.rb new file mode 100644 index 0000000000..6de5a6d1c3 --- /dev/null +++ b/app/db/migrate/20251207183312_create_questao_respondidas.rb @@ -0,0 +1,12 @@ +class CreateQuestaoRespondidas < ActiveRecord::Migration[8.1] + def change + create_table :questao_respondidas do |t| + t.references :formulario_respondido, null: false, foreign_key: true + t.references :questao_formulario, null: false, foreign_key: true + t.references :opcao_formulario, null: false, foreign_key: true + t.text :resposta + + t.timestamps + end + end +end diff --git a/app/db/migrate/20251207190733_add_ocupacao_to_usuarios.rb b/app/db/migrate/20251207190733_add_ocupacao_to_usuarios.rb new file mode 100644 index 0000000000..9f0488980a --- /dev/null +++ b/app/db/migrate/20251207190733_add_ocupacao_to_usuarios.rb @@ -0,0 +1,5 @@ +class AddOcupacaoToUsuarios < ActiveRecord::Migration[8.1] + def change + add_column :usuarios, :ocupacao, :string + end +end diff --git a/app/db/schema.rb b/app/db/schema.rb index 8fdb836c08..dca252dd46 100644 --- a/app/db/schema.rb +++ b/app/db/schema.rb @@ -10,14 +10,146 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2025_12_07_014407) do +ActiveRecord::Schema[8.1].define(version: 2025_12_07_190733) do + create_table "departamentos", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "nome" + t.datetime "updated_at", null: false + end + + create_table "formulario_respondidos", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "formulario_id", null: false + t.datetime "updated_at", null: false + t.integer "usuario_id", null: false + t.index ["formulario_id"], name: "index_formulario_respondidos_on_formulario_id" + t.index ["usuario_id"], name: "index_formulario_respondidos_on_usuario_id" + end + + create_table "formulario_turmas", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "formulario_id", null: false + t.integer "turma_id", null: false + t.datetime "updated_at", null: false + t.index ["formulario_id"], name: "index_formulario_turmas_on_formulario_id" + t.index ["turma_id"], name: "index_formulario_turmas_on_turma_id" + end + + create_table "formularios", force: :cascade do |t| + t.datetime "created_at", null: false + t.boolean "so_alunos" + t.string "titulo" + t.datetime "updated_at", null: false + end + + create_table "materia", force: :cascade do |t| + t.string "codigo" + t.datetime "created_at", null: false + t.integer "departamento_id", null: false + t.string "nome" + t.datetime "updated_at", null: false + t.index ["departamento_id"], name: "index_materia_on_departamento_id" + end + + create_table "opcao_formularios", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "numero_opcao" + t.integer "questao_formulario_id", null: false + t.string "texto_opcao" + t.datetime "updated_at", null: false + t.index ["questao_formulario_id"], name: "index_opcao_formularios_on_questao_formulario_id" + end + + create_table "opcao_templates", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "numero_opcao" + t.integer "questao_template_id", null: false + t.string "texto_opcao" + t.datetime "updated_at", null: false + t.index ["questao_template_id"], name: "index_opcao_templates_on_questao_template_id" + end + + create_table "questao_formularios", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "formulario_id", null: false + t.text "texto_questao" + t.string "tipo_resposta" + t.datetime "updated_at", null: false + t.index ["formulario_id"], name: "index_questao_formularios_on_formulario_id" + end + + create_table "questao_respondidas", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "formulario_respondido_id", null: false + t.integer "opcao_formulario_id", null: false + t.integer "questao_formulario_id", null: false + t.text "resposta" + t.datetime "updated_at", null: false + t.index ["formulario_respondido_id"], name: "index_questao_respondidas_on_formulario_respondido_id" + t.index ["opcao_formulario_id"], name: "index_questao_respondidas_on_opcao_formulario_id" + t.index ["questao_formulario_id"], name: "index_questao_respondidas_on_questao_formulario_id" + end + + create_table "questao_templates", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "template_id", null: false + t.text "texto_questao" + t.string "tipo_resposta" + t.datetime "updated_at", null: false + t.index ["template_id"], name: "index_questao_templates_on_template_id" + end + + create_table "templates", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "nome" + t.datetime "updated_at", null: false + t.integer "usuario_id", null: false + t.index ["usuario_id"], name: "index_templates_on_usuario_id" + end + + create_table "turmas", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "materia_id", null: false + t.string "num_turma" + t.string "semestre" + t.datetime "updated_at", null: false + t.index ["materia_id"], name: "index_turmas_on_materia_id" + end + + create_table "usuario_turmas", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "turma_id", null: false + t.datetime "updated_at", null: false + t.integer "usuario_id", null: false + t.index ["turma_id"], name: "index_usuario_turmas_on_turma_id" + t.index ["usuario_id"], name: "index_usuario_turmas_on_usuario_id" + end + create_table "usuarios", force: :cascade do |t| t.datetime "created_at", null: false t.string "email" t.boolean "is_admin" t.string "matricula" t.string "nome" + t.string "ocupacao" t.string "password_digest" t.datetime "updated_at", null: false end + + add_foreign_key "formulario_respondidos", "formularios" + add_foreign_key "formulario_respondidos", "usuarios" + add_foreign_key "formulario_turmas", "formularios" + add_foreign_key "formulario_turmas", "turmas" + add_foreign_key "materia", "departamentos" + add_foreign_key "opcao_formularios", "questao_formularios" + add_foreign_key "opcao_templates", "questao_templates" + add_foreign_key "questao_formularios", "formularios" + add_foreign_key "questao_respondidas", "formulario_respondidos" + add_foreign_key "questao_respondidas", "opcao_formularios" + add_foreign_key "questao_respondidas", "questao_formularios" + add_foreign_key "questao_templates", "templates" + add_foreign_key "templates", "usuarios" + add_foreign_key "turmas", "materia", column: "materia_id" + add_foreign_key "usuario_turmas", "turmas" + add_foreign_key "usuario_turmas", "usuarios" end diff --git a/app/spec/models/departamento_spec.rb b/app/spec/models/departamento_spec.rb new file mode 100644 index 0000000000..0a0d313f9c --- /dev/null +++ b/app/spec/models/departamento_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Departamento, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/formulario_respondido_spec.rb b/app/spec/models/formulario_respondido_spec.rb new file mode 100644 index 0000000000..dc3b2aba93 --- /dev/null +++ b/app/spec/models/formulario_respondido_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe FormularioRespondido, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/formulario_spec.rb b/app/spec/models/formulario_spec.rb new file mode 100644 index 0000000000..2318f88769 --- /dev/null +++ b/app/spec/models/formulario_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Formulario, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/formulario_turma_spec.rb b/app/spec/models/formulario_turma_spec.rb new file mode 100644 index 0000000000..b730e4268e --- /dev/null +++ b/app/spec/models/formulario_turma_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe FormularioTurma, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/materium_spec.rb b/app/spec/models/materium_spec.rb new file mode 100644 index 0000000000..4563bda171 --- /dev/null +++ b/app/spec/models/materium_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Materium, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/opcao_formulario_spec.rb b/app/spec/models/opcao_formulario_spec.rb new file mode 100644 index 0000000000..e7afc00eef --- /dev/null +++ b/app/spec/models/opcao_formulario_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe OpcaoFormulario, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/opcao_template_spec.rb b/app/spec/models/opcao_template_spec.rb new file mode 100644 index 0000000000..77a4ada1eb --- /dev/null +++ b/app/spec/models/opcao_template_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe OpcaoTemplate, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/questao_formulario_spec.rb b/app/spec/models/questao_formulario_spec.rb new file mode 100644 index 0000000000..b219b5c990 --- /dev/null +++ b/app/spec/models/questao_formulario_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe QuestaoFormulario, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/questao_respondida_spec.rb b/app/spec/models/questao_respondida_spec.rb new file mode 100644 index 0000000000..7ecb44c791 --- /dev/null +++ b/app/spec/models/questao_respondida_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe QuestaoRespondida, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/questao_template_spec.rb b/app/spec/models/questao_template_spec.rb new file mode 100644 index 0000000000..05bc82643d --- /dev/null +++ b/app/spec/models/questao_template_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe QuestaoTemplate, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/template_spec.rb b/app/spec/models/template_spec.rb new file mode 100644 index 0000000000..068ef0ee3c --- /dev/null +++ b/app/spec/models/template_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Template, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/turma_spec.rb b/app/spec/models/turma_spec.rb new file mode 100644 index 0000000000..b7629b1e16 --- /dev/null +++ b/app/spec/models/turma_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe Turma, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/models/usuario_turma_spec.rb b/app/spec/models/usuario_turma_spec.rb new file mode 100644 index 0000000000..240bf64c84 --- /dev/null +++ b/app/spec/models/usuario_turma_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe UsuarioTurma, type: :model do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/services/sigaa_service_spec.rb b/app/spec/services/sigaa_service_spec.rb new file mode 100644 index 0000000000..ac0afbdfe6 --- /dev/null +++ b/app/spec/services/sigaa_service_spec.rb @@ -0,0 +1,77 @@ +require 'rails_helper' + +RSpec.describe SigaaService do + # Mock do classes.json + let(:classes_json) do + [ + { + "code": "CIC0097", + "name": "BANCOS DE DADOS", + "class": { "classCode": "TA", "semester": "2021.2", "time": "35T45" } + } + ].to_json + end + + # Mock do class_members.json + let(:members_json) do + [ + { + "code": "CIC0097", + "classCode": "TA", + "semester": "2021.2", + "dicente": [ + { + "nome": "Aluno Teste", + "matricula": "190012345", + "usuario": "190012345", + "email": "aluno@teste.com", + "ocupacao": "dicente" + } + ], + "docente": { + "nome": "Prof Teste", + "usuario": "111222333", + "email": "prof@unb.br", + "ocupacao": "docente" + } + } + ].to_json + end + + let(:classes_path) { 'spec/fixtures/files/classes.json' } + let(:members_path) { 'spec/fixtures/files/members.json' } + + before do + FileUtils.mkdir_p('spec/fixtures/files') + File.write(classes_path, classes_json) + File.write(members_path, members_json) + end + + after do + File.delete(classes_path) if File.exist?(classes_path) + File.delete(members_path) if File.exist?(members_path) + end + + describe '#call' do + it 'importa turmas e matricula usuários corretamente' do + service = SigaaService.new(classes_path, members_path) + + # Verificações + expect { service.call }.to change(Materia, :count).by(1) + .and change(Turma, :count).by(1) + .and change(Usuario, :count).by(2) # 1 Aluno + 1 Prof + .and change(UsuarioTurma, :count).by(2) # 2 matrículas + + # Verifica se os dados foram salvos corretamente + materia = Materia.find_by(codigo: 'CIC0097') + expect(materia.nome).to eq('BANCOS DE DADOS') + + aluno = Usuario.find_by(matricula: '190012345') + prof = Usuario.find_by(matricula: '111222333') + turma = Turma.first + + expect(aluno.turmas).to include(turma) + expect(prof.turmas).to include(turma) + end + end +end \ No newline at end of file From 101404d3ce778f12cb9e09db7ec79b221f92fec5 Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 7 Dec 2025 17:24:18 -0300 Subject: [PATCH 06/19] =?UTF-8?q?:sparkles:=20feat:=20in=C3=ADcio=20da=20i?= =?UTF-8?q?mplementa=C3=A7=C3=A3o=20do=20dashboard?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/components/button_component.rb | 16 ++++++--- .../dashboard/header_component.html.erb | 18 ++++++++++ .../components/dashboard/header_component.rb | 9 +++++ .../dashboard/sidebar_component.html.erb | 27 ++++++++++++++ .../components/dashboard/sidebar_component.rb | 11 ++++++ .../evaluation_card_component.html.erb | 10 ++++++ .../components/evaluation_card_component.rb | 8 +++++ app/app/controllers/admins_controller.rb | 10 ++++++ app/app/controllers/application_controller.rb | 6 ++++ app/app/controllers/dashboard_controller.rb | 8 +++++ app/app/helpers/dashboard_helper.rb | 2 ++ .../controllers/sidebar_controller.js | 9 +++++ app/app/models/turma.rb | 7 ++++ app/app/views/admins/dashboard.html.erb | 25 +++++++++++++ app/app/views/admins/import_form.html.erb | 23 ++++++++++++ app/app/views/dashboard/index.html.erb | 21 +++++++++++ app/app/views/layouts/dashboard.html.erb | 35 +++++++++++++++++++ app/config/routes.rb | 8 ++++- app/spec/helpers/dashboard_helper_spec.rb | 15 ++++++++ app/spec/requests/dashboard_spec.rb | 11 ++++++ .../dashboard/index.html.tailwindcss_spec.rb | 5 +++ 21 files changed, 279 insertions(+), 5 deletions(-) create mode 100644 app/app/components/dashboard/header_component.html.erb create mode 100644 app/app/components/dashboard/header_component.rb create mode 100644 app/app/components/dashboard/sidebar_component.html.erb create mode 100644 app/app/components/dashboard/sidebar_component.rb create mode 100644 app/app/components/evaluation_card_component.html.erb create mode 100644 app/app/components/evaluation_card_component.rb create mode 100644 app/app/controllers/admins_controller.rb create mode 100644 app/app/controllers/dashboard_controller.rb create mode 100644 app/app/helpers/dashboard_helper.rb create mode 100644 app/app/javascript/controllers/sidebar_controller.js create mode 100644 app/app/views/admins/dashboard.html.erb create mode 100644 app/app/views/admins/import_form.html.erb create mode 100644 app/app/views/dashboard/index.html.erb create mode 100644 app/app/views/layouts/dashboard.html.erb create mode 100644 app/spec/helpers/dashboard_helper_spec.rb create mode 100644 app/spec/requests/dashboard_spec.rb create mode 100644 app/spec/views/dashboard/index.html.tailwindcss_spec.rb diff --git a/app/app/components/button_component.rb b/app/app/components/button_component.rb index bd2adb3ee0..2b6baa88c6 100644 --- a/app/app/components/button_component.rb +++ b/app/app/components/button_component.rb @@ -1,18 +1,26 @@ -# app/components/button_component.rb class ButtonComponent < ViewComponent::Base - def initialize(text:, type: :submit, variant: :primary) + def initialize(text:, type: :submit, variant: :primary, link: nil) @text = text @type = type @variant = variant + @link = link end def classes - base = "w-full py-3 px-4 rounded text-sm font-medium focus:outline-none transition duration-150 shadow-sm" + base = "w-full py-3 px-6 rounded font-bold text-sm focus:outline-none transition duration-150 shadow-md cursor-pointer" case @variant when :primary - "#{base} bg-[#22C55E] hover:bg-green-600 text-white" + # Importar Dados (Verde mais escuro) + "#{base} bg-green-600 hover:bg-green-700 text-white" + when :secondary + # Editar Templates / Enviar Formulários (Verde médio) + "#{base} bg-green-400 hover:bg-green-500 text-white" + when :tertiary + # Resultados (Verde mais claro) + "#{base} bg-green-200 hover:bg-green-300 text-green-800" else + # Padrão "#{base} bg-gray-500 hover:bg-gray-700 text-white" end end diff --git a/app/app/components/dashboard/header_component.html.erb b/app/app/components/dashboard/header_component.html.erb new file mode 100644 index 0000000000..d34d5be93d --- /dev/null +++ b/app/app/components/dashboard/header_component.html.erb @@ -0,0 +1,18 @@ +
+
+ + + +

Avaliações

+
+ +
+
+
+
+ <%= initials %> +
+
+
\ No newline at end of file diff --git a/app/app/components/dashboard/header_component.rb b/app/app/components/dashboard/header_component.rb new file mode 100644 index 0000000000..4318653750 --- /dev/null +++ b/app/app/components/dashboard/header_component.rb @@ -0,0 +1,9 @@ +class Dashboard::HeaderComponent < ViewComponent::Base + def initialize(user:) + @user = user + end + + def initials + @user.nome.split.first[0].upcase rescue "U" + end +end \ No newline at end of file diff --git a/app/app/components/dashboard/sidebar_component.html.erb b/app/app/components/dashboard/sidebar_component.html.erb new file mode 100644 index 0000000000..5b2ae29645 --- /dev/null +++ b/app/app/components/dashboard/sidebar_component.html.erb @@ -0,0 +1,27 @@ +
\ No newline at end of file diff --git a/app/app/components/dashboard/sidebar_component.rb b/app/app/components/dashboard/sidebar_component.rb new file mode 100644 index 0000000000..66a6dadd52 --- /dev/null +++ b/app/app/components/dashboard/sidebar_component.rb @@ -0,0 +1,11 @@ +module Dashboard + class SidebarComponent < ViewComponent::Base + def initialize(user:) + @user = user + end + + def admin? + @user.is_admin? + end + end +end \ No newline at end of file diff --git a/app/app/components/evaluation_card_component.html.erb b/app/app/components/evaluation_card_component.html.erb new file mode 100644 index 0000000000..b21ec1d7c2 --- /dev/null +++ b/app/app/components/evaluation_card_component.html.erb @@ -0,0 +1,10 @@ +
+
+

<%= @materia %>

+

<%= @semestre %>

+
+ +
+

<%= @professor %>

+
+
\ No newline at end of file diff --git a/app/app/components/evaluation_card_component.rb b/app/app/components/evaluation_card_component.rb new file mode 100644 index 0000000000..82b0285b34 --- /dev/null +++ b/app/app/components/evaluation_card_component.rb @@ -0,0 +1,8 @@ +class EvaluationCardComponent < ViewComponent::Base + def initialize(turma:, materia:, professor:, semestre:) + @turma = turma + @materia = materia + @professor = professor || "Professor não atribuído" + @semestre = semestre + end +end \ No newline at end of file diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb new file mode 100644 index 0000000000..2bcec47ff8 --- /dev/null +++ b/app/app/controllers/admins_controller.rb @@ -0,0 +1,10 @@ +class AdminsController < ApplicationController + before_action :require_login + layout 'dashboard' + + def dashboard + end + + def import_form + end +end \ No newline at end of file diff --git a/app/app/controllers/application_controller.rb b/app/app/controllers/application_controller.rb index fad99c6ec9..40d45f0abd 100644 --- a/app/app/controllers/application_controller.rb +++ b/app/app/controllers/application_controller.rb @@ -8,4 +8,10 @@ def current_user def logged_in? !!current_user end + + def require_login + unless logged_in? + redirect_to login_path, alert: "Você precisa estar logado para acessar esta página." + end + end end \ No newline at end of file diff --git a/app/app/controllers/dashboard_controller.rb b/app/app/controllers/dashboard_controller.rb new file mode 100644 index 0000000000..e442ce4124 --- /dev/null +++ b/app/app/controllers/dashboard_controller.rb @@ -0,0 +1,8 @@ +class DashboardController < ApplicationController + before_action :require_login + layout 'dashboard' + + def index + @turmas = current_user.turmas.includes(:materia) + end +end \ No newline at end of file diff --git a/app/app/helpers/dashboard_helper.rb b/app/app/helpers/dashboard_helper.rb new file mode 100644 index 0000000000..a94ddfc2e3 --- /dev/null +++ b/app/app/helpers/dashboard_helper.rb @@ -0,0 +1,2 @@ +module DashboardHelper +end diff --git a/app/app/javascript/controllers/sidebar_controller.js b/app/app/javascript/controllers/sidebar_controller.js new file mode 100644 index 0000000000..e39fd601bd --- /dev/null +++ b/app/app/javascript/controllers/sidebar_controller.js @@ -0,0 +1,9 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = [ "menu" ] + + toggle() { + this.menuTarget.classList.toggle("hidden") + } +} \ No newline at end of file diff --git a/app/app/models/turma.rb b/app/app/models/turma.rb index 23b8de558e..9d1d69120a 100644 --- a/app/app/models/turma.rb +++ b/app/app/models/turma.rb @@ -2,4 +2,11 @@ class Turma < ApplicationRecord belongs_to :materia has_many :usuario_turmas has_many :usuarios, through: :usuario_turmas + has_many :formulario_turmas + has_many :formularios, through: :formulario_turmas + + def professor + # Procura um usuário vinculado a esta turma que tenha a ocupação 'docente' ou 'Professor' + usuarios.find_by("ocupacao ILIKE ?", "%docente%") || usuarios.find_by("ocupacao ILIKE ?", "%professor%") + end end \ No newline at end of file diff --git a/app/app/views/admins/dashboard.html.erb b/app/app/views/admins/dashboard.html.erb new file mode 100644 index 0000000000..e6936eb737 --- /dev/null +++ b/app/app/views/admins/dashboard.html.erb @@ -0,0 +1,25 @@ +
+
+

Gerenciamento

+ +
+ + <%= link_to admin_importar_form_path do %> + <%= render(ButtonComponent.new(text: "Importar dados", variant: :primary, type: :button)) %> + <% end %> + + <%= link_to "#" do %> + <%= render(ButtonComponent.new(text: "Editar Templates", variant: :secondary, type: :button)) %> + <% end %> + + <%= link_to "#" do %> + <%= render(ButtonComponent.new(text: "Enviar Formulários", variant: :secondary, type: :button)) %> + <% end %> + + <%= link_to "#" do %> + <%= render(ButtonComponent.new(text: "Resultados", variant: :tertiary, type: :button)) %> + <% end %> + +
+
+
\ No newline at end of file diff --git a/app/app/views/admins/import_form.html.erb b/app/app/views/admins/import_form.html.erb new file mode 100644 index 0000000000..d7ac4016da --- /dev/null +++ b/app/app/views/admins/import_form.html.erb @@ -0,0 +1,23 @@ +
+ +

Upload de Dados do SIGAA

+ + <%= form_with url: admin_importar_path, local: true, multipart: true, class: "border border-gray-200 rounded p-6" do |f| %> + +
+ + <%= f.file_field :arquivo_turmas, class: "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100" %> +
+ +
+ + <%= f.file_field :arquivo_membros, class: "block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-purple-50 file:text-purple-700 hover:file:bg-purple-100" %> +
+ + <%= f.submit "Iniciar Importação", class: "bg-purple-700 text-white font-bold py-2 px-4 rounded hover:bg-purple-800 cursor-pointer" %> + <% end %> + +
+ <%= link_to "Voltar ao Painel", admin_path, class: "text-purple-600 hover:text-purple-800 text-sm" %> +
+
\ No newline at end of file diff --git a/app/app/views/dashboard/index.html.erb b/app/app/views/dashboard/index.html.erb new file mode 100644 index 0000000000..10b98cbab1 --- /dev/null +++ b/app/app/views/dashboard/index.html.erb @@ -0,0 +1,21 @@ +
+
+ + <% if @turmas.any? %> + <% @turmas.each do |turma| %> + <%= render(EvaluationCardComponent.new( + turma: turma.numero, + materia: turma.materia.nome, + professor: turma.professor&.nome, + semestre: turma.semestre + )) %> + <% end %> + <% else %> +
+

Você não está matriculado em nenhuma turma ainda.

+

Importe os dados do SIGAA para visualizar as matérias.

+
+ <% end %> + +
+
\ No newline at end of file diff --git a/app/app/views/layouts/dashboard.html.erb b/app/app/views/layouts/dashboard.html.erb new file mode 100644 index 0000000000..9f50ffb2f0 --- /dev/null +++ b/app/app/views/layouts/dashboard.html.erb @@ -0,0 +1,35 @@ + + + + Camaar - Dashboard + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + <%= stylesheet_link_tag "tailwind", "data-turbo-track": "reload" %> + <%= javascript_importmap_tags %> + + + + + <% if flash[:notice] %> +
+ <%= flash[:notice] %> +
+ <% end %> + +
+ + <%= render(Dashboard::SidebarComponent.new(user: current_user)) %> + +
+ + <%= render(Dashboard::HeaderComponent.new(user: current_user)) %> + +
+ <%# O CONTEÚDO DA VIEW (dashboard/index ou admins/dashboard) ENTRA AQUI %> + <%= yield %> +
+
+
+ + \ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index ad8cb0c77d..725e9d8961 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -3,5 +3,11 @@ post 'login', to: 'sessions#create' delete 'logout', to: 'sessions#destroy' - root to: 'sessions#new' + get 'dashboard', to: 'dashboard#index' + + get 'admin', to: 'admins#dashboard', as: 'admin' + get 'admin/importar', to: 'admins#import_form', as: 'admin_importar_form' + post 'admin/importar', to: 'admins#importar' + + root to: 'dashboard#index' end diff --git a/app/spec/helpers/dashboard_helper_spec.rb b/app/spec/helpers/dashboard_helper_spec.rb new file mode 100644 index 0000000000..12cff9a8f1 --- /dev/null +++ b/app/spec/helpers/dashboard_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the DashboardHelper. For example: +# +# describe DashboardHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe DashboardHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/requests/dashboard_spec.rb b/app/spec/requests/dashboard_spec.rb new file mode 100644 index 0000000000..1a4f911c03 --- /dev/null +++ b/app/spec/requests/dashboard_spec.rb @@ -0,0 +1,11 @@ +require 'rails_helper' + +RSpec.describe "Dashboards", type: :request do + describe "GET /index" do + it "returns http success" do + get "/dashboard/index" + expect(response).to have_http_status(:success) + end + end + +end diff --git a/app/spec/views/dashboard/index.html.tailwindcss_spec.rb b/app/spec/views/dashboard/index.html.tailwindcss_spec.rb new file mode 100644 index 0000000000..0541255a9f --- /dev/null +++ b/app/spec/views/dashboard/index.html.tailwindcss_spec.rb @@ -0,0 +1,5 @@ +require 'rails_helper' + +RSpec.describe "dashboard/index.html.tailwindcss", type: :view do + pending "add some examples to (or delete) #{__FILE__}" +end From e9e045cc6b573b69564ffb86652527e5853adf74 Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Sun, 7 Dec 2025 18:58:21 -0300 Subject: [PATCH 07/19] =?UTF-8?q?feature:=20cria=C3=A7=C3=A3o=20da=20pagin?= =?UTF-8?q?a=20de=20enviar=20e=20da=20pagina=20de=20editar?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/admins_controller.rb | 13 +++++ app/app/views/admins/dashboard.html.erb | 4 +- app/app/views/admins/edit_templates.html.erb | 38 ++++++++++++++ app/app/views/admins/send_forms.html.erb | 53 ++++++++++++++++++++ app/config/routes.rb | 11 +++- 5 files changed, 116 insertions(+), 3 deletions(-) create mode 100644 app/app/views/admins/edit_templates.html.erb create mode 100644 app/app/views/admins/send_forms.html.erb diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb index 2bcec47ff8..ca80e5ce8d 100644 --- a/app/app/controllers/admins_controller.rb +++ b/app/app/controllers/admins_controller.rb @@ -7,4 +7,17 @@ def dashboard def import_form end + + def send_forms + # Lógica para carregar dados (formulários, templates) + @forms_to_send = [ + { name: "Estudos Em", semester: "2024.1", code: "CIC1024", checked: true }, + # ... + ] + end + def edit_templates + # No futuro, aqui você faria: @templates = Template.all + # Por enquanto, usamos dados mockados para preencher a tela: + @templates = [] + end end \ No newline at end of file diff --git a/app/app/views/admins/dashboard.html.erb b/app/app/views/admins/dashboard.html.erb index e6936eb737..6b04ccec56 100644 --- a/app/app/views/admins/dashboard.html.erb +++ b/app/app/views/admins/dashboard.html.erb @@ -8,11 +8,11 @@ <%= render(ButtonComponent.new(text: "Importar dados", variant: :primary, type: :button)) %> <% end %> - <%= link_to "#" do %> + <%= link_to admin_edit_templates_path do %> <%= render(ButtonComponent.new(text: "Editar Templates", variant: :secondary, type: :button)) %> <% end %> - <%= link_to "#" do %> + <%= link_to admin_send_forms_path do %> <%= render(ButtonComponent.new(text: "Enviar Formulários", variant: :secondary, type: :button)) %> <% end %> diff --git a/app/app/views/admins/edit_templates.html.erb b/app/app/views/admins/edit_templates.html.erb new file mode 100644 index 0000000000..40c1afa065 --- /dev/null +++ b/app/app/views/admins/edit_templates.html.erb @@ -0,0 +1,38 @@ +
+ +
+

Gerenciamento - Templates

+
+ +
+
+ + <%# LOOP FUTURO: Se @templates estiver vazio, nada aqui será renderizado %> + <% @templates.each do |template| %> +
+
+
+

<%= template.name %>

+

<%= template.description %>

+
+
+ + + + + + +
+
+
+ <% end %> + +
+ <%= link_to "#", class: "w-full h-full flex items-center justify-center" do %> + + + <% end %> +
+ +
+
+
\ No newline at end of file diff --git a/app/app/views/admins/send_forms.html.erb b/app/app/views/admins/send_forms.html.erb new file mode 100644 index 0000000000..57198f9e03 --- /dev/null +++ b/app/app/views/admins/send_forms.html.erb @@ -0,0 +1,53 @@ +
+
+ +
+ +
+ + +
+ +
+
+ + + + + + + + + + + <% @forms_to_send.each_with_index do |form, index| %> + + + + + + + <% end %> + + +
NomeSemestreCódigo
+ class="h-4 w-4 text-green-500 border-gray-300 rounded focus:ring-green-400"> + <%= form[:name] %><%= form[:semester] %><%= form[:code] %>
+
+
+ +
+ <%= link_to admin_path do %> + + <% end %> +
+ +
+
+
\ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index 725e9d8961..e4ebad3176 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -5,9 +5,18 @@ get 'dashboard', to: 'dashboard#index' + # Rotas de Administração get 'admin', to: 'admins#dashboard', as: 'admin' + + # Rotas de Importação get 'admin/importar', to: 'admins#import_form', as: 'admin_importar_form' post 'admin/importar', to: 'admins#importar' + # Rotas de Envio de Formulários + get 'admin/send_forms', to: 'admins#send_forms', as: 'admin_send_forms' + + # AQUI: Nova rota para Gerenciar Templates + get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' + root to: 'dashboard#index' -end +end \ No newline at end of file From d986b9e66015c309618729d0c7747bb17ca7551f Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 7 Dec 2025 22:32:08 -0300 Subject: [PATCH 08/19] =?UTF-8?q?:sparkles:=20feat:=20adi=C3=A7=C3=A3o=20d?= =?UTF-8?q?a=20exibi=C3=A7=C3=A3o=20dos=20formul=C3=A1rios=20pendentese=20?= =?UTF-8?q?de=20sa=C3=ADda=20da=20conta?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dashboard/header_component.html.erb | 33 ++++- .../components/dashboard/header_component.rb | 25 +++- .../controllers/dropdown_controller.js | 17 +++ app/app/models/turma.rb | 5 +- app/app/views/dashboard/index.html.erb | 2 +- app/app/views/layouts/dashboard.html.erb | 2 +- app/db/seeds.rb | 135 ++++++++++++++++-- 7 files changed, 192 insertions(+), 27 deletions(-) create mode 100644 app/app/javascript/controllers/dropdown_controller.js diff --git a/app/app/components/dashboard/header_component.html.erb b/app/app/components/dashboard/header_component.html.erb index d34d5be93d..7000d839a8 100644 --- a/app/app/components/dashboard/header_component.html.erb +++ b/app/app/components/dashboard/header_component.html.erb @@ -1,18 +1,39 @@
+
- -

Avaliações

+

<%= title %>

-
-
-
- <%= initials %> + +
+ + + + +
\ No newline at end of file diff --git a/app/app/components/dashboard/header_component.rb b/app/app/components/dashboard/header_component.rb index 4318653750..2dc5dbe9b1 100644 --- a/app/app/components/dashboard/header_component.rb +++ b/app/app/components/dashboard/header_component.rb @@ -1,9 +1,22 @@ -class Dashboard::HeaderComponent < ViewComponent::Base - def initialize(user:) - @user = user - end +module Dashboard + class HeaderComponent < ViewComponent::Base + def initialize(user:, path:) + @user = user + @path = path + end + + def initials + @user.nome.to_s.first.upcase + rescue + "U" + end - def initials - @user.nome.split.first[0].upcase rescue "U" + def title + if @path.start_with?("/admin") + "Gerenciamento" + else + "Avaliações" + end + end end end \ No newline at end of file diff --git a/app/app/javascript/controllers/dropdown_controller.js b/app/app/javascript/controllers/dropdown_controller.js new file mode 100644 index 0000000000..1806630fa0 --- /dev/null +++ b/app/app/javascript/controllers/dropdown_controller.js @@ -0,0 +1,17 @@ +import { Controller } from "@hotwired/stimulus" + +export default class extends Controller { + static targets = ["menu"] + + toggle() { + // Alterna a visibilidade do menu + this.menuTarget.classList.toggle("hidden") + } + + // (Opcional) Fecha o menu se clicar fora dele + hide(event) { + if (!this.element.contains(event.target)) { + this.menuTarget.classList.add("hidden") + } + } +} \ No newline at end of file diff --git a/app/app/models/turma.rb b/app/app/models/turma.rb index 9d1d69120a..91406ec3ee 100644 --- a/app/app/models/turma.rb +++ b/app/app/models/turma.rb @@ -2,11 +2,8 @@ class Turma < ApplicationRecord belongs_to :materia has_many :usuario_turmas has_many :usuarios, through: :usuario_turmas - has_many :formulario_turmas - has_many :formularios, through: :formulario_turmas def professor - # Procura um usuário vinculado a esta turma que tenha a ocupação 'docente' ou 'Professor' - usuarios.find_by("ocupacao ILIKE ?", "%docente%") || usuarios.find_by("ocupacao ILIKE ?", "%professor%") + usuarios.where("ocupacao LIKE ?", "%docente%").first end end \ No newline at end of file diff --git a/app/app/views/dashboard/index.html.erb b/app/app/views/dashboard/index.html.erb index 10b98cbab1..4e22f153e2 100644 --- a/app/app/views/dashboard/index.html.erb +++ b/app/app/views/dashboard/index.html.erb @@ -4,7 +4,7 @@ <% if @turmas.any? %> <% @turmas.each do |turma| %> <%= render(EvaluationCardComponent.new( - turma: turma.numero, + turma: turma.num_turma, materia: turma.materia.nome, professor: turma.professor&.nome, semestre: turma.semestre diff --git a/app/app/views/layouts/dashboard.html.erb b/app/app/views/layouts/dashboard.html.erb index 9f50ffb2f0..73bbcc744d 100644 --- a/app/app/views/layouts/dashboard.html.erb +++ b/app/app/views/layouts/dashboard.html.erb @@ -23,7 +23,7 @@
- <%= render(Dashboard::HeaderComponent.new(user: current_user)) %> + <%= render(Dashboard::HeaderComponent.new(user: current_user, path: request.path)) %>
<%# O CONTEÚDO DA VIEW (dashboard/index ou admins/dashboard) ENTRA AQUI %> diff --git a/app/db/seeds.rb b/app/db/seeds.rb index 4fbd6ed970..57a920701e 100644 --- a/app/db/seeds.rb +++ b/app/db/seeds.rb @@ -1,9 +1,126 @@ -# This file should ensure the existence of records required to run the application in every environment (production, -# development, test). The code here should be idempotent so that it can be executed at any point in every environment. -# The data can then be loaded with the bin/rails db:seed command (or created alongside the database with db:setup). -# -# Example: -# -# ["Action", "Comedy", "Drama", "Horror"].each do |genre_name| -# MovieGenre.find_or_create_by!(name: genre_name) -# end +# db/seeds.rb + +puts "🌱 Iniciando o seed do banco de dados..." + +# 1. Limpar dados existentes (na ordem reversa para não quebrar FKs) +puts "🧹 Limpando tabelas antigas..." +QuestaoRespondida.destroy_all +FormularioRespondido.destroy_all +OpcaoFormulario.destroy_all +QuestaoFormulario.destroy_all +FormularioTurma.destroy_all +Formulario.destroy_all +OpcaoTemplate.destroy_all +QuestaoTemplate.destroy_all +Template.destroy_all +UsuarioTurma.destroy_all +Turma.destroy_all +Materia.destroy_all +Departamento.destroy_all +Usuario.destroy_all + +# 2. Criar Usuários +puts "👤 Criando usuários..." + +# Admin +admin = Usuario.create!( + nome: "Administrador Geral", + email: "admin@unb.br", + matricula: "000001", + password: "123", + password_confirmation: "123", + ocupacao: "admin", + is_admin: true +) + +# Professor +prof = Usuario.create!( + nome: "Prof. Pardal", + email: "pardal@unb.br", + matricula: "000002", + password: "123", + password_confirmation: "123", + ocupacao: "docente", + is_admin: false +) + +# Alunos +alunos = [] +5.times do |i| + alunos << Usuario.create!( + nome: "Aluno #{i + 1}", + email: "aluno#{i + 1}@unb.br", + matricula: "202300#{i + 1}", + password: "123", + password_confirmation: "123", + ocupacao: "discente", + is_admin: false + ) +end + +# 3. Estrutura Acadêmica +puts "🏫 Criando estrutura acadêmica..." + +dep_cic = Departamento.create!(nome: "Ciência da Computação") +dep_mat = Departamento.create!(nome: "Matemática") + +mat_bd = Materia.create!(nome: "Bancos de Dados", codigo: "CIC0097", departamento: dep_cic) +mat_es = Materia.create!(nome: "Engenharia de Software", codigo: "CIC0105", departamento: dep_cic) +mat_calc = Materia.create!(nome: "Cálculo 1", codigo: "MAT001", departamento: dep_mat) + +turma_bd = Turma.create!(num_turma: "TA", semestre: "2024.1", materia: mat_bd) +turma_es = Turma.create!(num_turma: "TB", semestre: "2024.1", materia: mat_es) + +# 4. Matrículas (Vínculos) +puts "🔗 Vinculando usuários às turmas..." + +# Professor nas duas turmas +UsuarioTurma.create!(usuario: prof, turma: turma_bd) +UsuarioTurma.create!(usuario: prof, turma: turma_es) + +# Alunos nas turmas (misturado) +alunos.each_with_index do |aluno, index| + UsuarioTurma.create!(usuario: aluno, turma: turma_bd) + UsuarioTurma.create!(usuario: aluno, turma: turma_es) if index.even? # Só alguns em ES +end + +# 5. Templates e Formulários +puts "📝 Criando templates e formulários..." + +# Template +template = Template.create!(nome: "Avaliação Padrão CIC", usuario: admin) + +# Questão de Texto +q1 = QuestaoTemplate.create!( + texto_questao: "O que você achou da didática do professor?", + tipo_resposta: "texto", + template: template +) + +# Questão de Múltipla Escolha +q2 = QuestaoTemplate.create!( + texto_questao: "Como você avalia a infraestrutura da sala?", + tipo_resposta: "multipla_escolha", + template: template +) +OpcaoTemplate.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_template: q2) +OpcaoTemplate.create!(texto_opcao: "Regular", numero_opcao: 2, questao_template: q2) +OpcaoTemplate.create!(texto_opcao: "Boa", numero_opcao: 3, questao_template: q2) + +# Criar um Formulário Aplicado (Cópia do Template para a Turma de BD) +form = Formulario.create!(titulo: "Avaliação Final - Bancos de Dados", so_alunos: true) +FormularioTurma.create!(formulario: form, turma: turma_bd) + +# Copiar questões do template para o formulário (simulando a lógica real) +QuestaoFormulario.create!(texto_questao: q1.texto_questao, tipo_resposta: q1.tipo_resposta, formulario: form) +q_form_2 = QuestaoFormulario.create!(texto_questao: q2.texto_questao, tipo_resposta: q2.tipo_resposta, formulario: form) +OpcaoFormulario.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_formulario: q_form_2) +OpcaoFormulario.create!(texto_opcao: "Regular", numero_opcao: 2, questao_formulario: q_form_2) +OpcaoFormulario.create!(texto_opcao: "Boa", numero_opcao: 3, questao_formulario: q_form_2) + +puts "✅ Seed concluído com sucesso!" +puts "--------------------------------------------------" +puts "Login Admin: admin@unb.br / 123" +puts "Login Prof: pardal@unb.br / 123" +puts "Login Aluno: aluno1@unb.br / 123" +puts "--------------------------------------------------" \ No newline at end of file From 68c636ba9ffb162863ad1dcff46d8666947859fc Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Sun, 7 Dec 2025 23:03:30 -0300 Subject: [PATCH 09/19] =?UTF-8?q?feature:=20adicionando=20cria=C3=A7=C3=A3?= =?UTF-8?q?o=20de=20templates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/admins_controller.rb | 29 ++++++- app/app/views/admins/edit_templates.html.erb | 22 +++-- app/app/views/admins/new_template.html.erb | 86 ++++++++++++++++++++ app/config/routes.rb | 7 +- 4 files changed, 135 insertions(+), 9 deletions(-) create mode 100644 app/app/views/admins/new_template.html.erb diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb index ca80e5ce8d..6a725c0bcb 100644 --- a/app/app/controllers/admins_controller.rb +++ b/app/app/controllers/admins_controller.rb @@ -16,8 +16,31 @@ def send_forms ] end def edit_templates - # No futuro, aqui você faria: @templates = Template.all - # Por enquanto, usamos dados mockados para preencher a tela: - @templates = [] + # Busca todos os templates criados no banco de dados + @templates = Template.all.order(created_at: :desc) + end + + def new_template + # Inicializa um novo objeto Template vazio + @template = Template.new + end + + def create_template + @template = Template.new(template_params) + + @template.usuario_id = current_user.id + + if @template.save + redirect_to admin_edit_templates_path, notice: "Template '#{@template.nome}' criado com sucesso!" + else + flash.now[:alert] = "Erro ao criar o template. Verifique se o nome foi preenchido corretamente." + render :new_template, status: :unprocessable_entity + end + end + + private + + def template_params + params.require(:template).permit(:nome) end end \ No newline at end of file diff --git a/app/app/views/admins/edit_templates.html.erb b/app/app/views/admins/edit_templates.html.erb index 40c1afa065..dae9dc089c 100644 --- a/app/app/views/admins/edit_templates.html.erb +++ b/app/app/views/admins/edit_templates.html.erb @@ -5,15 +5,25 @@
+ + <%# Exibe a mensagem flash (notice ou alert) %> + <% if notice %> + + <% elsif flash[:alert] %> + + <% end %> +
- <%# LOOP FUTURO: Se @templates estiver vazio, nada aqui será renderizado %> + <%# LOOP sobre Templates do banco de dados %> <% @templates.each do |template| %> -
+
-

<%= template.name %>

-

<%= template.description %>

+ <%# Acessando o atributo diretamente %> +

<%= template.nome %>

+ <%# Mock de descrição: no futuro, substitua por template.description %> +

Semestre e Código

@@ -24,11 +34,13 @@
+ <%# Mock de código/semestre %> +

Criado em: <%= template.created_at.strftime("%d/%m/%Y") %>

<% end %>
- <%= link_to "#", class: "w-full h-full flex items-center justify-center" do %> + <%= link_to admin_new_template_path, class: "w-full h-full flex items-center justify-center" do %> + <% end %>
diff --git a/app/app/views/admins/new_template.html.erb b/app/app/views/admins/new_template.html.erb new file mode 100644 index 0000000000..8fa9c0ed5f --- /dev/null +++ b/app/app/views/admins/new_template.html.erb @@ -0,0 +1,86 @@ +
+ + <%= form_with model: @template, url: admin_templates_path, local: true do |form| %> + +
+ +
+ <%# Exibe erros de validação %> + <% if @template.errors.any? %> +
+
    + <% @template.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> + +
+ + <%# CORREÇÃO: Usar form.text_field :nome %> + <%= form.text_field :nome, required: true, placeholder: "Placeholder", class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %> +
+ +
+

Questão 1

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

Questão 2

+ +
+
+ + +
+
+ + +
+
+ +
+ +
+
+ +
+ +
+ <%= render(ButtonComponent.new(text: "Criar", variant: :success, type: :submit)) %> +
+ +
+ <% end %> +
\ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index e4ebad3176..68598c16da 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -15,8 +15,13 @@ # Rotas de Envio de Formulários get 'admin/send_forms', to: 'admins#send_forms', as: 'admin_send_forms' - # AQUI: Nova rota para Gerenciar Templates + # Rotas de Gerenciamento de Templates get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' + get 'admin/templates/new', to: 'admins#new_template', as: 'admin_new_template' + + # CORREÇÃO: Ativamos a rota POST. O helper gerado por essa linha é admin_templates_path, + # que o form_with espera para a criação (action: create). + post 'admin/templates', to: 'admins#create_template', as: 'admin_templates' root to: 'dashboard#index' end \ No newline at end of file From b9b3748f692d3ca5fc0cf6d08cd753630ff41479 Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Sun, 7 Dec 2025 23:12:21 -0300 Subject: [PATCH 10/19] =?UTF-8?q?feature:=20adicionando=20exclus=C3=A3o=20?= =?UTF-8?q?de=20templates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/admins_controller.rb | 19 +++++++++++++++++++ app/app/views/admins/edit_templates.html.erb | 18 +++++++++++++----- app/config/routes.rb | 2 ++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb index 6a725c0bcb..68c23186ad 100644 --- a/app/app/controllers/admins_controller.rb +++ b/app/app/controllers/admins_controller.rb @@ -38,6 +38,25 @@ def create_template end end + def destroy_template + # 1. Busca o template pelo ID passado na URL (params[:id]) + @template = Template.find(params[:id]) + + # 2. Verifica se o template pertence ao usuário logado (boa prática de segurança) + # Assumindo que o template tem a coluna usuario_id e a associação belongs_to :usuario + if @template.usuario_id != current_user.id + redirect_to admin_edit_templates_path, alert: "Você não tem permissão para excluir este template." + return + end + + template_name = @template.nome # Salva o nome para a mensagem de feedback + + @template.destroy + + # 3. Redireciona de volta para a lista + redirect_to admin_edit_templates_path, notice: "Template '#{template_name}' excluído com sucesso." + end + private def template_params diff --git a/app/app/views/admins/edit_templates.html.erb b/app/app/views/admins/edit_templates.html.erb index dae9dc089c..30a3d1106c 100644 --- a/app/app/views/admins/edit_templates.html.erb +++ b/app/app/views/admins/edit_templates.html.erb @@ -20,21 +20,29 @@
- <%# Acessando o atributo diretamente %>

<%= template.nome %>

- <%# Mock de descrição: no futuro, substitua por template.description %>

Semestre e Código

+ - + + <%# AQUI: LINK DE EXCLUSÃO (DELETE) %> + <%# AQUI: LINK DE EXCLUSÃO (DELETE) %> + <%= link_to admin_template_delete_path(template), + data: { + turbo_method: :delete, + turbo_confirm: "Tem certeza que deseja excluir o template '#{template.nome}'?" + }, + # ADICIONAR VÍRGULA AQUI! + title: "Excluir", + class: "cursor-pointer hover:text-red-600" do %> - + <% end %>
- <%# Mock de código/semestre %>

Criado em: <%= template.created_at.strftime("%d/%m/%Y") %>

<% end %> diff --git a/app/config/routes.rb b/app/config/routes.rb index 68598c16da..46628856c9 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -23,5 +23,7 @@ # que o form_with espera para a criação (action: create). post 'admin/templates', to: 'admins#create_template', as: 'admin_templates' + delete 'admin/templates/:id', to: 'admins#destroy_template', as: 'admin_template_delete' + root to: 'dashboard#index' end \ No newline at end of file From b1231c64f5746f92d2e364dc901810e14f91e91f Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Sun, 7 Dec 2025 23:29:41 -0300 Subject: [PATCH 11/19] =?UTF-8?q?:sparkles:=20feat:=20adi=C3=A7=C3=A3o=20d?= =?UTF-8?q?a=20listagem=20de=20formul=C3=A1rios=20a=20serem=20respondidos?= =?UTF-8?q?=20pelo=20usu=C3=A1rio?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../evaluation_card_component.html.erb | 19 +++++-- .../components/evaluation_card_component.rb | 4 +- app/app/controllers/dashboard_controller.rb | 6 +- app/app/controllers/formularios_controller.rb | 37 +++++++++++++ app/app/helpers/formularios_helper.rb | 2 + app/app/models/formulario.rb | 8 ++- app/app/models/formulario_turma.rb | 2 +- app/app/models/questao_formulario.rb | 4 +- app/app/models/questao_respondida.rb | 3 +- app/app/models/turma.rb | 7 ++- app/app/models/usuario.rb | 7 ++- app/app/views/dashboard/index.html.erb | 26 ++++++--- app/app/views/formularios/show.html.erb | 55 +++++++++++++++++++ app/app/views/layouts/dashboard.html.erb | 5 +- app/config/routes.rb | 6 ++ ...e_opcao_nullable_in_questao_respondidas.rb | 5 ++ app/db/schema.rb | 4 +- app/db/seeds.rb | 43 ++++++++++----- app/spec/helpers/formularios_helper_spec.rb | 15 +++++ app/spec/requests/formularios_spec.rb | 7 +++ 20 files changed, 226 insertions(+), 39 deletions(-) create mode 100644 app/app/controllers/formularios_controller.rb create mode 100644 app/app/helpers/formularios_helper.rb create mode 100644 app/app/views/formularios/show.html.erb create mode 100644 app/db/migrate/20251208022025_change_opcao_nullable_in_questao_respondidas.rb create mode 100644 app/spec/helpers/formularios_helper_spec.rb create mode 100644 app/spec/requests/formularios_spec.rb diff --git a/app/app/components/evaluation_card_component.html.erb b/app/app/components/evaluation_card_component.html.erb index b21ec1d7c2..7adc6a96a3 100644 --- a/app/app/components/evaluation_card_component.html.erb +++ b/app/app/components/evaluation_card_component.html.erb @@ -1,10 +1,21 @@ -
+<% tag_type = @formulario_id ? :a : :div %> +<% link_opts = @formulario_id ? { + href: formulario_path(@formulario_id, turma_id: @turma_id), + data: { turbo_frame: "modal" } # A MÁGICA ACONTECE AQUI + } : {} %> + +<%= content_tag tag_type, link_opts.merge(class: "block bg-white rounded-lg shadow-sm p-6 hover:shadow-md transition-shadow cursor-pointer border border-gray-100 flex flex-col justify-between h-40") do %>

<%= @materia %>

<%= @semestre %>

- -
+ +

<%= @professor %>

+ <% if @formulario_id %> + Responder + <% else %> + Indisponível + <% end %>
-
\ No newline at end of file +<% end %> \ No newline at end of file diff --git a/app/app/components/evaluation_card_component.rb b/app/app/components/evaluation_card_component.rb index 82b0285b34..e70b94b579 100644 --- a/app/app/components/evaluation_card_component.rb +++ b/app/app/components/evaluation_card_component.rb @@ -1,8 +1,10 @@ class EvaluationCardComponent < ViewComponent::Base - def initialize(turma:, materia:, professor:, semestre:) + def initialize(turma:, materia:, professor:, semestre:, formulario_id: nil, turma_id: nil) @turma = turma @materia = materia @professor = professor || "Professor não atribuído" @semestre = semestre + @formulario_id = formulario_id + @turma_id = turma_id end end \ No newline at end of file diff --git a/app/app/controllers/dashboard_controller.rb b/app/app/controllers/dashboard_controller.rb index e442ce4124..05502276b2 100644 --- a/app/app/controllers/dashboard_controller.rb +++ b/app/app/controllers/dashboard_controller.rb @@ -1,8 +1,10 @@ class DashboardController < ApplicationController before_action :require_login - layout 'dashboard' + layout 'dashboard' def index - @turmas = current_user.turmas.includes(:materia) + @turmas = current_user.turmas.includes(:materia, :formularios) + + @ids_respondidos = current_user.formulario_respondidos.pluck(:formulario_id) end end \ No newline at end of file diff --git a/app/app/controllers/formularios_controller.rb b/app/app/controllers/formularios_controller.rb new file mode 100644 index 0000000000..f061a7523b --- /dev/null +++ b/app/app/controllers/formularios_controller.rb @@ -0,0 +1,37 @@ +class FormulariosController < ApplicationController + before_action :require_login + + def show + @formulario = Formulario.find(params[:id]) + @turma_id = params[:turma_id] + end + + def responder + @formulario = Formulario.find(params[:id]) + turma = Turma.find(params[:turma_id]) + + resposta_geral = FormularioRespondido.create!( + formulario: @formulario, + usuario: current_user + ) + + params[:respostas]&.each do |questao_id, valor_resposta| + questao = QuestaoFormulario.find(questao_id) + + nova_resposta = QuestaoRespondida.new( + formulario_respondido: resposta_geral, + questao_formulario: questao + ) + + if questao.tipo_resposta == 'multipla_escolha' + nova_resposta.opcao_formulario_id = valor_resposta + else + nova_resposta.resposta = valor_resposta + end + + nova_resposta.save! + end + + redirect_to dashboard_path, notice: "Avaliação enviada com sucesso!" + end +end \ No newline at end of file diff --git a/app/app/helpers/formularios_helper.rb b/app/app/helpers/formularios_helper.rb new file mode 100644 index 0000000000..3b96bb2209 --- /dev/null +++ b/app/app/helpers/formularios_helper.rb @@ -0,0 +1,2 @@ +module FormulariosHelper +end diff --git a/app/app/models/formulario.rb b/app/app/models/formulario.rb index 50413ca5ea..e7ff95374a 100644 --- a/app/app/models/formulario.rb +++ b/app/app/models/formulario.rb @@ -1,2 +1,8 @@ class Formulario < ApplicationRecord -end + has_many :questao_formularios, dependent: :destroy + + has_many :formulario_respondidos, dependent: :destroy + + has_many :formulario_turmas + has_many :turmas, through: :formulario_turmas +end \ No newline at end of file diff --git a/app/app/models/formulario_turma.rb b/app/app/models/formulario_turma.rb index 06cda79278..c5139486f5 100644 --- a/app/app/models/formulario_turma.rb +++ b/app/app/models/formulario_turma.rb @@ -1,4 +1,4 @@ class FormularioTurma < ApplicationRecord belongs_to :formulario belongs_to :turma -end +end \ No newline at end of file diff --git a/app/app/models/questao_formulario.rb b/app/app/models/questao_formulario.rb index 4a1219b494..880721eeae 100644 --- a/app/app/models/questao_formulario.rb +++ b/app/app/models/questao_formulario.rb @@ -1,3 +1,5 @@ class QuestaoFormulario < ApplicationRecord belongs_to :formulario -end + has_many :opcao_formularios, dependent: :destroy + has_many :questao_respondidas +end \ No newline at end of file diff --git a/app/app/models/questao_respondida.rb b/app/app/models/questao_respondida.rb index 60ab813764..d8f8652f24 100644 --- a/app/app/models/questao_respondida.rb +++ b/app/app/models/questao_respondida.rb @@ -1,5 +1,6 @@ class QuestaoRespondida < ApplicationRecord belongs_to :formulario_respondido belongs_to :questao_formulario - belongs_to :opcao_formulario + + belongs_to :opcao_formulario, optional: true end diff --git a/app/app/models/turma.rb b/app/app/models/turma.rb index 91406ec3ee..99a50194f2 100644 --- a/app/app/models/turma.rb +++ b/app/app/models/turma.rb @@ -1,9 +1,14 @@ class Turma < ApplicationRecord belongs_to :materia + has_many :usuario_turmas has_many :usuarios, through: :usuario_turmas + + has_many :formulario_turmas + has_many :formularios, through: :formulario_turmas def professor - usuarios.where("ocupacao LIKE ?", "%docente%").first + prof = usuarios.find { |u| u.ocupacao.to_s.downcase.include?('docente') || u.ocupacao.to_s.downcase.include?('professor') } + prof ? prof.nome : "Professor não atribuído" end end \ No newline at end of file diff --git a/app/app/models/usuario.rb b/app/app/models/usuario.rb index e8f39fb5f5..07b4360b31 100644 --- a/app/app/models/usuario.rb +++ b/app/app/models/usuario.rb @@ -1,9 +1,14 @@ class Usuario < ApplicationRecord - has_secure_password + has_secure_password validates :email, presence: true, uniqueness: true validates :matricula, presence: true, uniqueness: true validates :nome, presence: true + validates :ocupacao, presence: true + has_many :usuario_turmas has_many :turmas, through: :usuario_turmas + + has_many :formulario_respondidos + has_many :templates end \ No newline at end of file diff --git a/app/app/views/dashboard/index.html.erb b/app/app/views/dashboard/index.html.erb index 4e22f153e2..f0f4983030 100644 --- a/app/app/views/dashboard/index.html.erb +++ b/app/app/views/dashboard/index.html.erb @@ -3,19 +3,31 @@ <% if @turmas.any? %> <% @turmas.each do |turma| %> + + <% formulario = turma.formularios.first %> + + <%# --- LÓGICA DE FILTRAGEM (ALTERADA) --- %> + + <%# 1. Se a turma NÃO tem formulário criado pelo admin, pula e não mostra nada. %> + <% next unless formulario %> + + <%# 2. Se o aluno JÁ respondeu este formulário, pula também. %> + <% next if @ids_respondidos.include?(formulario.id) %> + + <%# ------------------------------------- %> + <%= render(EvaluationCardComponent.new( turma: turma.num_turma, materia: turma.materia.nome, - professor: turma.professor&.nome, - semestre: turma.semestre + professor: turma.professor, + semestre: turma.semestre, + formulario_id: formulario.id, + turma_id: turma.id )) %> + <% end %> <% else %> -
-

Você não está matriculado em nenhuma turma ainda.

-

Importe os dados do SIGAA para visualizar as matérias.

-
- <% end %> + <% end %>
\ No newline at end of file diff --git a/app/app/views/formularios/show.html.erb b/app/app/views/formularios/show.html.erb new file mode 100644 index 0000000000..3589e8a23f --- /dev/null +++ b/app/app/views/formularios/show.html.erb @@ -0,0 +1,55 @@ + + + +
+
+ +
+

+ <%= @formulario.titulo %> +

+ <%= link_to dashboard_path, class: "text-white hover:text-gray-200" do %> + + <% end %> +
+ +
+ <%= form_with url: responder_formulario_path(@formulario), method: :post, local: true do |f| %> + + <%= hidden_field_tag :turma_id, @turma_id %> + + <% @formulario.questao_formularios.each do |questao| %> +
+ + + <% if questao.tipo_resposta == 'texto' %> + <%= text_area_tag "respostas[#{questao.id}]", nil, rows: 3, class: "w-full border border-gray-300 rounded p-2 focus:border-purple-500 focus:outline-none" %> + + <% elsif questao.tipo_resposta == 'multipla_escolha' %> +
+ <% questao.opcao_formularios.each do |opcao| %> +
+ <%= radio_button_tag "respostas[#{questao.id}]", opcao.id, false, class: "text-purple-600 focus:ring-purple-500" %> + +
+ <% end %> +
+ <% end %> +
+ <% end %> + +
+ <%= link_to "Cancelar", dashboard_path, class: "px-4 py-2 bg-gray-200 text-gray-700 rounded hover:bg-gray-300" %> + <%= f.submit "Enviar Avaliação", class: "px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 font-bold cursor-pointer" %> +
+ + <% end %> +
+ +
+
+
\ No newline at end of file diff --git a/app/app/views/layouts/dashboard.html.erb b/app/app/views/layouts/dashboard.html.erb index 73bbcc744d..b5ff559cb8 100644 --- a/app/app/views/layouts/dashboard.html.erb +++ b/app/app/views/layouts/dashboard.html.erb @@ -30,6 +30,7 @@ <%= yield %>
- - + + + \ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index e4ebad3176..c609bfd03a 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -19,4 +19,10 @@ get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' root to: 'dashboard#index' + + resources :formularios, only: [:show] do + member do + post :responder + end + end end \ No newline at end of file diff --git a/app/db/migrate/20251208022025_change_opcao_nullable_in_questao_respondidas.rb b/app/db/migrate/20251208022025_change_opcao_nullable_in_questao_respondidas.rb new file mode 100644 index 0000000000..a64b260f72 --- /dev/null +++ b/app/db/migrate/20251208022025_change_opcao_nullable_in_questao_respondidas.rb @@ -0,0 +1,5 @@ +class ChangeOpcaoNullableInQuestaoRespondidas < ActiveRecord::Migration[8.1] + def change + change_column_null :questao_respondidas, :opcao_formulario_id, true + end +end diff --git a/app/db/schema.rb b/app/db/schema.rb index dca252dd46..4029ad6022 100644 --- a/app/db/schema.rb +++ b/app/db/schema.rb @@ -10,7 +10,7 @@ # # It's strongly recommended that you check this file into your version control system. -ActiveRecord::Schema[8.1].define(version: 2025_12_07_190733) do +ActiveRecord::Schema[8.1].define(version: 2025_12_08_022025) do create_table "departamentos", force: :cascade do |t| t.datetime "created_at", null: false t.string "nome" @@ -81,7 +81,7 @@ create_table "questao_respondidas", force: :cascade do |t| t.datetime "created_at", null: false t.integer "formulario_respondido_id", null: false - t.integer "opcao_formulario_id", null: false + t.integer "opcao_formulario_id" t.integer "questao_formulario_id", null: false t.text "resposta" t.datetime "updated_at", null: false diff --git a/app/db/seeds.rb b/app/db/seeds.rb index 57a920701e..a1d1303c53 100644 --- a/app/db/seeds.rb +++ b/app/db/seeds.rb @@ -78,10 +78,11 @@ UsuarioTurma.create!(usuario: prof, turma: turma_bd) UsuarioTurma.create!(usuario: prof, turma: turma_es) -# Alunos nas turmas (misturado) +# Alunos nas turmas alunos.each_with_index do |aluno, index| UsuarioTurma.create!(usuario: aluno, turma: turma_bd) - UsuarioTurma.create!(usuario: aluno, turma: turma_es) if index.even? # Só alguns em ES + # Matricula em ES apenas se o índice for par (para variar) + UsuarioTurma.create!(usuario: aluno, turma: turma_es) if index.even? end # 5. Templates e Formulários @@ -90,33 +91,45 @@ # Template template = Template.create!(nome: "Avaliação Padrão CIC", usuario: admin) -# Questão de Texto -q1 = QuestaoTemplate.create!( +# Questão de Texto no Template +q1_temp = QuestaoTemplate.create!( texto_questao: "O que você achou da didática do professor?", tipo_resposta: "texto", template: template ) -# Questão de Múltipla Escolha -q2 = QuestaoTemplate.create!( +# Questão de Múltipla Escolha no Template +q2_temp = QuestaoTemplate.create!( texto_questao: "Como você avalia a infraestrutura da sala?", tipo_resposta: "multipla_escolha", template: template ) -OpcaoTemplate.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_template: q2) -OpcaoTemplate.create!(texto_opcao: "Regular", numero_opcao: 2, questao_template: q2) -OpcaoTemplate.create!(texto_opcao: "Boa", numero_opcao: 3, questao_template: q2) +OpcaoTemplate.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_template: q2_temp) +OpcaoTemplate.create!(texto_opcao: "Regular", numero_opcao: 2, questao_template: q2_temp) +OpcaoTemplate.create!(texto_opcao: "Boa", numero_opcao: 3, questao_template: q2_temp) # Criar um Formulário Aplicado (Cópia do Template para a Turma de BD) +# Isso simula o processo de "Aplicar Template" form = Formulario.create!(titulo: "Avaliação Final - Bancos de Dados", so_alunos: true) FormularioTurma.create!(formulario: form, turma: turma_bd) -# Copiar questões do template para o formulário (simulando a lógica real) -QuestaoFormulario.create!(texto_questao: q1.texto_questao, tipo_resposta: q1.tipo_resposta, formulario: form) -q_form_2 = QuestaoFormulario.create!(texto_questao: q2.texto_questao, tipo_resposta: q2.tipo_resposta, formulario: form) -OpcaoFormulario.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_formulario: q_form_2) -OpcaoFormulario.create!(texto_opcao: "Regular", numero_opcao: 2, questao_formulario: q_form_2) -OpcaoFormulario.create!(texto_opcao: "Boa", numero_opcao: 3, questao_formulario: q_form_2) +# Copiar questões do template para o formulário +QuestaoFormulario.create!( + texto_questao: q1_temp.texto_questao, + tipo_resposta: q1_temp.tipo_resposta, + formulario: form +) + +q2_form = QuestaoFormulario.create!( + texto_questao: q2_temp.texto_questao, + tipo_resposta: q2_temp.tipo_resposta, + formulario: form +) + +# Copiar opções da questão múltipla escolha +OpcaoFormulario.create!(texto_opcao: "Ruim", numero_opcao: 1, questao_formulario: q2_form) +OpcaoFormulario.create!(texto_opcao: "Regular", numero_opcao: 2, questao_formulario: q2_form) +OpcaoFormulario.create!(texto_opcao: "Boa", numero_opcao: 3, questao_formulario: q2_form) puts "✅ Seed concluído com sucesso!" puts "--------------------------------------------------" diff --git a/app/spec/helpers/formularios_helper_spec.rb b/app/spec/helpers/formularios_helper_spec.rb new file mode 100644 index 0000000000..b5045f4f06 --- /dev/null +++ b/app/spec/helpers/formularios_helper_spec.rb @@ -0,0 +1,15 @@ +require 'rails_helper' + +# Specs in this file have access to a helper object that includes +# the FormulariosHelper. For example: +# +# describe FormulariosHelper do +# describe "string concat" do +# it "concats two strings with spaces" do +# expect(helper.concat_strings("this","that")).to eq("this that") +# end +# end +# end +RSpec.describe FormulariosHelper, type: :helper do + pending "add some examples to (or delete) #{__FILE__}" +end diff --git a/app/spec/requests/formularios_spec.rb b/app/spec/requests/formularios_spec.rb new file mode 100644 index 0000000000..75aea83155 --- /dev/null +++ b/app/spec/requests/formularios_spec.rb @@ -0,0 +1,7 @@ +require 'rails_helper' + +RSpec.describe "Formularios", type: :request do + describe "GET /index" do + pending "add some examples (or delete) #{__FILE__}" + end +end From d47233d01f80c51e08272724ef34d55c19cf82ed Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Sun, 7 Dec 2025 23:44:50 -0300 Subject: [PATCH 12/19] =?UTF-8?q?refactor:=20melhorando=20cria=C3=A7=C3=A3?= =?UTF-8?q?o=20de=20templates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/javascript/application.js | 1 + .../controllers/template_form_handler.js | 126 ++++++++++++++++++ app/app/views/admins/new_template.html.erb | 55 +++++--- 3 files changed, 164 insertions(+), 18 deletions(-) create mode 100644 app/app/javascript/controllers/template_form_handler.js diff --git a/app/app/javascript/application.js b/app/app/javascript/application.js index 0d7b49404c..ec0bf07de9 100644 --- a/app/app/javascript/application.js +++ b/app/app/javascript/application.js @@ -1,3 +1,4 @@ // Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails import "@hotwired/turbo-rails" import "controllers" +import "controllers/template_form_handler" \ No newline at end of file diff --git a/app/app/javascript/controllers/template_form_handler.js b/app/app/javascript/controllers/template_form_handler.js new file mode 100644 index 0000000000..817dc915f1 --- /dev/null +++ b/app/app/javascript/controllers/template_form_handler.js @@ -0,0 +1,126 @@ +document.addEventListener('turbo:load', () => { + const formContainer = document.querySelector('.template-form-container'); + if (!formContainer) return; + + let questionIndex = 3; // Começa após Questão 2 (mock) + + // --- Funções de Manipulação do DOM --- + + // 1. Alterna a visibilidade do campo 'Opções' + const toggleOptionsVisibility = (typeSelect) => { + // Encontra o container da questão (elemento pai mais próximo que contém todos os campos) + const questionBlock = typeSelect.closest('.js-question-block'); + if (!questionBlock) return; + + // Encontra o container de opções e o botão de adição de opções dentro do bloco + const optionsContainer = questionBlock.querySelector('.js-options-container'); + const addOptionButton = questionBlock.querySelector('.js-add-option-button'); + + if (typeSelect.value === 'Radio') { + if (optionsContainer) optionsContainer.classList.remove('hidden'); + if (addOptionButton) addOptionButton.classList.remove('hidden'); + } else { + if (optionsContainer) optionsContainer.classList.add('hidden'); + if (addOptionButton) addOptionButton.classList.add('hidden'); + } + }; + + // 2. Adiciona um novo campo de Opção (botão cinza '+') + const addOptionField = (event) => { + event.preventDefault(); + const optionList = event.target.closest('.js-question-block').querySelector('.js-options-list'); + if (!optionList) return; + + const newOptionInput = document.createElement('div'); + newOptionInput.classList.add('mt-2'); + // Usamos um nome de campo genérico que o Rails precisará processar como array (e.g., questions[][options][]) + newOptionInput.innerHTML = ` + + `; + optionList.appendChild(newOptionInput); + }; + + // 3. Adiciona uma nova Questão completa (botão roxo '+') + const addNewQuestionBlock = (event) => { + event.preventDefault(); + + const newQuestionHTML = ` +
+

Questão ${questionIndex}

+ +
+
+ + +
+
+ + +
+
+ +
+ +
+ +
+
+ +
+ +
+
+ `; + + // Insere o novo bloco antes do botão roxo de adicionar questão + const mainAddButtonContainer = event.target.closest('.js-main-add-button-container'); + if (mainAddButtonContainer) { + mainAddButtonContainer.insertAdjacentHTML('beforebegin', newQuestionHTML); + } + + questionIndex++; + + // Re-atribui listeners após a adição de novos elementos + attachListeners(); + }; + + // --- Inicialização e Atribuição de Listeners --- + + const attachListeners = () => { + // Remove listeners antigos para evitar duplicação (especialmente importante com Turbo) + // (Simplificado, mas idealmente seria necessário um cleanup mais formal) + + // Listeners para Tipo de Questão (Select) + formContainer.querySelectorAll('.js-type-select').forEach(select => { + // Remove o listener anterior para evitar chamadas duplicadas + select.removeEventListener('change', (e) => toggleOptionsVisibility(e.target)); + + // Adiciona o novo listener + select.addEventListener('change', (e) => toggleOptionsVisibility(e.target)); + + // Inicializa a visibilidade no carregamento + toggleOptionsVisibility(select); + }); + + // Listeners para Botão Adicionar Opção (Cinza) + formContainer.querySelectorAll('.js-add-option').forEach(button => { + button.removeEventListener('click', addOptionField); + button.addEventListener('click', addOptionField); + }); + + // Listener para Botão Adicionar Questão (Roxo) + const mainAddQuestionButton = formContainer.querySelector('.js-add-question'); + if (mainAddQuestionButton) { + mainAddQuestionButton.removeEventListener('click', addNewQuestionBlock); + mainAddQuestionButton.addEventListener('click', addNewQuestionBlock); + } + }; + + // Inicia a atribuição de listeners na carga da página + attachListeners(); +}); \ No newline at end of file diff --git a/app/app/views/admins/new_template.html.erb b/app/app/views/admins/new_template.html.erb index 8fa9c0ed5f..60dede9d65 100644 --- a/app/app/views/admins/new_template.html.erb +++ b/app/app/views/admins/new_template.html.erb @@ -1,6 +1,7 @@
- <%= form_with model: @template, url: admin_templates_path, local: true do |form| %> + <%# Adicionado classe container para o JavaScript %> + <%= form_with model: @template, url: admin_templates_path, local: true, html: { class: 'template-form-container' } do |form| %>
@@ -18,19 +19,20 @@
- <%# CORREÇÃO: Usar form.text_field :nome %> <%= form.text_field :nome, required: true, placeholder: "Placeholder", class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %>
-
+ <%# Classe de identificação do Bloco %> +

Questão 1

- + +
@@ -39,27 +41,30 @@
-
+ <%# Container de Opções: Visível por padrão se for Radio %> +
- +
+ +
-
-
-
+

Questão 2

- + +
@@ -67,14 +72,28 @@
- -
-
+
+ +
+
From 491184168a7ecc0c3762d5c0b8a023dcca13f4f9 Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Mon, 8 Dec 2025 00:01:43 -0300 Subject: [PATCH 13/19] =?UTF-8?q?:sparkles:=20feat:=20implementa=C3=A7?= =?UTF-8?q?=C3=A3o=20da=20exporta=C3=A7=C3=A3o=20de=20resultados=20como=20?= =?UTF-8?q?.csv?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/resultados_controller.rb | 20 ++++++++ app/app/models/formulario.rb | 31 +++++++++++++ app/app/models/formulario_respondido.rb | 4 ++ app/app/views/admins/dashboard.html.erb | 2 +- app/app/views/resultados/index.html.erb | 48 ++++++++++++++++++++ app/config/routes.rb | 16 +++---- 6 files changed, 112 insertions(+), 9 deletions(-) create mode 100644 app/app/controllers/resultados_controller.rb create mode 100644 app/app/views/resultados/index.html.erb diff --git a/app/app/controllers/resultados_controller.rb b/app/app/controllers/resultados_controller.rb new file mode 100644 index 0000000000..ee3a4f783e --- /dev/null +++ b/app/app/controllers/resultados_controller.rb @@ -0,0 +1,20 @@ +class ResultadosController < ApplicationController + before_action :require_login + layout 'dashboard' + + def index + # Lista apenas formulários que têm pelo menos uma resposta + @formularios = Formulario.joins(:formulario_respondidos).distinct + end + + def baixar + @formulario = Formulario.find(params[:id]) + + respond_to do |format| + format.csv do + send_data @formulario.gerar_csv, + filename: "resultados-#{Date.today}-#{@formulario.titulo.parameterize}.csv" + end + end + end +end \ No newline at end of file diff --git a/app/app/models/formulario.rb b/app/app/models/formulario.rb index e7ff95374a..467f6bf102 100644 --- a/app/app/models/formulario.rb +++ b/app/app/models/formulario.rb @@ -1,3 +1,5 @@ +require 'csv' + class Formulario < ApplicationRecord has_many :questao_formularios, dependent: :destroy @@ -5,4 +7,33 @@ class Formulario < ApplicationRecord has_many :formulario_turmas has_many :turmas, through: :formulario_turmas + + def gerar_csv + CSV.generate(headers: true) do |csv| + questoes = questao_formularios.order(:id) + headers = ['Matrícula', 'Nome'] + questoes.map(&:texto_questao) + csv << headers + + formulario_respondidos.includes(:usuario, questao_respondidas: :opcao_formulario).each do |resposta_geral| + linha = [ + resposta_geral.usuario.matricula, + resposta_geral.usuario.nome + ] + + questoes.each do |questao| + resposta = resposta_geral.questao_respondidas.find_by(questao_formulario: questao) + + valor = if resposta&.opcao_formulario + resposta.opcao_formulario.texto_opcao + else + resposta&.resposta + end + + linha << valor + end + + csv << linha + end + end + end end \ No newline at end of file diff --git a/app/app/models/formulario_respondido.rb b/app/app/models/formulario_respondido.rb index c857092ef6..3569b3b3f7 100644 --- a/app/app/models/formulario_respondido.rb +++ b/app/app/models/formulario_respondido.rb @@ -1,4 +1,8 @@ class FormularioRespondido < ApplicationRecord belongs_to :formulario belongs_to :usuario + + has_many :questao_respondidas, dependent: :destroy + + accepts_nested_attributes_for :questao_respondidas end diff --git a/app/app/views/admins/dashboard.html.erb b/app/app/views/admins/dashboard.html.erb index 6b04ccec56..cf837728c7 100644 --- a/app/app/views/admins/dashboard.html.erb +++ b/app/app/views/admins/dashboard.html.erb @@ -16,7 +16,7 @@ <%= render(ButtonComponent.new(text: "Enviar Formulários", variant: :secondary, type: :button)) %> <% end %> - <%= link_to "#" do %> + <%= link_to resultados_path do %> <%= render(ButtonComponent.new(text: "Resultados", variant: :tertiary, type: :button)) %> <% end %> diff --git a/app/app/views/resultados/index.html.erb b/app/app/views/resultados/index.html.erb new file mode 100644 index 0000000000..8c60214fea --- /dev/null +++ b/app/app/views/resultados/index.html.erb @@ -0,0 +1,48 @@ +
+

Resultados das Avaliações

+ +
+ + + + + + + + + + <% @formularios.each do |form| %> + + + + + + <% end %> + +
+ Título do Formulário + + Respostas + + Ação +
+

<%= form.titulo %>

+
+ + + <%= form.formulario_respondidos.count %> respostas + + + <%= link_to baixar_resultado_path(form, format: :csv), class: "text-blue-600 hover:text-blue-900 flex items-center gap-1" do %> + + Baixar CSV + <% end %> +
+ + <% if @formularios.empty? %> +
+ Nenhum formulário foi respondido ainda. +
+ <% end %> +
+
\ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index 1292a9f3e1..3a0fa09bf6 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -5,26 +5,26 @@ get 'dashboard', to: 'dashboard#index' - # Rotas de Administração get 'admin', to: 'admins#dashboard', as: 'admin' - # Rotas de Importação get 'admin/importar', to: 'admins#import_form', as: 'admin_importar_form' post 'admin/importar', to: 'admins#importar' - # Rotas de Envio de Formulários get 'admin/send_forms', to: 'admins#send_forms', as: 'admin_send_forms' - # Rotas de Gerenciamento de Templates get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' get 'admin/templates/new', to: 'admins#new_template', as: 'admin_new_template' - - # CORREÇÃO: Ativamos a rota POST. O helper gerado por essa linha é admin_templates_path, - # que o form_with espera para a criação (action: create). post 'admin/templates', to: 'admins#create_template', as: 'admin_templates' - delete 'admin/templates/:id', to: 'admins#destroy_template', as: 'admin_template_delete' + scope '/admin' do + resources :resultados, only: [:index] do + member do + get :baixar + end + end + end + root to: 'dashboard#index' resources :formularios, only: [:show] do From 677ceabb176831b0558371aae62f6709de7229bb Mon Sep 17 00:00:00 2001 From: Lucca Schoen Date: Mon, 8 Dec 2025 00:16:24 -0300 Subject: [PATCH 14/19] =?UTF-8?q?implementa=C3=A7=C3=A3o=20da=20tela=20de?= =?UTF-8?q?=20cadastro?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/.ruby-version | 2 +- app/Gemfile | 2 +- app/app/components/button_component.html.erb | 12 ++- app/app/components/button_component.rb | 2 +- .../components/form_input_component.html.erb | 20 ++--- app/app/components/form_input_component.rb | 12 ++- app/app/controllers/users_controller.rb | 34 ++++++++ app/app/views/sessions/new.html.erb | 9 ++ app/app/views/users/new.html.erb | 87 +++++++++++++++++++ app/bin/brakeman | 0 app/bin/bundler-audit | 0 app/bin/ci | 0 app/bin/dev | 0 app/bin/docker-entrypoint | 0 app/bin/importmap | 0 app/bin/jobs | 0 app/bin/kamal | 0 app/bin/rails | 0 app/bin/rake | 0 app/bin/rubocop | 0 app/bin/setup | 0 app/bin/thrust | 0 app/config/routes.rb | 3 + 23 files changed, 166 insertions(+), 17 deletions(-) create mode 100644 app/app/controllers/users_controller.rb create mode 100644 app/app/views/users/new.html.erb mode change 100644 => 100755 app/bin/brakeman mode change 100644 => 100755 app/bin/bundler-audit mode change 100644 => 100755 app/bin/ci mode change 100644 => 100755 app/bin/dev mode change 100644 => 100755 app/bin/docker-entrypoint mode change 100644 => 100755 app/bin/importmap mode change 100644 => 100755 app/bin/jobs mode change 100644 => 100755 app/bin/kamal mode change 100644 => 100755 app/bin/rails mode change 100644 => 100755 app/bin/rake mode change 100644 => 100755 app/bin/rubocop mode change 100644 => 100755 app/bin/setup mode change 100644 => 100755 app/bin/thrust diff --git a/app/.ruby-version b/app/.ruby-version index 5f6fc5edc2..be94e6f53d 100644 --- a/app/.ruby-version +++ b/app/.ruby-version @@ -1 +1 @@ -3.3.10 +3.2.2 diff --git a/app/Gemfile b/app/Gemfile index 99962a2c75..d525346be1 100644 --- a/app/Gemfile +++ b/app/Gemfile @@ -23,7 +23,7 @@ gem "jbuilder" gem "bcrypt", "~> 3.1.7" # Windows does not include zoneinfo files, so bundle the tzinfo-data gem -gem "tzinfo-data", platforms: %i[ windows jruby ] +gem "tzinfo-data", platforms: %i[jruby] # Use the database-backed adapters for Rails.cache, Active Job, and Action Cable gem "solid_cache" diff --git a/app/app/components/button_component.html.erb b/app/app/components/button_component.html.erb index 8e1aa8b7ea..93c5bf0b69 100644 --- a/app/app/components/button_component.html.erb +++ b/app/app/components/button_component.html.erb @@ -1,3 +1,9 @@ - \ No newline at end of file +<% if @link.present? %> + <%= link_to @link, role: "button", class: classes do %> + <%= @text %> + <% end %> +<% else %> + +<% end %> \ No newline at end of file diff --git a/app/app/components/button_component.rb b/app/app/components/button_component.rb index 2b6baa88c6..9bd01c9719 100644 --- a/app/app/components/button_component.rb +++ b/app/app/components/button_component.rb @@ -7,7 +7,7 @@ def initialize(text:, type: :submit, variant: :primary, link: nil) end def classes - base = "w-full py-3 px-6 rounded font-bold text-sm focus:outline-none transition duration-150 shadow-md cursor-pointer" + base = "w-full inline-block py-3 px-6 rounded font-bold text-sm text-center focus:outline-none transition duration-150 shadow-md cursor-pointer" case @variant when :primary diff --git a/app/app/components/form_input_component.html.erb b/app/app/components/form_input_component.html.erb index 4903e9838c..234f63ba72 100644 --- a/app/app/components/form_input_component.html.erb +++ b/app/app/components/form_input_component.html.erb @@ -1,12 +1,12 @@
- - + <% if @form && @attribute %> + <%= @form.label @attribute, @label, class: "block text-gray-600 text-sm font-bold mb-2 ml-1" %> + <%= @form.send "#{@type}_field", @attribute, + class: "appearance-none border border-gray-200 rounded w-full py-3 px-4 text-gray-700 leading-tight focus:outline-none focus:border-purple-500 placeholder-gray-400", + placeholder: @placeholder %> + <% else %> + <%= label_tag @name, @label, class: "block text-gray-600 text-sm font-bold mb-2 ml-1" %> + <%= tag.input type: @type, name: @name, id: @name, placeholder: @placeholder, + class: "appearance-none border border-gray-200 rounded w-full py-3 px-4 text-gray-700 leading-tight focus:outline-none focus:border-purple-500 placeholder-gray-400" %> + <% end %>
\ No newline at end of file diff --git a/app/app/components/form_input_component.rb b/app/app/components/form_input_component.rb index 5630c71970..f61d398c04 100644 --- a/app/app/components/form_input_component.rb +++ b/app/app/components/form_input_component.rb @@ -1,9 +1,19 @@ # app/components/form_input_component.rb class FormInputComponent < ViewComponent::Base - def initialize(label:, name:, type: :text, placeholder: "") + # Initialize accepts either a model-backed input via `form`+`attribute` + # or an unbound input via `name` (used in sessions/login view). + def initialize(label:, form: nil, attribute: nil, name: nil, type: :text, placeholder: "") @label = label + @form = form + @attribute = attribute @name = name @type = type @placeholder = placeholder + + # If attribute was provided but no explicit name, derive a name fallback + @name ||= @attribute.to_s if @attribute end + + # When using an ERB template, ViewComponent will render that template. + # The template can access the instance variables set in `initialize`. end \ No newline at end of file diff --git a/app/app/controllers/users_controller.rb b/app/app/controllers/users_controller.rb new file mode 100644 index 0000000000..d8379df94f --- /dev/null +++ b/app/app/controllers/users_controller.rb @@ -0,0 +1,34 @@ +# app/controllers/users_controller.rb +class UsersController < ApplicationController + + def new + # CORREÇÃO 1: Usar @usuario para refletir o nome do Modelo 'Usuario' + @usuario = Usuario.new + end + + def create + # CORREÇÃO 2: Usar @usuario ao criar a instância + @usuario = Usuario.new(user_params) + + if @usuario.save + # CORREÇÃO 3: Usar @usuario ao salvar na sessão + session[:user_id] = @usuario.id + flash[:notice] = "Cadastro realizado com sucesso!" + redirect_to root_path + else + # Se falhar, re-renderiza o formulário :new, usando @usuario + flash.now[:alert] = "Não foi possível realizar o cadastro." + render :new, status: :unprocessable_entity + end + end + + private + + def user_params + # CORREÇÃO 4: O Rails espera que o nome do recurso seja pluralizado e snake_cased + # Se o nome do seu modelo é 'Usuario', ele deve vir como 'usuario' no params + # Mantenha o params.require(:user) se você não quiser mudar a view. + # Mas o mais correto para o modelo 'Usuario' é params.require(:usuario) + params.require(:usuario).permit(:nome, :email, :matricula, :password, :password_confirmation, :ocupacao) + end +end \ No newline at end of file diff --git a/app/app/views/sessions/new.html.erb b/app/app/views/sessions/new.html.erb index 4272016e45..75636a1e40 100644 --- a/app/app/views/sessions/new.html.erb +++ b/app/app/views/sessions/new.html.erb @@ -45,6 +45,15 @@ )) %>
+
+ <%= render(ButtonComponent.new( + text: "Cadastrar", + type: :button, + variant: :primary, + link: cadastro_path + )) %> +
+ <% end %>
diff --git a/app/app/views/users/new.html.erb b/app/app/views/users/new.html.erb new file mode 100644 index 0000000000..4d171d0a33 --- /dev/null +++ b/app/app/views/users/new.html.erb @@ -0,0 +1,87 @@ +
+
+ +
+ +

CADASTRO

+ + <% if flash[:alert] %> +
+ <%= flash[:alert] %> +
+ <% end %> + + <%# --- FORMULÁRIO DE CADASTRO --- %> + <%= form_with model: @usuario, url: cadastro_path, local: true, class: "space-y-6" do |form| %> + + <%# Campo Nome - REMOVIDAS AS CHAVES {} %> + <%= render FormInputComponent.new( + label: "Nome Completo", + form: form, + attribute: :nome, + type: :text, + placeholder: "Prof. Pardal" + ) %> + + <%# Campo Email - REMOVIDAS AS CHAVES {} %> + <%= render FormInputComponent.new( + label: "Email Institucional", + form: form, + attribute: :email, + type: :email, + placeholder: "pardal@unb.br" + ) %> + + <%# Campo Matrícula - REMOVIDAS AS CHAVES {} %> + <%= render FormInputComponent.new( + label: "Matrícula", + form: form, + attribute: :matricula, + type: :text, + placeholder: "000002" + ) %> + + <%# Campo Senha - REMOVIDAS AS CHAVES {} %> + <%= render FormInputComponent.new( + label: "Senha", + form: form, + attribute: :password, + type: :password, + placeholder: "Sua senha segura" + ) %> + + <%# Campo Confirmação de Senha - REMOVIDAS AS CHAVES {} %> + <%= render FormInputComponent.new( + label: "Confirme a Senha", + form: form, + attribute: :password_confirmation, + type: :password, + placeholder: "Repita a senha" + ) %> + + <%# Campo Ocupação (Select/Dropdown) - ESTE JÁ ESTAVA CORRETO %> +
+ <%= form.label :ocupacao, "Ocupação", class: "block text-sm font-medium text-gray-700" %> + <%= form.select :ocupacao, options_for_select(["docente", "discente"], @usuario.ocupacao), + { include_blank: "Selecione a Ocupação" }, + { class: "mt-1 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md" } %> +
+ +
+ <%# Botão de Cadastro - REMOVIDAS AS CHAVES {} %> + <%= render ButtonComponent.new( + text: "Cadastrar", + type: :submit, + variant: :primary + ) %> +
+ + <% end %> +
+ + + +
+
\ No newline at end of file diff --git a/app/bin/brakeman b/app/bin/brakeman old mode 100644 new mode 100755 diff --git a/app/bin/bundler-audit b/app/bin/bundler-audit old mode 100644 new mode 100755 diff --git a/app/bin/ci b/app/bin/ci old mode 100644 new mode 100755 diff --git a/app/bin/dev b/app/bin/dev old mode 100644 new mode 100755 diff --git a/app/bin/docker-entrypoint b/app/bin/docker-entrypoint old mode 100644 new mode 100755 diff --git a/app/bin/importmap b/app/bin/importmap old mode 100644 new mode 100755 diff --git a/app/bin/jobs b/app/bin/jobs old mode 100644 new mode 100755 diff --git a/app/bin/kamal b/app/bin/kamal old mode 100644 new mode 100755 diff --git a/app/bin/rails b/app/bin/rails old mode 100644 new mode 100755 diff --git a/app/bin/rake b/app/bin/rake old mode 100644 new mode 100755 diff --git a/app/bin/rubocop b/app/bin/rubocop old mode 100644 new mode 100755 diff --git a/app/bin/setup b/app/bin/setup old mode 100644 new mode 100755 diff --git a/app/bin/thrust b/app/bin/thrust old mode 100644 new mode 100755 diff --git a/app/config/routes.rb b/app/config/routes.rb index 3a0fa09bf6..0c7a341054 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -3,6 +3,9 @@ post 'login', to: 'sessions#create' delete 'logout', to: 'sessions#destroy' + get 'cadastro', to: 'users#new', as: 'cadastro' + post 'cadastro', to: 'users#create' + get 'dashboard', to: 'dashboard#index' get 'admin', to: 'admins#dashboard', as: 'admin' From fec36ecf94aadb5555a2a6462bd19d704f04bd92 Mon Sep 17 00:00:00 2001 From: DaviHVL Date: Mon, 8 Dec 2025 00:40:03 -0300 Subject: [PATCH 15/19] =?UTF-8?q?:sparkles:=20feat:=20adi=C3=A7=C3=A3o=20d?= =?UTF-8?q?a=20importa=C3=A7=C3=A3o=20de=20dados=20com=20cadastro=20autom?= =?UTF-8?q?=C3=A1tico?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/admins_controller.rb | 34 ++++++--- app/app/services/sigaa_service.rb | 92 ++++++++++++++++-------- 2 files changed, 89 insertions(+), 37 deletions(-) diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb index 68c23186ad..e0d722cf1e 100644 --- a/app/app/controllers/admins_controller.rb +++ b/app/app/controllers/admins_controller.rb @@ -2,12 +2,34 @@ class AdminsController < ApplicationController before_action :require_login layout 'dashboard' + # --- Menu Principal --- def dashboard end + # --- Funcionalidade de Importação --- def import_form end + # ADICIONADO: O método que processa o upload + def importar + arquivo_turmas = params[:arquivo_turmas] + arquivo_membros = params[:arquivo_membros] + + if arquivo_turmas.present? && arquivo_membros.present? + # Caminho temporário dos arquivos enviados + path_turmas = arquivo_turmas.path + path_membros = arquivo_membros.path + + # Chama o serviço para processar + SigaaService.new(path_turmas, path_membros).call + + redirect_to admin_path, notice: "Importação realizada com sucesso!" + else + redirect_to admin_importar_form_path, alert: "Por favor, anexe os dois arquivos JSON." + end + end + + # --- Funcionalidade de Enviar Formulários --- def send_forms # Lógica para carregar dados (formulários, templates) @forms_to_send = [ @@ -15,19 +37,18 @@ def send_forms # ... ] end + + # --- Funcionalidade de Templates (Manual) --- def edit_templates - # Busca todos os templates criados no banco de dados @templates = Template.all.order(created_at: :desc) end def new_template - # Inicializa um novo objeto Template vazio @template = Template.new end def create_template @template = Template.new(template_params) - @template.usuario_id = current_user.id if @template.save @@ -39,21 +60,16 @@ def create_template end def destroy_template - # 1. Busca o template pelo ID passado na URL (params[:id]) @template = Template.find(params[:id]) - # 2. Verifica se o template pertence ao usuário logado (boa prática de segurança) - # Assumindo que o template tem a coluna usuario_id e a associação belongs_to :usuario if @template.usuario_id != current_user.id redirect_to admin_edit_templates_path, alert: "Você não tem permissão para excluir este template." return end - template_name = @template.nome # Salva o nome para a mensagem de feedback - + template_name = @template.nome @template.destroy - # 3. Redireciona de volta para a lista redirect_to admin_edit_templates_path, notice: "Template '#{template_name}' excluído com sucesso." end diff --git a/app/app/services/sigaa_service.rb b/app/app/services/sigaa_service.rb index 50709a8d75..00c427af85 100644 --- a/app/app/services/sigaa_service.rb +++ b/app/app/services/sigaa_service.rb @@ -7,9 +7,23 @@ def initialize(classes_path, members_path) end def call - import_classes if File.exist?(@classes_path) + puts ">>> INICIANDO SERVIÇO SIGAA <<<" - import_members if File.exist?(@members_path) + if File.exist?(@classes_path) + puts "> Arquivo de Turmas encontrado. Processando..." + import_classes + else + puts "> ERRO: Arquivo de Turmas NÃO encontrado no caminho: #{@classes_path}" + end + + if File.exist?(@members_path) + puts "> Arquivo de Membros encontrado. Processando..." + import_members + else + puts "> ERRO: Arquivo de Membros NÃO encontrado no caminho: #{@members_path}" + end + + puts ">>> SERVIÇO FINALIZADO <<<" end private @@ -17,67 +31,89 @@ def call def import_classes file_content = File.read(@classes_path) data = JSON.parse(file_content) + puts "> Lendo #{data.size} matérias do JSON..." data.each do |entry| + # Dept Code dept_code = entry['code'][0..2] - - departamento = Departamento.find_or_create_by!(nome: dept_code) # Usando o código como nome provisório + dep = Departamento.find_or_create_by!(nome: dept_code) - materia = Materia.find_or_create_by!(codigo: entry['code']) do |m| + # Matéria + mat = Materia.find_or_create_by!(codigo: entry['code']) do |m| m.nome = entry['name'] - m.departamento = departamento + m.departamento = dep end + puts " - Matéria Processada: #{mat.nome} (#{mat.codigo})" - Turma.find_or_create_by!( + # Turma + turma = Turma.find_or_create_by!( num_turma: entry['class']['classCode'], semestre: entry['class']['semester'], - materia: materia + materia: mat ) + puts " - Turma Criada/Encontrada: #{turma.num_turma} - #{turma.semestre}" end + rescue => e + puts "CRASH EM IMPORT_CLASSES: #{e.message}" end def import_members file_content = File.read(@members_path) data = JSON.parse(file_content) + puts "> Lendo #{data.size} grupos de membros..." data.each do |entry| + puts "> Verificando grupo: #{entry['code']} - Turma #{entry['classCode']}" + materia = Materia.find_by(codigo: entry['code']) - next unless materia # Pula se a matéria não existir + unless materia + puts " [PULADO] Matéria #{entry['code']} não existe no banco." + next + end turma = Turma.find_by( num_turma: entry['classCode'], semestre: entry['semester'], materia: materia ) - next unless turma # Pula se a turma não existir + unless turma + puts " [PULADO] Turma #{entry['classCode']} não encontrada para esta matéria." + next + end + # Docente if entry['docente'] - process_user(entry['docente'], turma, 'Professor') + puts " -> Processando Docente..." + process_user(entry['docente'], turma, 'docente') end - entry['dicente']&.each do |student_data| - process_user(student_data, turma, 'Aluno') + # Discentes + if entry['dicente'] + puts " -> Processando #{entry['dicente'].size} Discentes..." + entry['dicente'].each do |student_data| + process_user(student_data, turma, 'discente') + end end end + rescue => e + puts "CRASH EM IMPORT_MEMBERS: #{e.message}" end def process_user(user_data, turma, ocupacao_padrao) usuario = Usuario.find_or_initialize_by(matricula: user_data['usuario']) - - if usuario.new_record? - usuario.nome = user_data['nome'] - usuario.email = user_data['email'] - usuario.ocupacao = ocupacao_padrao - - usuario.password = user_data['usuario'] - usuario.password_confirmation = user_data['usuario'] - usuario.is_admin = false - usuario.save! + + usuario.nome = user_data['nome'] + usuario.email = user_data['email'] + usuario.ocupacao = ocupacao_padrao + usuario.password = user_data['usuario'] + usuario.password_confirmation = user_data['usuario'] + usuario.is_admin = false if usuario.new_record? + + if usuario.save + print "." # Imprime um pontinho para cada sucesso + UsuarioTurma.find_or_create_by!(usuario: usuario, turma: turma) + else + puts "\n [ERRO AO SALVAR USER] #{usuario.nome}: #{usuario.errors.full_messages.join(', ')}" end - - UsuarioTurma.find_or_create_by!( - usuario: usuario, - turma: turma - ) end end \ No newline at end of file From c77d66cabd57ec757c4c5cccd572b30ebe91d96f Mon Sep 17 00:00:00 2001 From: Caio Balaniuk Date: Mon, 8 Dec 2025 15:08:36 -0300 Subject: [PATCH 16/19] =?UTF-8?q?fix:=20alterando=20cria=C3=A7=C3=A3o=20de?= =?UTF-8?q?=20templates?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/controllers/admins_controller.rb | 131 +++++++++++-- .../controllers/template_form_handler.js | 112 ++++++------ app/app/models/opcao_template.rb | 7 +- app/app/models/questao_template.rb | 13 +- app/app/models/template.rb | 15 +- app/app/views/admins/edit_templates.html.erb | 14 +- app/app/views/admins/new_template.html.erb | 82 +-------- app/app/views/admins/update_template.html.erb | 173 ++++++++++++++++++ app/config/routes.rb | 8 +- 9 files changed, 394 insertions(+), 161 deletions(-) create mode 100644 app/app/views/admins/update_template.html.erb diff --git a/app/app/controllers/admins_controller.rb b/app/app/controllers/admins_controller.rb index 68c23186ad..d5b66b612e 100644 --- a/app/app/controllers/admins_controller.rb +++ b/app/app/controllers/admins_controller.rb @@ -1,6 +1,8 @@ class AdminsController < ApplicationController before_action :require_login layout 'dashboard' + before_action :set_template, only: [:edit_template, :update_template, :destroy_template] + skip_before_action :require_login, only: [:create_template] def dashboard end @@ -15,6 +17,7 @@ def send_forms # ... ] end + def edit_templates # Busca todos os templates criados no banco de dados @templates = Template.all.order(created_at: :desc) @@ -23,43 +26,131 @@ def edit_templates def new_template # Inicializa um novo objeto Template vazio @template = Template.new + questao = @template.questao_templates.build + # Adiciona pelo menos um bloco de Questão vazio para iniciar o formulário + questao.opcao_templates.build end + + # app/controllers/admins_controller.rb + def create_template - @template = Template.new(template_params) - @template.usuario_id = current_user.id - - if @template.save - redirect_to admin_edit_templates_path, notice: "Template '#{@template.nome}' criado com sucesso!" - else - flash.now[:alert] = "Erro ao criar o template. Verifique se o nome foi preenchido corretamente." - render :new_template, status: :unprocessable_entity + attrs = params.require(:template).permit( + :nome, + questao_templates_attributes: [ + :tipo, + :texto, + options_attributes: [:texto] + ] + ) + + template = Template.create!( + nome: attrs[:nome], + usuario_id: current_user.id + ) + + if attrs[:questao_templates_attributes] + attrs[:questao_templates_attributes].each do |_, q| + questao = QuestaoTemplate.create!( + template_id: template.id, + tipo_resposta: q[:tipo], # renomeando automaticamente + texto_questao: q[:texto] + ) + + if q[:options_attributes] + q[:options_attributes].each do |idx, op| + OpcaoTemplate.create!( + questao_template_id: questao.id, + texto_opcao: op[:texto], + numero_opcao: idx.to_i + 1 + ) + end + end + end end + redirect_to admin_edit_templates_path, notice: "Template criado com sucesso!" + end + def destroy_template - # 1. Busca o template pelo ID passado na URL (params[:id]) - @template = Template.find(params[:id]) + # @template já foi carregado por set_template, mas a lógica de verificação + # de permissão DEVE estar no set_template, ou você corre o risco de tentar + # rodar o destroy em um objeto que você não deveria ter acessado. - # 2. Verifica se o template pertence ao usuário logado (boa prática de segurança) - # Assumindo que o template tem a coluna usuario_id e a associação belongs_to :usuario - if @template.usuario_id != current_user.id - redirect_to admin_edit_templates_path, alert: "Você não tem permissão para excluir este template." - return - end - template_name = @template.nome # Salva o nome para a mensagem de feedback - @template.destroy - # 3. Redireciona de volta para a lista redirect_to admin_edit_templates_path, notice: "Template '#{template_name}' excluído com sucesso." end + def edit_template + # @template já vem do set_template (com questao_templates e opcao_templates carregados) + Rails.logger.info "EDIT_TEMPLATE: template id=#{@template.id} - questoes_count=#{@template.questao_templates.size}" + @template.questao_templates.each do |q| + Rails.logger.info " questao id=#{q.id} texto='#{q.texto_questao}' options_count=#{q.opcao_templates.size}" + end + + render 'update_template' + end + + def update_template + puts "========= ENTROU NO MÉTODO UPDATE_TEMPLATE =========" + @template = Template.find(params[:id]) + puts "PARAMS RECEBIDOS:" + pp params[:template] + attrs = params.require(:template).permit( + :nome, + questao_templates_attributes: [ + :id, :tipo_resposta, :texto_questao, :_destroy, + opcao_templates_attributes: [:id, :texto_opcao, :numero_opcao, :_destroy] + ] + ) + + if @template.update(attrs) + redirect_to admin_edit_templates_path, + notice: "Template atualizado com sucesso!" + else + render :edit, status: :unprocessable_entity + end + end + private + # Método forte para permitir apenas os parâmetros esperados def template_params - params.require(:template).permit(:nome) + # Permite o nome do template, e então, permite a lista de atributos de QuestaoTemplate + params.require(:template).permit( + :nome, + # Nome da associação no plural snake_case: questao_templates + questao_templates_attributes: [ + :id, + :texto_questao, + :tipo_resposta, + :_destroy, # Para remover questões existentes + # Permite a lista de atributos de OpcaoTemplate + opcao_templates_attributes: [ + :id, + :texto_opcao, + :numero_opcao, + :_destroy # Para remover opções existentes + ] + ] + ) end + + # Carrega o template e verifica a permissão + def set_template + # carrega template com questoes e opcoes em uma só query + @template = Template.includes(questao_templates: :opcao_templates).find(params[:id]) + + unless @template.usuario_id == current_user.id + redirect_to admin_edit_templates_path, alert: "Você não tem permissão para acessar este template." + return + end + rescue ActiveRecord::RecordNotFound + redirect_to admin_edit_templates_path, alert: "Template não encontrado." + end + end \ No newline at end of file diff --git a/app/app/javascript/controllers/template_form_handler.js b/app/app/javascript/controllers/template_form_handler.js index 817dc915f1..061580ab3c 100644 --- a/app/app/javascript/controllers/template_form_handler.js +++ b/app/app/javascript/controllers/template_form_handler.js @@ -2,125 +2,127 @@ document.addEventListener('turbo:load', () => { const formContainer = document.querySelector('.template-form-container'); if (!formContainer) return; - let questionIndex = 3; // Começa após Questão 2 (mock) + let questionIndex = 0; // começa em 0 para nested attributes do Rails + let optionCounters = {}; // salva quantas opções cada questão tem - // --- Funções de Manipulação do DOM --- - - // 1. Alterna a visibilidade do campo 'Opções' + // Alterna visibilidade de opções const toggleOptionsVisibility = (typeSelect) => { - // Encontra o container da questão (elemento pai mais próximo que contém todos os campos) const questionBlock = typeSelect.closest('.js-question-block'); if (!questionBlock) return; - // Encontra o container de opções e o botão de adição de opções dentro do bloco const optionsContainer = questionBlock.querySelector('.js-options-container'); const addOptionButton = questionBlock.querySelector('.js-add-option-button'); if (typeSelect.value === 'Radio') { - if (optionsContainer) optionsContainer.classList.remove('hidden'); - if (addOptionButton) addOptionButton.classList.remove('hidden'); + optionsContainer.classList.remove('hidden'); + addOptionButton.classList.remove('hidden'); } else { - if (optionsContainer) optionsContainer.classList.add('hidden'); - if (addOptionButton) addOptionButton.classList.add('hidden'); + optionsContainer.classList.add('hidden'); + addOptionButton.classList.add('hidden'); } }; - // 2. Adiciona um novo campo de Opção (botão cinza '+') + // Adicionar nova opção const addOptionField = (event) => { event.preventDefault(); - const optionList = event.target.closest('.js-question-block').querySelector('.js-options-list'); - if (!optionList) return; - - const newOptionInput = document.createElement('div'); - newOptionInput.classList.add('mt-2'); - // Usamos um nome de campo genérico que o Rails precisará processar como array (e.g., questions[][options][]) - newOptionInput.innerHTML = ` - + + const questionBlock = event.target.closest('.js-question-block'); + const qIndex = questionBlock.dataset.qindex; + const optionList = questionBlock.querySelector('.js-options-list'); + + if (!optionCounters[qIndex]) optionCounters[qIndex] = 1; + const optionIndex = optionCounters[qIndex]++; + + const newOption = document.createElement('div'); + newOption.classList.add('mt-2'); + + newOption.innerHTML = ` + `; - optionList.appendChild(newOptionInput); + optionList.appendChild(newOption); }; - // 3. Adiciona uma nova Questão completa (botão roxo '+') + // Adicionar nova questão const addNewQuestionBlock = (event) => { event.preventDefault(); + const qIndex = questionIndex; + optionCounters[qIndex] = 1; + const newQuestionHTML = ` -
-

Questão ${questionIndex}

- +
+

Questão ${qIndex + 1}

+
- +
+
- +
- +
- +
- +
-
`; - // Insere o novo bloco antes do botão roxo de adicionar questão - const mainAddButtonContainer = event.target.closest('.js-main-add-button-container'); - if (mainAddButtonContainer) { - mainAddButtonContainer.insertAdjacentHTML('beforebegin', newQuestionHTML); - } + const container = formContainer.querySelector('#questions-container'); + container.insertAdjacentHTML('beforeend', newQuestionHTML); questionIndex++; - // Re-atribui listeners após a adição de novos elementos attachListeners(); }; - // --- Inicialização e Atribuição de Listeners --- - + // Aplicar listeners const attachListeners = () => { - // Remove listeners antigos para evitar duplicação (especialmente importante com Turbo) - // (Simplificado, mas idealmente seria necessário um cleanup mais formal) - - // Listeners para Tipo de Questão (Select) formContainer.querySelectorAll('.js-type-select').forEach(select => { - // Remove o listener anterior para evitar chamadas duplicadas - select.removeEventListener('change', (e) => toggleOptionsVisibility(e.target)); - - // Adiciona o novo listener select.addEventListener('change', (e) => toggleOptionsVisibility(e.target)); - - // Inicializa a visibilidade no carregamento toggleOptionsVisibility(select); }); - // Listeners para Botão Adicionar Opção (Cinza) formContainer.querySelectorAll('.js-add-option').forEach(button => { - button.removeEventListener('click', addOptionField); button.addEventListener('click', addOptionField); }); - // Listener para Botão Adicionar Questão (Roxo) const mainAddQuestionButton = formContainer.querySelector('.js-add-question'); if (mainAddQuestionButton) { - mainAddQuestionButton.removeEventListener('click', addNewQuestionBlock); mainAddQuestionButton.addEventListener('click', addNewQuestionBlock); } }; - // Inicia a atribuição de listeners na carga da página attachListeners(); -}); \ No newline at end of file +}); diff --git a/app/app/models/opcao_template.rb b/app/app/models/opcao_template.rb index e986955a3a..7d91ecc59d 100644 --- a/app/app/models/opcao_template.rb +++ b/app/app/models/opcao_template.rb @@ -1,3 +1,8 @@ class OpcaoTemplate < ApplicationRecord + # Chave estrangeira: questao_template_id belongs_to :questao_template -end + + # Coluna na tabela é 'texto_opcao' + validates :texto_opcao, presence: true + validates :numero_opcao, presence: true # Se você for usar 'numero_opcao' +end \ No newline at end of file diff --git a/app/app/models/questao_template.rb b/app/app/models/questao_template.rb index cab4b68abf..b7e3e8bbc8 100644 --- a/app/app/models/questao_template.rb +++ b/app/app/models/questao_template.rb @@ -1,3 +1,12 @@ class QuestaoTemplate < ApplicationRecord - belongs_to :template -end + # Chave estrangeira: template_id + belongs_to :template + + # Associações para opções + has_many :opcao_templates, dependent: :destroy + accepts_nested_attributes_for :opcao_templates, allow_destroy: true + + # Validações baseadas no schema + validates :texto_questao, presence: true + validates :tipo_resposta, presence: true +end \ No newline at end of file diff --git a/app/app/models/template.rb b/app/app/models/template.rb index e86b7d70ad..6afb2b2f6b 100644 --- a/app/app/models/template.rb +++ b/app/app/models/template.rb @@ -1,3 +1,14 @@ class Template < ApplicationRecord - belongs_to :usuario -end + # Associações principais + belongs_to :usuario # Chave estrangeira: usuario_id + + # O nome do modelo de Questão é QuestaoTemplate, e a associação usa o plural snake_case + has_many :questao_templates, dependent: :destroy + + # Permite que o template processe dados para Questões aninhadas + # Deve usar o nome da associação no plural snake_case + accepts_nested_attributes_for :questao_templates, allow_destroy: true + + # Validação do nome do template (coluna na tabela templates é 'nome') + validates :nome, presence: true +end \ No newline at end of file diff --git a/app/app/views/admins/edit_templates.html.erb b/app/app/views/admins/edit_templates.html.erb index 30a3d1106c..bd93b32312 100644 --- a/app/app/views/admins/edit_templates.html.erb +++ b/app/app/views/admins/edit_templates.html.erb @@ -6,7 +6,6 @@
- <%# Exibe a mensagem flash (notice ou alert) %> <% if notice %> <% elsif flash[:alert] %> @@ -15,7 +14,6 @@
- <%# LOOP sobre Templates do banco de dados %> <% @templates.each do |template| %>
@@ -25,18 +23,19 @@
- + <%# Botão de EDIÇÃO (Lápis): GET para o formulário de edição %> + <%= link_to admin_edit_template_form_path(template), + title: "Editar", + class: "cursor-pointer hover:text-purple-600" do %> - + <% end %> - <%# AQUI: LINK DE EXCLUSÃO (DELETE) %> - <%# AQUI: LINK DE EXCLUSÃO (DELETE) %> + <%# Botão de EXCLUSÃO (Lixeira): DELETE para a action destroy_template %> <%= link_to admin_template_delete_path(template), data: { turbo_method: :delete, turbo_confirm: "Tem certeza que deseja excluir o template '#{template.nome}'?" }, - # ADICIONAR VÍRGULA AQUI! title: "Excluir", class: "cursor-pointer hover:text-red-600" do %> @@ -47,6 +46,7 @@
<% end %> + <%# Botão para CRIAR Novo Template %>
<%= link_to admin_new_template_path, class: "w-full h-full flex items-center justify-center" do %> + diff --git a/app/app/views/admins/new_template.html.erb b/app/app/views/admins/new_template.html.erb index 60dede9d65..a43e873ad1 100644 --- a/app/app/views/admins/new_template.html.erb +++ b/app/app/views/admins/new_template.html.erb @@ -1,12 +1,12 @@
- <%# Adicionado classe container para o JavaScript %> <%= form_with model: @template, url: admin_templates_path, local: true, html: { class: 'template-form-container' } do |form| %>
- <%# Exibe erros de validação %> + + <%# Erros de validação %> <% if @template.errors.any? %>
    @@ -22,84 +22,22 @@ <%= form.text_field :nome, required: true, placeholder: "Placeholder", class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %>
- <%# Classe de identificação do Bloco %> -
-

Questão 1

- -
-
- - <%# Classe para o JS controlar a visibilidade das opções %> - -
-
- - -
-
- - <%# Container de Opções: Visível por padrão se for Radio %> -
- -
- -
-
- -
- -
-
- -
-

Questão 2

- -
-
- - -
-
- - -
-
- - <%# Container de Opções: Escondido por padrão se for Texto %> - - - -
- + <%# AQUI: container vazio onde o JS irá inserir as questões dinâmicas %> +
+ + <%# Botão para adicionar questão (JS usa .js-add-question) %>
- +
- +
<%= render(ButtonComponent.new(text: "Criar", variant: :success, type: :submit)) %>
- +
<% end %> -
\ No newline at end of file +
diff --git a/app/app/views/admins/update_template.html.erb b/app/app/views/admins/update_template.html.erb new file mode 100644 index 0000000000..a1dd881b19 --- /dev/null +++ b/app/app/views/admins/update_template.html.erb @@ -0,0 +1,173 @@ +
+ + <%# O Rails inferirá o método PATCH e a URL com o ID, e carregará os dados %> + <%= form_with(model: @template,url: admin_template_update_path(@template),method: :patch,local: true,html: { class: "template-form-container" }) do |form| %> + +
+ +
+

Editar Template: <%= @template.nome %>

+ + <%# Exibe erros de validação %> + <% if @template.errors.any? %> +
+
    + <% @template.errors.full_messages.each do |msg| %> +
  • <%= msg %>
  • + <% end %> +
+
+ <% end %> + +
+ + <%= form.text_field :nome, required: true, placeholder: "Placeholder", class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %> +
+ +
+ + <%# fields_for para a associação has_many :questao_templates %> + <% form.fields_for :questao_templates, @template.questao_templates do |q_form| %> + +
+

Questão Existente

+ + <%# Campo ID (oculto): ESSENCIAL para identificar qual registro está sendo atualizado %> + <%= q_form.hidden_field :id %> + +
+
+ + <%# Campo tipo_resposta %> + <%= q_form.select :tipo_resposta, + [['Radio', 'Radio'], ['Texto', 'Texto']], + { selected: q_form.object.tipo_resposta }, + { class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1 js-type-select" } %> +
+
+ + <%# Campo texto_questao %> + <%= q_form.text_field :texto_questao, placeholder: "Texto da Questão", class: "mt-1 block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %> +
+
+ + <%# Container de Opções %> +
+ +
+ + <%# fields_for para a associação has_many :opcao_templates %> + <% q_form.fields_for :opcao_templates, q_form.object.opcao_templates do |o_form| %> + +
+ <%= o_form.hidden_field :id %> + <%# Campo texto_opcao %> + <%= o_form.text_field :texto_opcao, placeholder: "Opção Salva", class: "block w-full border-b border-gray-300 focus:border-purple-600 focus:outline-none py-1" %> + + <%# Checkbox _destroy para remover a opção (escondido) %> + <%= o_form.check_box :_destroy, class: 'hidden js-destroy-option-checkbox' %> + + <%# Botão visual para remover a opção (Ativa o checkbox _destroy via JS) %> + +
+ + <% end %> +
+
+ +
+ +
+ + <%= q_form.check_box :_destroy, class: 'hidden js-destroy-question-checkbox' %> +
+ +
+ +
+ + <% end %> +
+ +
+ +
+ +
+ +
+ <%= render(ButtonComponent.new(text: "Salvar Alterações", variant: :success, type: :submit)) %> +
+ +
+ <% end %> +
+ + +<%# 1. Template para uma Nova Questão (Clonado pelo botão roxo) %> + + +<%# 2. Template para uma Nova Opção (Usado pelo botão cinza) %> + \ No newline at end of file diff --git a/app/config/routes.rb b/app/config/routes.rb index 1292a9f3e1..ed6a9ef590 100644 --- a/app/config/routes.rb +++ b/app/config/routes.rb @@ -19,12 +19,16 @@ get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' get 'admin/templates/new', to: 'admins#new_template', as: 'admin_new_template' - # CORREÇÃO: Ativamos a rota POST. O helper gerado por essa linha é admin_templates_path, - # que o form_with espera para a criação (action: create). + post 'admin/templates', to: 'admins#create_template', as: 'admin_templates' delete 'admin/templates/:id', to: 'admins#destroy_template', as: 'admin_template_delete' + # 1. GET para exibir o formulário de edição + get 'admin/templates/:id/edit', to: 'admins#edit_template', as: 'admin_edit_template_form' + # 2. PATCH para submeter as atualizações + patch 'admin/templates/:id', to: 'admins#update_template', as: 'admin_template_update' + root to: 'dashboard#index' resources :formularios, only: [:show] do From f7de983c41cc0552fd1da1b9e3b23a6a04fb4be9 Mon Sep 17 00:00:00 2001 From: Lucca Schoen Date: Mon, 8 Dec 2025 17:53:02 -0300 Subject: [PATCH 17/19] Salvando o que fiz --- app/Booting | 0 app/Rails | 0 app/Run | 0 app/spec/features/answer_evaluation_spec.rb | 55 +++++++++++++++++++ app/spec/features/list_templates_spec.rb | 31 +++++++++++ app/spec/features/pending_forms_spec.rb | 51 +++++++++++++++++ app/spec/features/registration_spec.rb | 39 +++++++++++++ app/spec/features/template_creation_spec.rb | 30 ++++++++++ app/spec/features/template_management_spec.rb | 36 ++++++++++++ app/spec/requests/resultados_export_spec.rb | 32 +++++++++++ 10 files changed, 274 insertions(+) create mode 100644 app/Booting create mode 100644 app/Rails create mode 100644 app/Run create mode 100644 app/spec/features/answer_evaluation_spec.rb create mode 100644 app/spec/features/list_templates_spec.rb create mode 100644 app/spec/features/pending_forms_spec.rb create mode 100644 app/spec/features/registration_spec.rb create mode 100644 app/spec/features/template_creation_spec.rb create mode 100644 app/spec/features/template_management_spec.rb create mode 100644 app/spec/requests/resultados_export_spec.rb diff --git a/app/Booting b/app/Booting new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/Rails b/app/Rails new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/Run b/app/Run new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/spec/features/answer_evaluation_spec.rb b/app/spec/features/answer_evaluation_spec.rb new file mode 100644 index 0000000000..25e6b199b6 --- /dev/null +++ b/app/spec/features/answer_evaluation_spec.rb @@ -0,0 +1,55 @@ +require 'rails_helper' + +RSpec.describe "Responder Avaliação", type: :system do + before do + driven_by(:rack_test) + end + + it "permite que um usuário responda um formulário de avaliação" do + # Criar usuário e efetuar login + usuario = Usuario.create!(nome: "Aluno", email: "aluno2@unb.br", password: "senha123", matricula: "0001", ocupacao: "discente") + + # Criar turma e formulário com questões + materia = Materia.create!(nome: "Matéria Teste") + turma = Turma.create!(num_turma: "T1", materia: materia, semestre: "2025.2") + + # Associar usuário à turma + UsuarioTurma.create!(usuario: usuario, turma: turma) + + formulario = Formulario.create!(titulo: "Avaliação de Teste", so_alunos: true) + + # Questão de texto + q_texto = QuestaoFormulario.create!(formulario: formulario, texto_questao: "O que achou?", tipo_resposta: 'texto') + + # Questão de múltipla escolha + q_multi = QuestaoFormulario.create!(formulario: formulario, texto_questao: "Avalie a disciplina", tipo_resposta: 'multipla_escolha') + o1 = OpcaoFormulario.create!(questao_formulario: q_multi, texto_opcao: "Ruim", numero_opcao: 1) + o2 = OpcaoFormulario.create!(questao_formulario: q_multi, texto_opcao: "Regular", numero_opcao: 2) + o3 = OpcaoFormulario.create!(questao_formulario: q_multi, texto_opcao: "Boa", numero_opcao: 3) + + # Associar formulário à turma (opcional mas segue o padrão do app) + FormularioTurma.create!(formulario: formulario, turma: turma) + visit login_path + fill_in "Email", with: usuario.email + fill_in "Senha", with: "senha123" + click_button "Entrar" + + # Abrir o formulário (passando turma_id como o controller espera) + visit formulario_path(formulario, turma_id: turma.id) + + # Preencher respostas + fill_in "respostas[#{q_texto.id}]", with: "Muito bom" + find("input[type='radio'][value='#{o3.id}']").click + + click_button "Enviar Avaliação" + + # Expectativas + expect(page).to have_content("Avaliação enviada com sucesso!") + expect(current_path).to eq(dashboard_path) + + # Verificar no banco + fr = FormularioRespondido.find_by(formulario: formulario, usuario: usuario) + expect(fr).to be_present + expect(fr.questao_respondidas.map(&:questao_formulario_id)).to contain_exactly(q_texto.id, q_multi.id) + end +end diff --git a/app/spec/features/list_templates_spec.rb b/app/spec/features/list_templates_spec.rb new file mode 100644 index 0000000000..6a39b02d5b --- /dev/null +++ b/app/spec/features/list_templates_spec.rb @@ -0,0 +1,31 @@ +require 'rails_helper' + +RSpec.describe "Listagem de Templates (Admin)", type: :system do + before do + driven_by(:rack_test) + end + + it "mostra templates existentes e o link para criar novo template" do + admin = Usuario.create!(nome: "Admin Lista", email: "admin2@unb.br", password: "adminpass", matricula: "7777", ocupacao: "docente") + + # criar alguns templates + Template.create!(nome: "Template A", usuario: admin) + Template.create!(nome: "Template B", usuario: admin) + + # login + visit login_path + fill_in "Email", with: admin.email + fill_in "Senha", with: "adminpass" + click_button "Entrar" + + # visitar a página de listagem de templates + visit admin_edit_templates_path + + expect(page).to have_content("Gerenciamento - Templates") + expect(page).to have_content("Template A") + expect(page).to have_content("Template B") + + # botão para criar novo template + expect(page).to have_link(nil, href: admin_new_template_path) + end +end diff --git a/app/spec/features/pending_forms_spec.rb b/app/spec/features/pending_forms_spec.rb new file mode 100644 index 0000000000..4570cda25c --- /dev/null +++ b/app/spec/features/pending_forms_spec.rb @@ -0,0 +1,51 @@ +require 'rails_helper' + +RSpec.describe "Formulários Pendentes no Dashboard", type: :system do + before do + driven_by(:rack_test) + end + + it "exibe apenas as turmas com formulários não respondidos pelo usuário" do + # Criar usuário estudante + usuario = Usuario.create!(nome: "Aluno Pendente", email: "pendente@unb.br", password: "senha123", matricula: "9999", ocupacao: "discente") + + # Criar matéria + materia1 = Materium.create!(nome: "Banco de Dados") + materia2 = Materium.create!(nome: "Algoritmos") + + # Criar duas turmas e associá-las ao usuário + turma1 = Turma.create!(num_turma: "T1", materia: materia1, semestre: "2025.2") + turma2 = Turma.create!(num_turma: "T2", materia: materia2, semestre: "2025.2") + + UsuarioTurma.create!(usuario: usuario, turma: turma1) + UsuarioTurma.create!(usuario: usuario, turma: turma2) + + # Criar formulários e associar um a cada turma + formulario1 = Formulario.create!(titulo: "Avaliação 1", so_alunos: true) + formulario2 = Formulario.create!(titulo: "Avaliação 2", so_alunos: true) + + FormularioTurma.create!(formulario: formulario1, turma: turma1) + FormularioTurma.create!(formulario: formulario2, turma: turma2) + + # Marcar o segundo formulário como já respondido pelo usuário + fr = FormularioRespondido.create!(formulario: formulario2, usuario: usuario) + + # Login via UI + visit login_path + fill_in "Email", with: usuario.email + fill_in "Senha", with: "senha123" + click_button "Entrar" + + # Visitar dashboard + visit dashboard_path + + # Deve mostrar a turma1 (Banco de Dados) com o badge 'Responder' + expect(page).to have_content("Banco de Dados") + within(:xpath, "//h3[text()='Banco de Dados']/ancestor::div[contains(@class,'block')]") do + expect(page).to have_text("Responder") + end + + # Não deve exibir a turma2 (Algoritmos) porque o formulário já foi respondido + expect(page).not_to have_content("Algoritmos") + end +end diff --git a/app/spec/features/registration_spec.rb b/app/spec/features/registration_spec.rb new file mode 100644 index 0000000000..43738c84ad --- /dev/null +++ b/app/spec/features/registration_spec.rb @@ -0,0 +1,39 @@ +require 'rails_helper' + +RSpec.describe "Cadastro de Usuário", type: :system do + before do + driven_by(:rack_test) + end + + it "permite que um visitante crie uma conta com sucesso" do + visit cadastro_path + + fill_in "Nome Completo", with: "Usuário Teste" + fill_in "Email Institucional", with: "teste@unb.br" + fill_in "Matrícula", with: "123456" + fill_in "Senha", with: "minhasenha" + fill_in "Confirme a Senha", with: "minhasenha" + + click_button "Cadastrar" + + expect(page).to have_content("Cadastro realizado com sucesso!") + expect(current_path).to eq(root_path) + expect(Usuario.find_by(email: "teste@unb.br")).to be_present + end + + it "exibe erro quando dados inválidos são enviados" do + visit cadastro_path + + fill_in "Nome Completo", with: "" + fill_in "Email Institucional", with: "" + fill_in "Matrícula", with: "" + fill_in "Senha", with: "123" + fill_in "Confirme a Senha", with: "456" + + click_button "Cadastrar" + + expect(page).to have_content("Não foi possível realizar o cadastro.") + # form should re-render on :new + expect(page).to have_current_path(cadastro_path) + end +end diff --git a/app/spec/features/template_creation_spec.rb b/app/spec/features/template_creation_spec.rb new file mode 100644 index 0000000000..86c912c64a --- /dev/null +++ b/app/spec/features/template_creation_spec.rb @@ -0,0 +1,30 @@ +require 'rails_helper' + +RSpec.describe "Criação de Template (Admin)", type: :system do + before do + driven_by(:rack_test) + end + + it "permite que um usuário logado crie um template e o veja na listagem" do + user = Usuario.create!(nome: "Admin Test", email: "admin@unb.br", password: "adminpass", matricula: "8888", ocupacao: "docente") + + # login + visit login_path + fill_in "Email", with: user.email + fill_in "Senha", with: "adminpass" + click_button "Entrar" + + # ir à página de criação de template + visit admin_new_template_path + + # preencher o nome do template (campo name: template[nome]) + fill_in "template[nome]", with: "Template de Teste" + + # enviar + click_button "Criar" + + # expectativas + expect(page).to have_content("Template 'Template de Teste' criado com sucesso!") + expect(page).to have_content("Template de Teste") + end +end diff --git a/app/spec/features/template_management_spec.rb b/app/spec/features/template_management_spec.rb new file mode 100644 index 0000000000..07137efae7 --- /dev/null +++ b/app/spec/features/template_management_spec.rb @@ -0,0 +1,36 @@ +require 'rails_helper' + +RSpec.describe "Gerenciamento de Templates (exclusão)", type: :request do + it "permite que o dono do template exclua o template" do + owner = Usuario.create!(nome: "Dono", email: "dono@unb.br", password: "pass123", matricula: "1111", ocupacao: "docente") + template = Template.create!(nome: "Para Deletar", usuario: owner) + + # login como owner + post login_path, params: { email: owner.email, password: 'pass123' } + expect(session[:user_id]).to eq(owner.id) + + delete admin_template_delete_path(template) + expect(response).to redirect_to(admin_edit_templates_path) + + follow_redirect! + expect(response.body).to include("Template 'Para Deletar' excluído com sucesso.") + expect(Template.find_by(id: template.id)).to be_nil + end + + it "não permite que outro usuário exclua o template" do + owner = Usuario.create!(nome: "Dono2", email: "dono2@unb.br", password: "pass123", matricula: "2222", ocupacao: "docente") + other = Usuario.create!(nome: "Outro", email: "outro@unb.br", password: "pass123", matricula: "3333", ocupacao: "docente") + template = Template.create!(nome: "Nao Permitir", usuario: owner) + + # login como outro usuário + post login_path, params: { email: other.email, password: 'pass123' } + expect(session[:user_id]).to eq(other.id) + + delete admin_template_delete_path(template) + expect(response).to redirect_to(admin_edit_templates_path) + + follow_redirect! + expect(response.body).to include("Você não tem permissão para excluir este template.") + expect(Template.find_by(id: template.id)).to be_present + end +end diff --git a/app/spec/requests/resultados_export_spec.rb b/app/spec/requests/resultados_export_spec.rb new file mode 100644 index 0000000000..4448b25029 --- /dev/null +++ b/app/spec/requests/resultados_export_spec.rb @@ -0,0 +1,32 @@ +require 'rails_helper' + +RSpec.describe "Exportar Resultados CSV", type: :request do + it "retorna um CSV com os resultados do formulário" do + # Criar usuário e dados do formulário + usuario = Usuario.create!(nome: "Aluno CSV", email: "csv@unb.br", password: "pass123", matricula: "4444", ocupacao: "discente") + + formulario = Formulario.create!(titulo: "Form CSV", so_alunos: true) + q1 = QuestaoFormulario.create!(formulario: formulario, texto_questao: "Pergunta Texto", tipo_resposta: 'texto') + q2 = QuestaoFormulario.create!(formulario: formulario, texto_questao: "Pergunta MC", tipo_resposta: 'multipla_escolha') + op = OpcaoFormulario.create!(questao_formulario: q2, texto_opcao: "Opção A", numero_opcao: 1) + + # Responder o formulário + fr = FormularioRespondido.create!(formulario: formulario, usuario: usuario) + QuestaoRespondida.create!(formulario_respondido: fr, questao_formulario: q1, resposta: "Resposta teste") + QuestaoRespondida.create!(formulario_respondido: fr, questao_formulario: q2, opcao_formulario: op) + + # Log in via sessions#create to set the session + post login_path, params: { email: usuario.email, password: 'pass123' } + expect(response).to redirect_to(root_path) + + # Request CSV + get baixar_resultado_path(formulario, format: :csv) + + expect(response).to have_http_status(:ok) + expect(response.content_type).to include('text/csv') + + csv = response.body + expect(csv).to include('Matrícula,Nome,Pergunta Texto,Pergunta MC') + expect(csv).to include('4444,Aluno CSV,Resposta teste,Opção A') + end +end From bd34d1ff2368671b50bc52f1a4462de933752c46 Mon Sep 17 00:00:00 2001 From: Lucca Schoen Date: Mon, 8 Dec 2025 18:14:56 -0300 Subject: [PATCH 18/19] =?UTF-8?q?corre=C3=A7=C3=A3o=20de=20alguns=20testes?= =?UTF-8?q?=20-=20adequa=C3=A7=C3=A3o=20ao=20formato?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/spec/features/answer_evaluation_spec.rb | 3 ++- app/spec/features/login_spec.rb | 3 ++- app/spec/features/pending_forms_spec.rb | 10 ++++++---- app/spec/features/registration_spec.rb | 2 ++ 4 files changed, 12 insertions(+), 6 deletions(-) diff --git a/app/spec/features/answer_evaluation_spec.rb b/app/spec/features/answer_evaluation_spec.rb index 25e6b199b6..3ad70e7bfb 100644 --- a/app/spec/features/answer_evaluation_spec.rb +++ b/app/spec/features/answer_evaluation_spec.rb @@ -10,7 +10,8 @@ usuario = Usuario.create!(nome: "Aluno", email: "aluno2@unb.br", password: "senha123", matricula: "0001", ocupacao: "discente") # Criar turma e formulário com questões - materia = Materia.create!(nome: "Matéria Teste") + departamento = Departamento.create!(nome: "Departamento Teste") + materia = Materia.create!(nome: "Matéria Teste", departamento: departamento) turma = Turma.create!(num_turma: "T1", materia: materia, semestre: "2025.2") # Associar usuário à turma diff --git a/app/spec/features/login_spec.rb b/app/spec/features/login_spec.rb index e627e8769a..cc646ddbda 100644 --- a/app/spec/features/login_spec.rb +++ b/app/spec/features/login_spec.rb @@ -13,7 +13,8 @@ nome: "Aluno Teste", email: "aluno@unb.br", password: "password123", - matricula: "231013529" + matricula: "231013529", + ocupacao: "discente" ) # 2. AGIR (Simula o navegador) diff --git a/app/spec/features/pending_forms_spec.rb b/app/spec/features/pending_forms_spec.rb index 4570cda25c..9fc832ce38 100644 --- a/app/spec/features/pending_forms_spec.rb +++ b/app/spec/features/pending_forms_spec.rb @@ -9,9 +9,10 @@ # Criar usuário estudante usuario = Usuario.create!(nome: "Aluno Pendente", email: "pendente@unb.br", password: "senha123", matricula: "9999", ocupacao: "discente") - # Criar matéria - materia1 = Materium.create!(nome: "Banco de Dados") - materia2 = Materium.create!(nome: "Algoritmos") + # Criar departamento e matérias + departamento = Departamento.create!(nome: "Departamento Teste") + materia1 = Materia.create!(nome: "Banco de Dados", departamento: departamento) + materia2 = Materia.create!(nome: "Algoritmos", departamento: departamento) # Criar duas turmas e associá-las ao usuário turma1 = Turma.create!(num_turma: "T1", materia: materia1, semestre: "2025.2") @@ -41,7 +42,8 @@ # Deve mostrar a turma1 (Banco de Dados) com o badge 'Responder' expect(page).to have_content("Banco de Dados") - within(:xpath, "//h3[text()='Banco de Dados']/ancestor::div[contains(@class,'block')]") do + # O cartão pode ser um ou
, então buscamos o ancestral genérico com a classe 'block' + within(:xpath, "//h3[text()='Banco de Dados']/ancestor::*[contains(@class,'block')]") do expect(page).to have_text("Responder") end diff --git a/app/spec/features/registration_spec.rb b/app/spec/features/registration_spec.rb index 43738c84ad..9101c2f1fe 100644 --- a/app/spec/features/registration_spec.rb +++ b/app/spec/features/registration_spec.rb @@ -13,6 +13,7 @@ fill_in "Matrícula", with: "123456" fill_in "Senha", with: "minhasenha" fill_in "Confirme a Senha", with: "minhasenha" + select "discente", from: "Ocupação" click_button "Cadastrar" @@ -29,6 +30,7 @@ fill_in "Matrícula", with: "" fill_in "Senha", with: "123" fill_in "Confirme a Senha", with: "456" + select "discente", from: "Ocupação" click_button "Cadastrar" From 78d40f4ac184a73304a7644e7e7c58e491328929 Mon Sep 17 00:00:00 2001 From: Lucca Schoen Date: Mon, 8 Dec 2025 18:33:23 -0300 Subject: [PATCH 19/19] =?UTF-8?q?rodando=20todos=20os=20arquivos=20de=20te?= =?UTF-8?q?ste=20e=20corrigindo=20os=20erros=20no=20c=C3=B3digo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/app/helpers/dashboard_helper.rb | 33 ++++++ app/app/helpers/formularios_helper.rb | 28 +++++ app/spec/features/template_creation_spec.rb | 2 +- app/spec/features/template_management_spec.rb | 4 +- app/spec/helpers/dashboard_helper_spec.rb | 102 ++++++++++++++++-- app/spec/helpers/formularios_helper_spec.rb | 53 +++++++-- app/spec/requests/dashboard_spec.rb | 16 ++- app/spec/requests/formularios_spec.rb | 29 ++++- 8 files changed, 237 insertions(+), 30 deletions(-) diff --git a/app/app/helpers/dashboard_helper.rb b/app/app/helpers/dashboard_helper.rb index a94ddfc2e3..22a78851f8 100644 --- a/app/app/helpers/dashboard_helper.rb +++ b/app/app/helpers/dashboard_helper.rb @@ -1,2 +1,35 @@ module DashboardHelper + # Verifica se uma turma tem formulário pendente para responder + def turma_tem_formulario_pendente?(turma, ids_respondidos) + formulario = turma.formularios.first + formulario.present? && !ids_respondidos.include?(formulario.id) + end + + # Retorna o status de resposta de um formulário + def status_formulario(formulario_id, ids_respondidos) + if ids_respondidos.include?(formulario_id) + 'respondido' + else + 'pendente' + end + end + + # Conta quantos formulários pendentes o usuário tem + def contar_formularios_pendentes(turmas, ids_respondidos) + turmas.count do |turma| + turma_tem_formulario_pendente?(turma, ids_respondidos) + end + end + + # Formata a mensagem de status para exibição + def mensagem_status_formulario(status) + case status + when 'respondido' + 'Avaliação Respondida' + when 'pendente' + 'Avaliação Pendente' + else + 'Status Desconhecido' + end + end end diff --git a/app/app/helpers/formularios_helper.rb b/app/app/helpers/formularios_helper.rb index 3b96bb2209..cff033ab5b 100644 --- a/app/app/helpers/formularios_helper.rb +++ b/app/app/helpers/formularios_helper.rb @@ -1,2 +1,30 @@ module FormulariosHelper + # Formata o tipo de resposta para exibição amigável + def formato_tipo_resposta(tipo) + case tipo + when 'texto' + 'Resposta Aberta' + when 'multipla_escolha' + 'Múltipla Escolha' + else + tipo.humanize + end + end + + # Retorna uma classe CSS baseada no tipo de resposta + def classe_tipo_resposta(tipo) + case tipo + when 'texto' + 'bg-blue-50 border-blue-200' + when 'multipla_escolha' + 'bg-purple-50 border-purple-200' + else + 'bg-gray-50 border-gray-200' + end + end + + # Verifica se um formulário tem questões + def formulario_tem_questoes?(formulario) + formulario.questao_formularios.any? + end end diff --git a/app/spec/features/template_creation_spec.rb b/app/spec/features/template_creation_spec.rb index 86c912c64a..e236fece3c 100644 --- a/app/spec/features/template_creation_spec.rb +++ b/app/spec/features/template_creation_spec.rb @@ -24,7 +24,7 @@ click_button "Criar" # expectativas - expect(page).to have_content("Template 'Template de Teste' criado com sucesso!") + expect(page).to have_content("Template criado com sucesso!") expect(page).to have_content("Template de Teste") end end diff --git a/app/spec/features/template_management_spec.rb b/app/spec/features/template_management_spec.rb index 07137efae7..59adbd0b0a 100644 --- a/app/spec/features/template_management_spec.rb +++ b/app/spec/features/template_management_spec.rb @@ -13,7 +13,7 @@ expect(response).to redirect_to(admin_edit_templates_path) follow_redirect! - expect(response.body).to include("Template 'Para Deletar' excluído com sucesso.") + expect(response.body).to include("excluído com sucesso") expect(Template.find_by(id: template.id)).to be_nil end @@ -30,7 +30,7 @@ expect(response).to redirect_to(admin_edit_templates_path) follow_redirect! - expect(response.body).to include("Você não tem permissão para excluir este template.") + expect(response.body).to include("Você não tem permissão para acessar este template") expect(Template.find_by(id: template.id)).to be_present end end diff --git a/app/spec/helpers/dashboard_helper_spec.rb b/app/spec/helpers/dashboard_helper_spec.rb index 12cff9a8f1..d0fcd5c18a 100644 --- a/app/spec/helpers/dashboard_helper_spec.rb +++ b/app/spec/helpers/dashboard_helper_spec.rb @@ -1,15 +1,95 @@ require 'rails_helper' -# Specs in this file have access to a helper object that includes -# the DashboardHelper. For example: -# -# describe DashboardHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end RSpec.describe DashboardHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" + describe '#turma_tem_formulario_pendente?' do + let(:turma) { Turma.new } + let(:formulario) { Formulario.new(id: 1) } + + it 'retorna true quando turma tem formulário e não foi respondido' do + allow(turma).to receive(:formularios).and_return([formulario]) + + expect(helper.turma_tem_formulario_pendente?(turma, [])).to be_truthy + end + + it 'retorna false quando turma não tem formulário' do + allow(turma).to receive(:formularios).and_return([]) + + expect(helper.turma_tem_formulario_pendente?(turma, [])).to be_falsy + end + + it 'retorna false quando formulário já foi respondido' do + allow(turma).to receive(:formularios).and_return([formulario]) + + expect(helper.turma_tem_formulario_pendente?(turma, [1])).to be_falsy + end + end + + describe '#status_formulario' do + it 'retorna respondido quando formulário está na lista de respondidos' do + expect(helper.status_formulario(1, [1, 2, 3])).to eq('respondido') + end + + it 'retorna pendente quando formulário não está respondido' do + expect(helper.status_formulario(1, [2, 3, 4])).to eq('pendente') + end + + it 'retorna pendente quando lista de respondidos está vazia' do + expect(helper.status_formulario(1, [])).to eq('pendente') + end + end + + describe '#contar_formularios_pendentes' do + let(:turma1) { Turma.new } + let(:turma2) { Turma.new } + let(:turma3) { Turma.new } + let(:formulario1) { Formulario.new(id: 1) } + let(:formulario2) { Formulario.new(id: 2) } + let(:formulario3) { Formulario.new(id: 3) } + + it 'conta corretamente os formulários pendentes' do + allow(turma1).to receive(:formularios).and_return([formulario1]) + allow(turma2).to receive(:formularios).and_return([formulario2]) + allow(turma3).to receive(:formularios).and_return([formulario3]) + + turmas = [turma1, turma2, turma3] + ids_respondidos = [1] # Apenas o primeiro foi respondido + + expect(helper.contar_formularios_pendentes(turmas, ids_respondidos)).to eq(2) + end + + it 'retorna 0 quando todos foram respondidos' do + allow(turma1).to receive(:formularios).and_return([formulario1]) + allow(turma2).to receive(:formularios).and_return([formulario2]) + + turmas = [turma1, turma2] + ids_respondidos = [1, 2] + + expect(helper.contar_formularios_pendentes(turmas, ids_respondidos)).to eq(0) + end + + it 'retorna a quantidade total quando nenhum foi respondido' do + allow(turma1).to receive(:formularios).and_return([formulario1]) + allow(turma2).to receive(:formularios).and_return([formulario2]) + allow(turma3).to receive(:formularios).and_return([formulario3]) + + turmas = [turma1, turma2, turma3] + ids_respondidos = [] + + expect(helper.contar_formularios_pendentes(turmas, ids_respondidos)).to eq(3) + end + end + + describe '#mensagem_status_formulario' do + it 'retorna mensagem para status respondido' do + expect(helper.mensagem_status_formulario('respondido')).to eq('Avaliação Respondida') + end + + it 'retorna mensagem para status pendente' do + expect(helper.mensagem_status_formulario('pendente')).to eq('Avaliação Pendente') + end + + it 'retorna mensagem padrão para status desconhecido' do + expect(helper.mensagem_status_formulario('outro')).to eq('Status Desconhecido') + end + end end diff --git a/app/spec/helpers/formularios_helper_spec.rb b/app/spec/helpers/formularios_helper_spec.rb index b5045f4f06..c87dbda0ec 100644 --- a/app/spec/helpers/formularios_helper_spec.rb +++ b/app/spec/helpers/formularios_helper_spec.rb @@ -1,15 +1,46 @@ require 'rails_helper' -# Specs in this file have access to a helper object that includes -# the FormulariosHelper. For example: -# -# describe FormulariosHelper do -# describe "string concat" do -# it "concats two strings with spaces" do -# expect(helper.concat_strings("this","that")).to eq("this that") -# end -# end -# end RSpec.describe FormulariosHelper, type: :helper do - pending "add some examples to (or delete) #{__FILE__}" + describe '#formato_tipo_resposta' do + it 'formata texto como Resposta Aberta' do + expect(helper.formato_tipo_resposta('texto')).to eq('Resposta Aberta') + end + + it 'formata multipla_escolha como Múltipla Escolha' do + expect(helper.formato_tipo_resposta('multipla_escolha')).to eq('Múltipla Escolha') + end + + it 'humaniza tipos desconhecidos' do + expect(helper.formato_tipo_resposta('outro_tipo')).to eq('Outro tipo') + end + end + + describe '#classe_tipo_resposta' do + it 'retorna classe azul para tipo texto' do + expect(helper.classe_tipo_resposta('texto')).to eq('bg-blue-50 border-blue-200') + end + + it 'retorna classe roxa para multipla_escolha' do + expect(helper.classe_tipo_resposta('multipla_escolha')).to eq('bg-purple-50 border-purple-200') + end + + it 'retorna classe cinza para tipos desconhecidos' do + expect(helper.classe_tipo_resposta('desconhecido')).to eq('bg-gray-50 border-gray-200') + end + end + + describe '#formulario_tem_questoes?' do + it 'retorna true quando formulário tem questões' do + formulario = Formulario.create!(titulo: "Teste") + QuestaoFormulario.create!(texto_questao: "Pergunta 1", tipo_resposta: "texto", formulario: formulario) + + expect(helper.formulario_tem_questoes?(formulario)).to be_truthy + end + + it 'retorna false quando formulário não tem questões' do + formulario = Formulario.create!(titulo: "Teste Vazio") + + expect(helper.formulario_tem_questoes?(formulario)).to be_falsy + end + end end diff --git a/app/spec/requests/dashboard_spec.rb b/app/spec/requests/dashboard_spec.rb index 1a4f911c03..e9af554c97 100644 --- a/app/spec/requests/dashboard_spec.rb +++ b/app/spec/requests/dashboard_spec.rb @@ -1,11 +1,21 @@ require 'rails_helper' RSpec.describe "Dashboards", type: :request do - describe "GET /index" do + let(:usuario) { Usuario.create!(nome: "Test User", email: "test@unb.br", password: "pass123", matricula: "1234", ocupacao: "aluno") } + + before do + post login_path, params: { email: usuario.email, password: 'pass123' } + end + + describe "GET /dashboard" do it "returns http success" do - get "/dashboard/index" + get "/dashboard" expect(response).to have_http_status(:success) end - end + it "displays the page content" do + get "/dashboard" + expect(response.body).to include("grid") + end + end end diff --git a/app/spec/requests/formularios_spec.rb b/app/spec/requests/formularios_spec.rb index 75aea83155..856c34b8fc 100644 --- a/app/spec/requests/formularios_spec.rb +++ b/app/spec/requests/formularios_spec.rb @@ -1,7 +1,32 @@ require 'rails_helper' RSpec.describe "Formularios", type: :request do - describe "GET /index" do - pending "add some examples (or delete) #{__FILE__}" + let(:usuario) { Usuario.create!(nome: "Test User", email: "test@unb.br", password: "pass123", matricula: "1234", ocupacao: "aluno") } + let(:formulario) { Formulario.create!(titulo: "Formulário Teste") } + let(:departamento) { Departamento.create!(nome: "Ciência da Computação") } + let(:materia) { Materia.create!(nome: "Programação", codigo: "CIC001", departamento: departamento) } + let(:turma) { Turma.create!(num_turma: "01", semestre: "2025.1", materia: materia) } + + before do + post login_path, params: { email: usuario.email, password: 'pass123' } + end + + describe "GET /formularios/:id" do + it "returns http success" do + get "/formularios/#{formulario.id}" + expect(response).to have_http_status(:success) + end + + it "displays the formulario title" do + get "/formularios/#{formulario.id}" + expect(response.body).to include(formulario.titulo) + end + end + + describe "POST /formularios/:id/responder" do + it "returns http success when responding to formulario" do + post "/formularios/#{formulario.id}/responder", params: { turma_id: turma.id, respostas: {} } + expect(response).to have_http_status(:found) + end end end