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/.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/.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..be94e6f53d --- /dev/null +++ b/app/.ruby-version @@ -0,0 +1 @@ +3.2.2 diff --git a/app/Booting b/app/Booting new file mode 100644 index 0000000000..e69de29bb2 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..d525346be1 --- /dev/null +++ b/app/Gemfile @@ -0,0 +1,74 @@ +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[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 + +group :development, :test do + gem 'rspec-rails' +end + +gem "view_component", "~> 4.1" diff --git a/app/Gemfile.lock b/app/Gemfile.lock new file mode 100644 index 0000000000..a115fba9ac --- /dev/null +++ b/app/Gemfile.lock @@ -0,0 +1,469 @@ +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 (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) + 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) + diff-lcs (1.6.2) + 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-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) + 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-x64-mingw-ucrt) + 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) + 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) + 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-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) + 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-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) + 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) + 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) + 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 + 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 + capybara + debug + image_processing (~> 1.2) + importmap-rails + jbuilder + kamal + propshaft + puma (>= 5.0) + rails (~> 8.1.1) + rspec-rails + rubocop-rails-omakase + selenium-webdriver + solid_cable + solid_cache + solid_queue + sqlite3 (>= 2.1) + stimulus-rails + tailwindcss-rails + thruster + turbo-rails + tzinfo-data + view_component (~> 4.1) + 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/Rails b/app/Rails new file mode 100644 index 0000000000..e69de29bb2 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/Run b/app/Run new file mode 100644 index 0000000000..e69de29bb2 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/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..93c5bf0b69 --- /dev/null +++ b/app/app/components/button_component.html.erb @@ -0,0 +1,9 @@ +<% 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 new file mode 100644 index 0000000000..9bd01c9719 --- /dev/null +++ b/app/app/components/button_component.rb @@ -0,0 +1,27 @@ +class ButtonComponent < ViewComponent::Base + def initialize(text:, type: :submit, variant: :primary, link: nil) + @text = text + @type = type + @variant = variant + @link = link + end + + def classes + 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 + # 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 +end \ No newline at end of file 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..7000d839a8 --- /dev/null +++ b/app/app/components/dashboard/header_component.html.erb @@ -0,0 +1,39 @@ +
+ +
+ + +

<%= title %>

+
+ +
+ +
+ + + + + +
+
+
\ 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..2dc5dbe9b1 --- /dev/null +++ b/app/app/components/dashboard/header_component.rb @@ -0,0 +1,22 @@ +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 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/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..7adc6a96a3 --- /dev/null +++ b/app/app/components/evaluation_card_component.html.erb @@ -0,0 +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 %> +
+<% 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 new file mode 100644 index 0000000000..e70b94b579 --- /dev/null +++ b/app/app/components/evaluation_card_component.rb @@ -0,0 +1,10 @@ +class EvaluationCardComponent < ViewComponent::Base + 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/components/form_input_component.html.erb b/app/app/components/form_input_component.html.erb new file mode 100644 index 0000000000..234f63ba72 --- /dev/null +++ b/app/app/components/form_input_component.html.erb @@ -0,0 +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 new file mode 100644 index 0000000000..f61d398c04 --- /dev/null +++ b/app/app/components/form_input_component.rb @@ -0,0 +1,19 @@ +# app/components/form_input_component.rb +class FormInputComponent < ViewComponent::Base + # 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/admins_controller.rb b/app/app/controllers/admins_controller.rb new file mode 100644 index 0000000000..9bc793abef --- /dev/null +++ b/app/app/controllers/admins_controller.rb @@ -0,0 +1,177 @@ +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] + + # --- 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 = [ + { name: "Estudos Em", semester: "2024.1", code: "CIC1024", checked: true }, + # ... + ] + end + + # --- Funcionalidade de Templates (Manual) --- + def edit_templates + @templates = Template.all.order(created_at: :desc) + end + + def new_template + @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 + + 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 + # @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. + + template_name = @template.nome # Salva o nome para a mensagem de feedback + @template.destroy + + 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 + # 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/controllers/application_controller.rb b/app/app/controllers/application_controller.rb new file mode 100644 index 0000000000..40d45f0abd --- /dev/null +++ b/app/app/controllers/application_controller.rb @@ -0,0 +1,17 @@ +class ApplicationController < ActionController::Base + helper_method :current_user, :logged_in? + + def current_user + @current_user ||= Usuario.find(session[:user_id]) if session[:user_id] + end + + 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/concerns/.keep b/app/app/controllers/concerns/.keep new file mode 100644 index 0000000000..e69de29bb2 diff --git a/app/app/controllers/dashboard_controller.rb b/app/app/controllers/dashboard_controller.rb new file mode 100644 index 0000000000..05502276b2 --- /dev/null +++ b/app/app/controllers/dashboard_controller.rb @@ -0,0 +1,10 @@ +class DashboardController < ApplicationController + before_action :require_login + layout 'dashboard' + + def index + @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/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/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/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/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/helpers/dashboard_helper.rb b/app/app/helpers/dashboard_helper.rb new file mode 100644 index 0000000000..22a78851f8 --- /dev/null +++ b/app/app/helpers/dashboard_helper.rb @@ -0,0 +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 new file mode 100644 index 0000000000..cff033ab5b --- /dev/null +++ b/app/app/helpers/formularios_helper.rb @@ -0,0 +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/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/javascript/application.js b/app/app/javascript/application.js new file mode 100644 index 0000000000..ec0bf07de9 --- /dev/null +++ b/app/app/javascript/application.js @@ -0,0 +1,4 @@ +// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails +import "@hotwired/turbo-rails" +import "controllers" +import "controllers/template_form_handler" \ No newline at end of file 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/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/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/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/javascript/controllers/template_form_handler.js b/app/app/javascript/controllers/template_form_handler.js new file mode 100644 index 0000000000..061580ab3c --- /dev/null +++ b/app/app/javascript/controllers/template_form_handler.js @@ -0,0 +1,128 @@ +document.addEventListener('turbo:load', () => { + const formContainer = document.querySelector('.template-form-container'); + if (!formContainer) return; + + let questionIndex = 0; // começa em 0 para nested attributes do Rails + let optionCounters = {}; // salva quantas opções cada questão tem + + // Alterna visibilidade de opções + const toggleOptionsVisibility = (typeSelect) => { + const questionBlock = typeSelect.closest('.js-question-block'); + if (!questionBlock) return; + + const optionsContainer = questionBlock.querySelector('.js-options-container'); + const addOptionButton = questionBlock.querySelector('.js-add-option-button'); + + if (typeSelect.value === 'Radio') { + optionsContainer.classList.remove('hidden'); + addOptionButton.classList.remove('hidden'); + } else { + optionsContainer.classList.add('hidden'); + addOptionButton.classList.add('hidden'); + } + }; + + // Adicionar nova opção + const addOptionField = (event) => { + event.preventDefault(); + + 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(newOption); + }; + + // Adicionar nova questão + const addNewQuestionBlock = (event) => { + event.preventDefault(); + + const qIndex = questionIndex; + optionCounters[qIndex] = 1; + + const newQuestionHTML = ` +
+

Questão ${qIndex + 1}

+ +
+
+ + +
+ +
+ + +
+
+ +
+ +
+ +
+
+ +
+ +
+
+ `; + + const container = formContainer.querySelector('#questions-container'); + container.insertAdjacentHTML('beforeend', newQuestionHTML); + + questionIndex++; + + attachListeners(); + }; + + // Aplicar listeners + const attachListeners = () => { + formContainer.querySelectorAll('.js-type-select').forEach(select => { + select.addEventListener('change', (e) => toggleOptionsVisibility(e.target)); + toggleOptionsVisibility(select); + }); + + formContainer.querySelectorAll('.js-add-option').forEach(button => { + button.addEventListener('click', addOptionField); + }); + + const mainAddQuestionButton = formContainer.querySelector('.js-add-question'); + if (mainAddQuestionButton) { + mainAddQuestionButton.addEventListener('click', addNewQuestionBlock); + } + }; + + attachListeners(); +}); 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/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..467f6bf102 --- /dev/null +++ b/app/app/models/formulario.rb @@ -0,0 +1,39 @@ +require 'csv' + +class Formulario < ApplicationRecord + has_many :questao_formularios, dependent: :destroy + + has_many :formulario_respondidos, dependent: :destroy + + 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 new file mode 100644 index 0000000000..3569b3b3f7 --- /dev/null +++ b/app/app/models/formulario_respondido.rb @@ -0,0 +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/models/formulario_turma.rb b/app/app/models/formulario_turma.rb new file mode 100644 index 0000000000..c5139486f5 --- /dev/null +++ b/app/app/models/formulario_turma.rb @@ -0,0 +1,4 @@ +class FormularioTurma < ApplicationRecord + belongs_to :formulario + belongs_to :turma +end \ No newline at end of file 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..7d91ecc59d --- /dev/null +++ b/app/app/models/opcao_template.rb @@ -0,0 +1,8 @@ +class OpcaoTemplate < ApplicationRecord + # Chave estrangeira: questao_template_id + belongs_to :questao_template + + # 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_formulario.rb b/app/app/models/questao_formulario.rb new file mode 100644 index 0000000000..880721eeae --- /dev/null +++ b/app/app/models/questao_formulario.rb @@ -0,0 +1,5 @@ +class QuestaoFormulario < ApplicationRecord + belongs_to :formulario + 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 new file mode 100644 index 0000000000..d8f8652f24 --- /dev/null +++ b/app/app/models/questao_respondida.rb @@ -0,0 +1,6 @@ +class QuestaoRespondida < ApplicationRecord + belongs_to :formulario_respondido + belongs_to :questao_formulario + + belongs_to :opcao_formulario, optional: true +end diff --git a/app/app/models/questao_template.rb b/app/app/models/questao_template.rb new file mode 100644 index 0000000000..b7e3e8bbc8 --- /dev/null +++ b/app/app/models/questao_template.rb @@ -0,0 +1,12 @@ +class QuestaoTemplate < ApplicationRecord + # 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 new file mode 100644 index 0000000000..6afb2b2f6b --- /dev/null +++ b/app/app/models/template.rb @@ -0,0 +1,14 @@ +class Template < ApplicationRecord + # 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/models/turma.rb b/app/app/models/turma.rb new file mode 100644 index 0000000000..99a50194f2 --- /dev/null +++ b/app/app/models/turma.rb @@ -0,0 +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 + 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 new file mode 100644 index 0000000000..07b4360b31 --- /dev/null +++ b/app/app/models/usuario.rb @@ -0,0 +1,14 @@ +class Usuario < ApplicationRecord + 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/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..00c427af85 --- /dev/null +++ b/app/app/services/sigaa_service.rb @@ -0,0 +1,119 @@ +require 'json' + +class SigaaService + def initialize(classes_path, members_path) + @classes_path = classes_path + @members_path = members_path + end + + def call + puts ">>> INICIANDO SERVIÇO SIGAA <<<" + + 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 + + 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] + dep = Departamento.find_or_create_by!(nome: dept_code) + + # Matéria + mat = Materia.find_or_create_by!(codigo: entry['code']) do |m| + m.nome = entry['name'] + m.departamento = dep + end + puts " - Matéria Processada: #{mat.nome} (#{mat.codigo})" + + # Turma + turma = Turma.find_or_create_by!( + num_turma: entry['class']['classCode'], + semestre: entry['class']['semester'], + 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']) + 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 + ) + unless turma + puts " [PULADO] Turma #{entry['classCode']} não encontrada para esta matéria." + next + end + + # Docente + if entry['docente'] + puts " -> Processando Docente..." + process_user(entry['docente'], turma, 'docente') + end + + # 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']) + + 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 + 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..cf837728c7 --- /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 admin_edit_templates_path do %> + <%= render(ButtonComponent.new(text: "Editar Templates", variant: :secondary, type: :button)) %> + <% end %> + + <%= link_to admin_send_forms_path do %> + <%= render(ButtonComponent.new(text: "Enviar Formulários", variant: :secondary, type: :button)) %> + <% end %> + + <%= link_to resultados_path do %> + <%= render(ButtonComponent.new(text: "Resultados", variant: :tertiary, type: :button)) %> + <% 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 new file mode 100644 index 0000000000..bd93b32312 --- /dev/null +++ b/app/app/views/admins/edit_templates.html.erb @@ -0,0 +1,58 @@ +
+ +
+

Gerenciamento - Templates

+
+ +
+ + <% if notice %> + + <% elsif flash[:alert] %> + + <% end %> + +
+ + <% @templates.each do |template| %> +
+
+
+

<%= template.nome %>

+

Semestre e Código

+
+
+ + <%# 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 %> + + <%# 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}'?" + }, + title: "Excluir", + class: "cursor-pointer hover:text-red-600" do %> + + <% end %> +
+
+

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

+
+ <% end %> + + <%# Botão para CRIAR Novo Template %> +
+ <%= link_to admin_new_template_path, 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/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/admins/new_template.html.erb b/app/app/views/admins/new_template.html.erb new file mode 100644 index 0000000000..a43e873ad1 --- /dev/null +++ b/app/app/views/admins/new_template.html.erb @@ -0,0 +1,43 @@ +
+ + <%= form_with model: @template, url: admin_templates_path, local: true, html: { class: 'template-form-container' } do |form| %> + +
+ +
+ + <%# 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" %> +
+ + <%# 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 %> +
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/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/app/views/dashboard/index.html.erb b/app/app/views/dashboard/index.html.erb new file mode 100644 index 0000000000..f0f4983030 --- /dev/null +++ b/app/app/views/dashboard/index.html.erb @@ -0,0 +1,33 @@ +
+
+ + <% 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, + semestre: turma.semestre, + formulario_id: formulario.id, + turma_id: turma.id + )) %> + + <% end %> + <% else %> + <% 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/application.html.erb b/app/app/views/layouts/application.html.erb new file mode 100644 index 0000000000..440a69e8db --- /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/dashboard.html.erb b/app/app/views/layouts/dashboard.html.erb new file mode 100644 index 0000000000..b5ff559cb8 --- /dev/null +++ b/app/app/views/layouts/dashboard.html.erb @@ -0,0 +1,36 @@ + + + + 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, path: request.path)) %> + +
+ <%# O CONTEÚDO DA VIEW (dashboard/index ou admins/dashboard) ENTRA AQUI %> + <%= yield %> +
+
+
+ + + \ No newline at end of file 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/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/app/views/sessions/new.html.erb b/app/app/views/sessions/new.html.erb new file mode 100644 index 0000000000..75636a1e40 --- /dev/null +++ b/app/app/views/sessions/new.html.erb @@ -0,0 +1,65 @@ +
+ +
+ +
+ +

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 + )) %> +
+ +
+ <%= render(ButtonComponent.new( + text: "Cadastrar", + type: :button, + variant: :primary, + link: cadastro_path + )) %> +
+ + <% end %> +
+ + + +
+
\ No newline at end of file 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 new file mode 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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 100755 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..8fd9010b01 --- /dev/null +++ b/app/config/routes.rb @@ -0,0 +1,44 @@ +Rails.application.routes.draw do + get 'login', to: 'sessions#new' + 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' + + get 'admin/importar', to: 'admins#import_form', as: 'admin_importar_form' + post 'admin/importar', to: 'admins#importar' + + get 'admin/send_forms', to: 'admins#send_forms', as: 'admin_send_forms' + + get 'admin/templates', to: 'admins#edit_templates', as: 'admin_edit_templates' + get 'admin/templates/new', to: 'admins#new_template', as: 'admin_new_template' + + + 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' + scope '/admin' do + resources :resultados, only: [:index] do + member do + get :baixar + end + end + end + + 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/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/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/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/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/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/schema.rb b/app/db/schema.rb new file mode 100644 index 0000000000..4029ad6022 --- /dev/null +++ b/app/db/schema.rb @@ -0,0 +1,155 @@ +# 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_08_022025) 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" + 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/db/seeds.rb b/app/db/seeds.rb new file mode 100644 index 0000000000..a1d1303c53 --- /dev/null +++ b/app/db/seeds.rb @@ -0,0 +1,139 @@ +# 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 +alunos.each_with_index do |aluno, index| + UsuarioTurma.create!(usuario: aluno, turma: turma_bd) + # 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 +puts "📝 Criando templates e formulários..." + +# Template +template = Template.create!(nome: "Avaliação Padrão CIC", usuario: admin) + +# 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 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_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 +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 "--------------------------------------------------" +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 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 0000000000..c4c9dbfbbd Binary files /dev/null and b/app/public/icon.png differ 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/spec/features/answer_evaluation_spec.rb b/app/spec/features/answer_evaluation_spec.rb new file mode 100644 index 0000000000..3ad70e7bfb --- /dev/null +++ b/app/spec/features/answer_evaluation_spec.rb @@ -0,0 +1,56 @@ +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 + 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 + 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/login_spec.rb b/app/spec/features/login_spec.rb new file mode 100644 index 0000000000..cc646ddbda --- /dev/null +++ b/app/spec/features/login_spec.rb @@ -0,0 +1,41 @@ +# 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", + ocupacao: "discente" + ) + + # 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/features/pending_forms_spec.rb b/app/spec/features/pending_forms_spec.rb new file mode 100644 index 0000000000..9fc832ce38 --- /dev/null +++ b/app/spec/features/pending_forms_spec.rb @@ -0,0 +1,53 @@ +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 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") + 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") + # 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 + + # 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..9101c2f1fe --- /dev/null +++ b/app/spec/features/registration_spec.rb @@ -0,0 +1,41 @@ +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" + select "discente", from: "Ocupação" + + 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" + select "discente", from: "Ocupação" + + 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..e236fece3c --- /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 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..59adbd0b0a --- /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("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 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 new file mode 100644 index 0000000000..d0fcd5c18a --- /dev/null +++ b/app/spec/helpers/dashboard_helper_spec.rb @@ -0,0 +1,95 @@ +require 'rails_helper' + +RSpec.describe DashboardHelper, type: :helper do + 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 new file mode 100644 index 0000000000..c87dbda0ec --- /dev/null +++ b/app/spec/helpers/formularios_helper_spec.rb @@ -0,0 +1,46 @@ +require 'rails_helper' + +RSpec.describe FormulariosHelper, type: :helper do + 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/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/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/requests/dashboard_spec.rb b/app/spec/requests/dashboard_spec.rb new file mode 100644 index 0000000000..e9af554c97 --- /dev/null +++ b/app/spec/requests/dashboard_spec.rb @@ -0,0 +1,21 @@ +require 'rails_helper' + +RSpec.describe "Dashboards", type: :request 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" + expect(response).to have_http_status(:success) + 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 new file mode 100644 index 0000000000..856c34b8fc --- /dev/null +++ b/app/spec/requests/formularios_spec.rb @@ -0,0 +1,32 @@ +require 'rails_helper' + +RSpec.describe "Formularios", type: :request do + 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 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 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 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/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 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/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/files/.keep b/app/test/fixtures/files/.keep new file mode 100644 index 0000000000..e69de29bb2 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/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/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 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 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 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