diff --git a/.annotaterb.yml b/.annotaterb.yml new file mode 100644 index 000000000..92184b6ad --- /dev/null +++ b/.annotaterb.yml @@ -0,0 +1,71 @@ +--- +:position: before +:position_in_additional_file_patterns: before +:position_in_class: before +:position_in_factory: before +:position_in_fixture: before +:position_in_routes: before +:position_in_serializer: before +:position_in_test: before +:classified_sort: true +:exclude_controllers: true +:exclude_factories: true +:exclude_fixtures: true +:exclude_helpers: true +:exclude_scaffolds: true +:exclude_serializers: false +:exclude_sti_subclasses: false +:exclude_tests: true +:force: false +:format_markdown: false +:format_rdoc: false +:format_yard: false +:frozen: false +:grouped_polymorphic: false +:ignore_database_name: false +:ignore_model_sub_dir: false +:ignore_unknown_models: false +:include_version: false +:show_check_constraints: false +:show_unique_constraints: false +:show_exclusion_constraints: false +:show_enums: false +:show_complete_foreign_keys: false +:show_foreign_keys: true +:show_indexes: true +:show_indexes_comments: false +:show_indexes_include: false +:simple_indexes: false +:sort: false +:timestamp: false +:trace: false +:with_comment: true +:with_column_comments: true +:with_table_comments: true +:position_of_column_comment: :with_name +:active_admin: false +:command: +:debug: false +:hide_default_column_types: '' +:hide_limit_column_types: '' +:timestamp_columns: +- created_at +- updated_at +:ignore_columns: +:ignore_routes: +:ignore_multi_database_name: false +:models: true +:routes: false +:skip_on_db_migrate: false +:auto_annotate_routes_after_migrate: false +:target_action: :do_annotations +:wrapper: +:wrapper_close: +:wrapper_open: +:classes_default_to_s: [] +:additional_file_patterns: [] +:model_dir: +- app/models +:require: [] +:root_dir: +- '' diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 000000000..325bfc036 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,51 @@ +# See https://docs.docker.com/engine/reference/builder/#dockerignore-file for more about ignoring files. + +# Ignore git directory. +/.git/ +/.gitignore + +# Ignore bundler config. +/.bundle + +# Ignore all environment files. +/.env* + +# Ignore all default key files. +/config/master.key +/config/credentials/*.key + +# Ignore all logfiles and tempfiles. +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep + +# Ignore pidfiles, but keep the directory. +/tmp/pids/* +!/tmp/pids/.keep + +# Ignore storage (uploaded files in development and any SQLite databases). +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep + +# Ignore assets. +/node_modules/ +/app/assets/builds/* +!/app/assets/builds/.keep +/public/assets + +# Ignore CI service files. +/.github + +# Ignore Kamal files. +/config/deploy*.yml +/.kamal + +# Ignore development files +/.devcontainer + +# Ignore Docker-related files +/.dockerignore +/Dockerfile* diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 000000000..83610cfa4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +version: 2 +updates: +- package-ecosystem: bundler + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 +- package-ecosystem: github-actions + directory: "/" + schedule: + interval: weekly + open-pull-requests-limit: 10 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..708f1419e --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,137 @@ +name: CI + +on: + pull_request: + push: + branches: [ master ] + +jobs: + scan_ruby: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Scan for common Rails security vulnerabilities using static analysis + run: bin/brakeman --no-pager + + - name: Scan for known security vulnerabilities in gems used + run: bin/bundler-audit + + lint: + runs-on: ubuntu-latest + env: + RUBOCOP_CACHE_ROOT: tmp/rubocop + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Prepare RuboCop cache + uses: actions/cache@v4 + env: + DEPENDENCIES_HASH: ${{ hashFiles('.ruby-version', '**/.rubocop.yml', '**/.rubocop_todo.yml', 'Gemfile.lock') }} + with: + path: ${{ env.RUBOCOP_CACHE_ROOT }} + key: rubocop-${{ runner.os }}-${{ env.DEPENDENCIES_HASH }}-${{ github.ref_name == github.event.repository.default_branch && github.run_id || 'default' }} + restore-keys: | + rubocop-${{ runner.os }}-${{ env.DEPENDENCIES_HASH }}- + + - name: Lint code for consistent style + run: bin/rubocop -f github + + test: + runs-on: ubuntu-latest + + services: + postgres: + image: postgres + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - 5433:5432 + options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=3 + + # 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: Install packages + run: sudo apt-get update && sudo apt-get install --no-install-recommends -y libpq-dev libvips + + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Run tests + env: + RAILS_ENV: test + DATABASE_URL: postgres://postgres:postgres@localhost:5433 + # 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: + postgres: + image: postgres + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + ports: + - 5433:5432 + options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=3 + + # 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: Install packages + run: sudo apt-get update && sudo apt-get install --no-install-recommends -y libpq-dev libvips + + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up Ruby + uses: ruby/setup-ruby@v1 + with: + bundler-cache: true + + - name: Run System Tests + env: + RAILS_ENV: test + DATABASE_URL: postgres://postgres:postgres@localhost:5433 + # 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/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 4b950cc66..aab7d9f84 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -11,41 +11,27 @@ jobs: runs-on: ubuntu-latest + permissions: + security-events: write + packages: read + actions: read + contents: read + steps: - name: Checkout repository - uses: actions/checkout@v2 - with: - # We must fetch at least the immediate parents so that if this is - # a pull request then we can checkout the head. - fetch-depth: 2 - - # If this run was triggered by a pull request event, then checkout - # the head of the pull request instead of the merge commit. - - run: git checkout HEAD^2 - if: ${{ github.event_name == 'pull_request' }} - + uses: actions/checkout@v4 + # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - # Override language selection by uncommenting this and choosing your languages - # with: - # languages: go, javascript, csharp, python, cpp, java + uses: github/codeql-action/init@v3 + with: + languages: javascript-typescript, ruby - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release + uses: github/codeql-action/autobuild@v3 - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 + uses: github/codeql-action/analyze@v3 + with: + category: "/language:ruby" diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..fbc41d21e --- /dev/null +++ b/.gitignore @@ -0,0 +1,48 @@ +# Rails +*.rbc +/.bundle +capybara-*.html +.rspec +/log/* +/tmp/* +!/log/.keep +!/tmp/.keep +/storage/* +!/storage/.keep +/tmp/storage/* +!/tmp/storage/.keep +.byebug_history +config/master.key +config/credentials/*.key +.env* +!/.env.example + +# Node / Vite +node_modules/ +vite.config.*.timestamp-*.mjs +app/frontend/dist/ +public/vite-test/ +ssr-dist/ + +# OS / Editor +.DS_Store +*.swp +*.swo +/.vscode/* +!/.vscode/extensions.json +.idea/ + +# Coverage +coverage/ +.simplecov + +# Kamal secrets +.kamal/secrets + +# Vite Ruby +/public/vite* +node_modules +# Vite uses dotenv and suggests to ignore local-only env files. See +# https://vitejs.dev/guide/env-and-mode.html#env-files +*.local + diff --git a/.kamal/hooks/docker-setup.sample b/.kamal/hooks/docker-setup.sample new file mode 100755 index 000000000..a0b053784 --- /dev/null +++ b/.kamal/hooks/docker-setup.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Docker set up on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-app-boot.sample b/.kamal/hooks/post-app-boot.sample new file mode 100755 index 000000000..7d2a13db2 --- /dev/null +++ b/.kamal/hooks/post-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booted app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/post-deploy.sample b/.kamal/hooks/post-deploy.sample new file mode 100755 index 000000000..17b0567a5 --- /dev/null +++ b/.kamal/hooks/post-deploy.sample @@ -0,0 +1,14 @@ +#!/usr/bin/env sh + +# A sample post-deploy hook +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +echo "$KAMAL_PERFORMER deployed $KAMAL_VERSION to $KAMAL_DESTINATION in $KAMAL_RUNTIME seconds" diff --git a/.kamal/hooks/post-proxy-reboot.sample b/.kamal/hooks/post-proxy-reboot.sample new file mode 100755 index 000000000..84548ed04 --- /dev/null +++ b/.kamal/hooks/post-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooted kamal-proxy on $KAMAL_HOSTS" diff --git a/.kamal/hooks/pre-app-boot.sample b/.kamal/hooks/pre-app-boot.sample new file mode 100755 index 000000000..1f9fe844c --- /dev/null +++ b/.kamal/hooks/pre-app-boot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Booting app version $KAMAL_VERSION on $KAMAL_HOSTS..." diff --git a/.kamal/hooks/pre-build.sample b/.kamal/hooks/pre-build.sample new file mode 100755 index 000000000..d53d28cf7 --- /dev/null +++ b/.kamal/hooks/pre-build.sample @@ -0,0 +1,51 @@ +#!/usr/bin/env sh + +# A sample pre-build hook +# +# Checks: +# 1. We have a clean checkout +# 2. A remote is configured +# 3. The branch has been pushed to the remote +# 4. The version we are deploying matches the remote +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +if [ -n "$(git status --porcelain)" ]; then + echo "Git checkout is not clean, aborting..." >&2 + git status --porcelain >&2 + exit 1 +fi + +first_remote=$(git remote) + +if [ -z "$first_remote" ]; then + echo "No git remote set, aborting..." >&2 + exit 1 +fi + +current_branch=$(git branch --show-current) + +if [ -z "$current_branch" ]; then + echo "Not on a git branch, aborting..." >&2 + exit 1 +fi + +remote_head=$(git ls-remote $first_remote --tags $current_branch | cut -f1) + +if [ -z "$remote_head" ]; then + echo "Branch not pushed to remote, aborting..." >&2 + exit 1 +fi + +if [ "$KAMAL_VERSION" != "$remote_head" ]; then + echo "Version ($KAMAL_VERSION) does not match remote HEAD ($remote_head), aborting..." >&2 + exit 1 +fi + +exit 0 diff --git a/.kamal/hooks/pre-connect.sample b/.kamal/hooks/pre-connect.sample new file mode 100755 index 000000000..77744bdca --- /dev/null +++ b/.kamal/hooks/pre-connect.sample @@ -0,0 +1,47 @@ +#!/usr/bin/env ruby + +# A sample pre-connect check +# +# Warms DNS before connecting to hosts in parallel +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) +# KAMAL_RUNTIME + +hosts = ENV["KAMAL_HOSTS"].split(",") +results = nil +max = 3 + +elapsed = Benchmark.realtime do + results = hosts.map do |host| + Thread.new do + tries = 1 + + begin + Socket.getaddrinfo(host, 0, Socket::AF_UNSPEC, Socket::SOCK_STREAM, nil, Socket::AI_CANONNAME) + rescue SocketError + if tries < max + puts "Retrying DNS warmup: #{host}" + tries += 1 + sleep rand + retry + else + puts "DNS warmup failed: #{host}" + host + end + end + + tries + end + end.map(&:value) +end + +retries = results.sum - hosts.size +nopes = results.count { |r| r == max } + +puts "Prewarmed %d DNS lookups in %.2f sec: %d retries, %d failures" % [ hosts.size, elapsed, retries, nopes ] diff --git a/.kamal/hooks/pre-deploy.sample b/.kamal/hooks/pre-deploy.sample new file mode 100755 index 000000000..05b3055b7 --- /dev/null +++ b/.kamal/hooks/pre-deploy.sample @@ -0,0 +1,122 @@ +#!/usr/bin/env ruby + +# A sample pre-deploy hook +# +# Checks the Github status of the build, waiting for a pending build to complete for up to 720 seconds. +# +# Fails unless the combined status is "success" +# +# These environment variables are available: +# KAMAL_RECORDED_AT +# KAMAL_PERFORMER +# KAMAL_VERSION +# KAMAL_HOSTS +# KAMAL_COMMAND +# KAMAL_SUBCOMMAND +# KAMAL_ROLES (if set) +# KAMAL_DESTINATION (if set) + +# Only check the build status for production deployments +if ENV["KAMAL_COMMAND"] == "rollback" || ENV["KAMAL_DESTINATION"] != "production" + exit 0 +end + +require "bundler/inline" + +# true = install gems so this is fast on repeat invocations +gemfile(true, quiet: true) do + source "https://rubygems.org" + + gem "octokit" + gem "faraday-retry" +end + +MAX_ATTEMPTS = 72 +ATTEMPTS_GAP = 10 + +def exit_with_error(message) + $stderr.puts message + exit 1 +end + +class GithubStatusChecks + attr_reader :remote_url, :git_sha, :github_client, :combined_status + + def initialize + @remote_url = github_repo_from_remote_url + @git_sha = `git rev-parse HEAD`.strip + @github_client = Octokit::Client.new(access_token: ENV["GITHUB_TOKEN"]) + refresh! + end + + def refresh! + @combined_status = github_client.combined_status(remote_url, git_sha) + end + + def state + combined_status[:state] + end + + def first_status_url + first_status = combined_status[:statuses].find { |status| status[:state] == state } + first_status && first_status[:target_url] + end + + def complete_count + combined_status[:statuses].count { |status| status[:state] != "pending"} + end + + def total_count + combined_status[:statuses].count + end + + def current_status + if total_count > 0 + "Completed #{complete_count}/#{total_count} checks, see #{first_status_url} ..." + else + "Build not started..." + end + end + + private + def github_repo_from_remote_url + url = `git config --get remote.origin.url`.strip.delete_suffix(".git") + if url.start_with?("https://github.com/") + url.delete_prefix("https://github.com/") + elsif url.start_with?("git@github.com:") + url.delete_prefix("git@github.com:") + else + url + end + end +end + + +$stdout.sync = true + +begin + puts "Checking build status..." + + attempts = 0 + checks = GithubStatusChecks.new + + loop do + case checks.state + when "success" + puts "Checks passed, see #{checks.first_status_url}" + exit 0 + when "failure" + exit_with_error "Checks failed, see #{checks.first_status_url}" + when "pending" + attempts += 1 + end + + exit_with_error "Checks are still pending, gave up after #{MAX_ATTEMPTS * ATTEMPTS_GAP} seconds" if attempts == MAX_ATTEMPTS + + puts checks.current_status + sleep(ATTEMPTS_GAP) + checks.refresh! + end +rescue Octokit::NotFound + exit_with_error "Build status could not be found" +end diff --git a/.kamal/hooks/pre-proxy-reboot.sample b/.kamal/hooks/pre-proxy-reboot.sample new file mode 100755 index 000000000..93e11991d --- /dev/null +++ b/.kamal/hooks/pre-proxy-reboot.sample @@ -0,0 +1,3 @@ +#!/usr/bin/env sh + +echo "Rebooting kamal-proxy on $KAMAL_HOSTS..." diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 000000000..f9d86d4a5 --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,8 @@ +# Omakase Ruby styling for Rails +inherit_gem: { rubocop-rails-omakase: rubocop.yml } + +# Overwrite or add rules to create your own house style +# +# # Use `[a, [b, c]]` not `[ a, [ b, c ] ]` +# Layout/SpaceInsideArrayLiteralBrackets: +# Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 000000000..1cf76f52b --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +ruby-4.0.6 diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..d207b232f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,97 @@ +# syntax=docker/dockerfile:1 +# check=error=true + +# This Dockerfile is designed for production, not development. Use with Kamal or build'n'run by hand: +# docker build -t fullstack_developer . +# docker run -d -p 80:80 -e RAILS_MASTER_KEY= --name fullstack_developer fullstack_developer + +# For a containerized dev environment, see Dev Containers: https://guides.rubyonrails.org/getting_started_with_devcontainer.html + +# Make sure RUBY_VERSION matches the Ruby version in .ruby-version +ARG RUBY_VERSION=4.0.6 +FROM docker.io/library/ruby:$RUBY_VERSION-slim AS base + +# Rails app lives here +WORKDIR /rails + +# Install base packages +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y curl libjemalloc2 libvips postgresql-client && \ + 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 and JS assets (Node 22 for Vite + SSR) +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y build-essential git libpq-dev libvips libyaml-dev pkg-config ca-certificates curl gnupg && \ + mkdir -p /etc/apt/keyrings && \ + curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \ + echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \ + apt-get update -qq && \ + apt-get install --no-install-recommends -y nodejs && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# Install JS dependencies first for better layer caching +COPY package.json package-lock.json ./ +RUN npm ci + +# Install application gems +COPY vendor/* ./vendor/ +COPY Gemfile Gemfile.lock ./ + +RUN bundle install && \ + rm -rf ~/.bundle/ "${BUNDLE_PATH}"/ruby/*/cache "${BUNDLE_PATH}"/ruby/*/bundler/gems/*/.git && \ + # -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 + bundle exec bootsnap precompile -j 1 --gemfile + +# Copy application code +COPY . . + +# Precompile bootsnap code for faster boot times. +# -j 1 disable parallel compilation to avoid a QEMU bug: https://github.com/rails/bootsnap/issues/495 +RUN bundle exec bootsnap precompile -j 1 app/ lib/ + +# Precompiling assets for production without requiring secret RAILS_MASTER_KEY +RUN SECRET_KEY_BASE_DUMMY=1 ./bin/rails assets:precompile + + + + +# Final stage for app image +FROM base + +# Node.js is required at runtime for the Inertia SSR server and for running +# the test suite (Vite) inside the container. +RUN apt-get update -qq && \ + apt-get install --no-install-recommends -y ca-certificates curl gnupg && \ + mkdir -p /etc/apt/keyrings && \ + curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \ + echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_22.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \ + apt-get update -qq && \ + apt-get install --no-install-recommends -y nodejs && \ + rm -rf /var/lib/apt/lists /var/cache/apt/archives + +# 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 13714 +CMD ["./bin/thrust", "./bin/rails", "server"] diff --git a/Gemfile b/Gemfile new file mode 100644 index 000000000..75c34f344 --- /dev/null +++ b/Gemfile @@ -0,0 +1,89 @@ +source "https://rubygems.org" + +# Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main" +gem "rails", "~> 8.1.3", ">= 8.1.3.1" +# The modern asset pipeline for Rails [https://github.com/rails/propshaft] +gem "propshaft" +# Use postgresql as the database for Active Record +gem "pg", "~> 1.1" +# Use the Puma web server [https://github.com/puma/puma] +gem "puma", ">= 5.0" +# Use Tailwind CSS [https://github.com/rails/tailwindcss-rails] +gem "tailwindcss-rails" +# SPA monolith: Inertia + React + Vite (non-negotiable frontend) +gem "inertia_rails", "~> 3.0" +gem "vite_rails", "~> 3.0" + +# 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" + +# Pagination for list views +gem "kaminari" + +# Pin JSON < 3 for Ruby 4 kwargs compat with ActiveSupport 8.1 (JSON.parse positional hash) +gem "json", "< 3" + +# Performance profiling leveraging Ruby 4's ZJIT compilation optimizations +gem "benchmark-ips" + +# Spreadsheet import (.csv/.xlsx) +gem "csv" +gem "rubyXL", "~> 3.4" + +# Release It! — error tracking and performance monitoring +gem "sentry-ruby" +gem "sentry-rails" + +# Windows does not include zoneinfo files, so bundle the tzinfo-data gem +gem "tzinfo-data", platforms: %i[ windows jruby ] + +# Use the database-backed adapters for Rails.cache, Active Job, and Action Cable +gem "solid_cache" +gem "solid_queue" +gem "solid_cable" + +# Reduces boot times through caching; required in config/boot.rb +gem "bootsnap", require: false + +# Deploy this application anywhere as a Docker container [https://kamal-deploy.org] +gem "kamal", require: false + +# Add HTTP asset caching/compression and X-Sendfile acceleration to Puma [https://github.com/basecamp/thruster/] +gem "thruster", require: false + +# Use Active Storage variants [https://guides.rubyonrails.org/active_storage_overview.html#transforming-images] +gem "image_processing", "~> 1.2" + +group :development, :test do + # See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-the-debug-gem + gem "debug", platforms: %i[ mri windows ], require: "debug/prelude" + + # 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" + + # Annotate models with schema info + gem "annotaterb", require: false +end + +group :test do + # Coverage gate (90% minimum) + gem "simplecov", require: false + + # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing] + gem "capybara" + gem "selenium-webdriver" +end diff --git a/Gemfile.lock b/Gemfile.lock new file mode 100644 index 000000000..987408f84 --- /dev/null +++ b/Gemfile.lock @@ -0,0 +1,626 @@ +GEM + remote: https://rubygems.org/ + specs: + action_text-trix (2.1.19) + railties + actioncable (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + nio4r (~> 2.0) + websocket-driver (>= 0.6.1) + zeitwerk (~> 2.6) + actionmailbox (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + actionmailer (8.1.3.1) + actionpack (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activesupport (= 8.1.3.1) + mail (>= 2.8.0) + rails-dom-testing (~> 2.2) + actionpack (8.1.3.1) + actionview (= 8.1.3.1) + activesupport (= 8.1.3.1) + nokogiri (>= 1.8.5) + rack (>= 2.2.4) + rack-session (>= 1.0.1) + rack-test (>= 0.6.3) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + useragent (~> 0.16) + actiontext (8.1.3.1) + action_text-trix (~> 2.1.15) + actionpack (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.6.0) + nokogiri (>= 1.8.5) + actionview (8.1.3.1) + activesupport (= 8.1.3.1) + builder (~> 3.1) + erubi (~> 1.11) + rails-dom-testing (~> 2.2) + rails-html-sanitizer (~> 1.6) + activejob (8.1.3.1) + activesupport (= 8.1.3.1) + globalid (>= 0.3.6) + activemodel (8.1.3.1) + activesupport (= 8.1.3.1) + activerecord (8.1.3.1) + activemodel (= 8.1.3.1) + activesupport (= 8.1.3.1) + timeout (>= 0.4.0) + activestorage (8.1.3.1) + actionpack (= 8.1.3.1) + activejob (= 8.1.3.1) + activerecord (= 8.1.3.1) + activesupport (= 8.1.3.1) + marcel (~> 1.0) + activesupport (8.1.3.1) + base64 + bigdecimal + concurrent-ruby (~> 1.0, >= 1.3.1) + connection_pool (>= 2.2.5) + drb + i18n (>= 1.6, < 2) + json + logger (>= 1.4.2) + minitest (>= 5.1) + securerandom (>= 0.3) + tzinfo (~> 2.0, >= 2.0.5) + uri (>= 0.13.1) + addressable (2.9.0) + public_suffix (>= 2.0.2, < 8.0) + annotaterb (4.24.0) + activerecord (>= 6.0.0) + activesupport (>= 6.0.0) + ast (2.4.3) + base64 (0.3.0) + bcrypt (3.1.22) + bcrypt_pbkdf (1.1.2) + benchmark-ips (2.15.1) + bigdecimal (4.1.2) + bindex (0.8.1) + bootsnap (1.26.0) + msgpack (~> 1.5) + brakeman (8.0.6) + racc + builder (3.3.0) + bundler-audit (0.9.3) + bundler (>= 1.2.0) + thor (~> 1.0) + capybara (3.40.0) + addressable + matrix + mini_mime (>= 0.1.3) + nokogiri (~> 1.11) + rack (>= 1.6.0) + rack-test (>= 0.6.3) + regexp_parser (>= 1.5, < 3.0) + xpath (~> 3.2) + concurrent-ruby (1.3.8) + connection_pool (3.0.2) + crass (1.0.7) + csv (3.3.6) + date (3.5.1) + debug (1.11.1) + irb (~> 1.10) + reline (>= 0.3.8) + dotenv (3.2.0) + drb (2.2.3) + dry-cli (1.4.1) + ed25519 (1.4.0) + erb (6.0.7) + erubi (1.13.1) + et-orbi (1.4.2) + tzinfo + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fugit (1.13.0) + et-orbi (~> 1.4) + raabro (~> 1.4) + globalid (1.4.0) + activesupport (>= 6.1) + i18n (1.15.2) + concurrent-ruby (~> 1.0) + image_processing (1.14.0) + mini_magick (>= 4.9.5, < 6) + ruby-vips (>= 2.0.17, < 3) + inertia_rails (3.22.0) + railties (>= 6) + io-console (0.9.2) + irb (1.18.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) + jbuilder (2.15.1) + actionview (>= 7.0.0) + activesupport (>= 7.0.0) + json (2.21.2) + kamal (2.12.0) + activesupport (>= 7.0) + base64 (~> 0.2) + bcrypt_pbkdf (~> 1.0) + concurrent-ruby (~> 1.2) + dotenv (~> 3.1) + ed25519 (~> 1.4) + net-ssh (~> 7.3) + sshkit (>= 1.23.0, < 2.0) + thor (~> 1.3) + zeitwerk (>= 2.6.18, < 3.0) + kaminari (1.2.2) + activesupport (>= 4.1.0) + kaminari-actionview (= 1.2.2) + kaminari-activerecord (= 1.2.2) + kaminari-core (= 1.2.2) + kaminari-actionview (1.2.2) + actionview + kaminari-core (= 1.2.2) + kaminari-activerecord (1.2.2) + activerecord + kaminari-core (= 1.2.2) + kaminari-core (1.2.2) + language_server-protocol (3.17.0.6) + lint_roller (1.1.0) + logger (1.7.0) + loofah (2.25.2) + crass (~> 1.0.2) + nokogiri (>= 1.12.0) + mail (2.9.1) + logger + mini_mime (>= 0.1.1) + net-imap + net-pop + net-smtp + marcel (1.2.1) + matrix (0.4.3) + mini_magick (5.4.0) + logger + mini_mime (1.1.5) + minitest (6.0.6) + drb (~> 2.0) + prism (~> 1.5) + msgpack (1.8.4) + mutex_m (0.3.0) + net-imap (0.6.6) + date + net-protocol + net-pop (0.1.2) + net-protocol + net-protocol (0.3.0) + timeout + net-scp (4.1.0) + net-ssh (>= 2.6.5, < 8.0.0) + net-sftp (4.0.0) + net-ssh (>= 5.0.0, < 8.0.0) + net-smtp (0.5.1) + net-protocol + net-ssh (7.3.3) + nio4r (2.7.5) + nokogiri (1.19.4-aarch64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-aarch64-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-arm-linux-musl) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-gnu) + racc (~> 1.4) + nokogiri (1.19.4-x86_64-linux-musl) + racc (~> 1.4) + ostruct (0.6.3) + parallel (2.2.0) + parser (3.3.12.0) + ast (~> 2.4.1) + racc + pg (1.6.3) + pg (1.6.3-aarch64-linux) + pg (1.6.3-aarch64-linux-musl) + pg (1.6.3-x86_64-linux) + pg (1.6.3-x86_64-linux-musl) + pp (0.6.4) + prettyprint + prettyprint (0.2.0) + prism (1.9.0) + propshaft (1.3.2) + actionpack (>= 7.0.0) + activesupport (>= 7.0.0) + rack + public_suffix (7.0.5) + puma (8.0.2) + nio4r (~> 2.0) + raabro (1.5.0) + racc (1.8.1) + rack (3.2.7) + rack-proxy (2.0.0) + rack (>= 2.0, < 4) + rack-session (2.1.2) + base64 (>= 0.1.0) + rack (>= 3.0.0) + rack-test (2.2.0) + rack (>= 1.3) + rackup (2.3.1) + rack (>= 3) + rails (8.1.3.1) + actioncable (= 8.1.3.1) + actionmailbox (= 8.1.3.1) + actionmailer (= 8.1.3.1) + actionpack (= 8.1.3.1) + actiontext (= 8.1.3.1) + actionview (= 8.1.3.1) + activejob (= 8.1.3.1) + activemodel (= 8.1.3.1) + activerecord (= 8.1.3.1) + activestorage (= 8.1.3.1) + activesupport (= 8.1.3.1) + bundler (>= 1.15.0) + railties (= 8.1.3.1) + rails-dom-testing (2.3.0) + activesupport (>= 5.0.0) + minitest + nokogiri (>= 1.6) + rails-html-sanitizer (1.7.1) + loofah (~> 2.25, >= 2.25.2) + nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) + railties (8.1.3.1) + actionpack (= 8.1.3.1) + activesupport (= 8.1.3.1) + irb (~> 1.13) + rackup (>= 1.0.0) + rake (>= 12.2) + thor (~> 1.0, >= 1.2.2) + tsort (>= 0.2) + zeitwerk (~> 2.6) + rainbow (3.1.1) + rake (13.4.2) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.0.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort + regexp_parser (2.12.0) + reline (0.7.0) + io-console (~> 0.5) + rexml (3.4.4) + rubocop (1.90.0) + json (>= 2.3) + language_server-protocol (~> 3.17.0.2) + lint_roller (~> 1.1.0) + parallel (>= 1.10) + parser (>= 3.3.0.2) + rainbow (>= 2.2.2, < 4.0) + regexp_parser (>= 2.9.3, < 3.0) + rubocop-ast (>= 1.49.0, < 2.0) + ruby-progressbar (~> 1.7) + unicode-display_width (>= 2.4.0, < 4.0) + rubocop-ast (1.50.0) + parser (>= 3.3.7.2) + prism (~> 1.7) + rubocop-performance (1.27.0) + lint_roller (~> 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.47.1, < 2.0) + rubocop-rails (2.37.0) + activesupport (>= 4.2.0) + lint_roller (~> 1.1) + rack (>= 1.1) + rubocop (>= 1.89.0, < 2.0) + rubocop-ast (>= 1.44.0, < 2.0) + rubocop-rails-omakase (1.1.0) + rubocop (>= 1.72) + rubocop-performance (>= 1.24) + rubocop-rails (>= 2.30) + ruby-progressbar (1.13.0) + ruby-vips (2.3.0) + ffi (~> 1.12) + logger + rubyXL (3.4.38) + nokogiri (>= 1.10.8) + rubyzip (>= 3.2.2) + rubyzip (3.6.0) + securerandom (0.4.1) + selenium-webdriver (4.48.0) + base64 (~> 0.2) + logger (~> 1.4) + rexml (~> 3.2, >= 3.2.5) + rubyzip (>= 1.2.2, < 4.0) + websocket (~> 1.0) + sentry-rails (7.0.0) + railties (>= 5.2.0) + sentry-ruby (~> 7.0.0) + sentry-ruby (7.0.0) + bigdecimal + concurrent-ruby (~> 1.0, >= 1.0.2) + logger + simplecov (1.2.0) + solid_cable (4.0.2) + actioncable (>= 7.2) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_cache (1.0.10) + activejob (>= 7.2) + activerecord (>= 7.2) + railties (>= 7.2) + solid_queue (1.7.0) + activejob (>= 7.1) + activerecord (>= 7.1) + concurrent-ruby (>= 1.3.1) + fugit (~> 1.11) + railties (>= 7.1) + thor (>= 1.3.1) + sshkit (1.25.1) + base64 + logger + net-scp (>= 1.1.2) + net-sftp (>= 2.1.2) + net-ssh (>= 2.8.0) + ostruct + tailwindcss-rails (4.6.0) + railties (>= 7.0.0) + tailwindcss-ruby (~> 4.0) + tailwindcss-ruby (4.3.3) + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) + tailwindcss-ruby (4.3.3-aarch64-linux-musl) + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) + tailwindcss-ruby (4.3.3-x86_64-linux-musl) + thor (1.5.0) + thruster (0.1.26) + thruster (0.1.26-aarch64-linux) + thruster (0.1.26-x86_64-linux) + timeout (0.6.1) + tsort (0.2.0) + tzinfo (2.0.6) + concurrent-ruby (~> 1.0) + unicode-display_width (3.2.0) + unicode-emoji (~> 4.1) + unicode-emoji (4.2.0) + uri (1.1.1) + useragent (0.16.11) + vite_rails (3.11.1) + railties (>= 5.1, < 9) + vite_ruby (~> 3.0, >= 3.2.2) + vite_ruby (3.10.5) + dry-cli (>= 0.7, < 2) + logger (~> 1.6) + mutex_m + rack-proxy (>= 0.6.1) + zeitwerk (~> 2.2) + web-console (4.3.0) + actionview (>= 8.0.0) + bindex (>= 0.4.0) + railties (>= 8.0.0) + websocket (1.2.11) + websocket-driver (0.8.2) + base64 + websocket-extensions (>= 0.1.0) + websocket-extensions (0.1.5) + xpath (3.2.0) + nokogiri (~> 1.8) + zeitwerk (2.8.3) + +PLATFORMS + aarch64-linux + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + x86_64-linux + x86_64-linux-gnu + x86_64-linux-musl + +DEPENDENCIES + annotaterb + bcrypt (~> 3.1.7) + benchmark-ips + bootsnap + brakeman + bundler-audit + capybara + csv + debug + image_processing (~> 1.2) + inertia_rails (~> 3.0) + jbuilder + json (< 3) + kamal + kaminari + pg (~> 1.1) + propshaft + puma (>= 5.0) + rails (~> 8.1.3, >= 8.1.3.1) + rubocop-rails-omakase + rubyXL (~> 3.4) + selenium-webdriver + sentry-rails + sentry-ruby + simplecov + solid_cable + solid_cache + solid_queue + tailwindcss-rails + thruster + tzinfo-data + vite_rails (~> 3.0) + web-console + +CHECKSUMS + action_text-trix (2.1.19) sha256=7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009 + actioncable (8.1.3.1) sha256=e318528295c878a3efdfe25f0f2267c80cb7a76eba41bb5f64d44aa380a3d91b + actionmailbox (8.1.3.1) sha256=5f704972097d843ade8e435e93694a1dac732b926df1717aceba1f3840082b1c + actionmailer (8.1.3.1) sha256=88ea441b28ff02a0c6c006468892642a3d9942affce9d294e81a74504aa5c43c + actionpack (8.1.3.1) sha256=974cb7154548e81f470b1b0f247b99cb38e87825899dca58610596e2817723d0 + actiontext (8.1.3.1) sha256=5da729d833d1a29cddb1eee938878e55e503d2613e00e735f5daf58c2ba98af2 + actionview (8.1.3.1) sha256=2da68b8414c47b43bfbed1ce69c5afe1c04f78c267aacb5660a4cab5ca12cfb6 + activejob (8.1.3.1) sha256=1c8dd275df930df40deecffec63d913a550a33fd94bd298f69721dd96939954a + activemodel (8.1.3.1) sha256=99cc02ce2faec371d14440949d85787ebd23a907c9baef0a9d4bcd4d21888f88 + activerecord (8.1.3.1) sha256=0a2fb6c28f4938f6b013a3a549bec0a7e37d535f3dc8990e804bcc3258c0403b + activestorage (8.1.3.1) sha256=f555254f387b1cffa499d2fd3115d12635eadc5b15206a8534316a67036163ef + activesupport (8.1.3.1) sha256=85458765f25ea48b9019c46b6bb3fa5683197bf4280d9f06710a6e8d7a831376 + addressable (2.9.0) sha256=7fdf6ac3660f7f4e867a0838be3f6cf722ace541dd97767fa42bc6cfa980c7af + annotaterb (4.24.0) sha256=3953d3a3fb86ef06639a8d5ea29001e4af1e51cabd147973b1b23524b8fbced6 + ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383 + base64 (0.3.0) sha256=27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b + bcrypt (3.1.22) sha256=1f0072e88c2d705d94aff7f2c5cb02eb3f1ec4b8368671e19112527489f29032 + bcrypt_pbkdf (1.1.2) sha256=c2414c23ce66869b3eb9f643d6a3374d8322dfb5078125c82792304c10b94cf6 + benchmark-ips (2.15.1) sha256=07a1a9f3c6105ecaf68c174fc3fbcddd71a0e9ada6236ae03093a0dcfd812d59 + bigdecimal (4.1.2) sha256=53d217666027eab4280346fba98e7d5b66baaae1b9c3c1c0ffe89d48188a3fbd + bindex (0.8.1) sha256=7b1ecc9dc539ed8bccfc8cb4d2732046227b09d6f37582ff12e50a5047ceb17e + bootsnap (1.26.0) sha256=ca96237015e6cd74a02963d5821cf00ac5ea134653b323e8cd6d702a7718bf1b + brakeman (8.0.6) sha256=759cc69341115e6c2dcd47b6fd8649a0b9bd540e3585ac8a0a94e31c66fee386 + builder (3.3.0) sha256=497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f + bundler-audit (0.9.3) sha256=81c8766c71e47d0d28a0f98c7eed028539f21a6ea3cd8f685eb6f42333c9b4e9 + capybara (3.40.0) sha256=42dba720578ea1ca65fd7a41d163dd368502c191804558f6e0f71b391054aeef + concurrent-ruby (1.3.8) sha256=b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1 + connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a + crass (1.0.7) sha256=94868719948664c89ddcaf0a37c65048413dfcb1c869470a5f7a7ceb5390b295 + csv (3.3.6) sha256=aba61e7e507a66f03d45cb1f3c4b6359861c3504038b422962875dce099e4456 + date (3.5.1) sha256=750d06384d7b9c15d562c76291407d89e368dda4d4fff957eb94962d325a0dc0 + debug (1.11.1) sha256=2e0b0ac6119f2207a6f8ac7d4a73ca8eb4e440f64da0a3136c30343146e952b6 + dotenv (3.2.0) sha256=e375b83121ea7ca4ce20f214740076129ab8514cd81378161f11c03853fe619d + drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373 + dry-cli (1.4.1) sha256=b8015bb76c708aa8705a36faf694973e75eeeffca39b89c8e172dc6f66a7d874 + ed25519 (1.4.0) sha256=16e97f5198689a154247169f3453ef4cfd3f7a47481fde0ae33206cdfdcac506 + erb (6.0.7) sha256=c5ca6dc25b0ef974a44dc8f59fe847577122483b1968a38dec305c60bf91ee92 + erubi (1.13.1) sha256=a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9 + et-orbi (1.4.2) sha256=bb555dae668419cb24caa2a293a170e58be6d4df1e017c51f5030bdc133cd20c + ffi (1.17.4-aarch64-linux-gnu) sha256=b208f06f91ffd8f5e1193da3cae3d2ccfc27fc36fba577baf698d26d91c080df + ffi (1.17.4-aarch64-linux-musl) sha256=9286b7a615f2676245283aef0a0a3b475ae3aae2bb5448baace630bb77b91f39 + ffi (1.17.4-arm-linux-gnu) sha256=d6dbddf7cb77bf955411af5f187a65b8cd378cb003c15c05697f5feee1cb1564 + ffi (1.17.4-arm-linux-musl) sha256=9d4838ded0465bef6e2426935f6bcc93134b6616785a84ffd2a3d82bc3cf6f95 + ffi (1.17.4-x86_64-linux-gnu) sha256=9d3db14c2eae074b382fa9c083fe95aec6e0a1451da249eab096c34002bc752d + ffi (1.17.4-x86_64-linux-musl) sha256=3fdf9888483de005f8ef8d1cf2d3b20d86626af206cbf780f6a6a12439a9c49e + fugit (1.13.0) sha256=a4f093fce740da52f216740a5041e2a594ea763cdb89e8b2754ca4399634ab18 + globalid (1.4.0) sha256=037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427 + i18n (1.15.2) sha256=00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5 + image_processing (1.14.0) sha256=754cc169c9c262980889bec6bfd325ed1dafad34f85242b5a07b60af004742fb + inertia_rails (3.22.0) sha256=39c20120de472015d2831fa461f8a09672c68e91c41d3d660e0b1d16b787b7b1 + io-console (0.9.2) sha256=efa74f891dd03c0939a931dfc6e74c2813d904763d456ea9762b0525e748db08 + irb (1.18.0) sha256=de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3 + jbuilder (2.15.1) sha256=2430bec28fb0cebacb5875b1009cf9d8bc3c303ccb810c4c8b062a4b51457637 + json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a + kamal (2.12.0) sha256=c51d1ab085e515470f98d0c0f043637122b5ebf76e8b610cb1fbbed0b7f9b8fa + kaminari (1.2.2) sha256=c4076ff9adccc6109408333f87b5c4abbda5e39dc464bd4c66d06d9f73442a3e + kaminari-actionview (1.2.2) sha256=1330f6fc8b59a4a4ef6a549ff8a224797289ebf7a3a503e8c1652535287cc909 + kaminari-activerecord (1.2.2) sha256=0dd3a67bab356a356f36b3b7236bcb81cef313095365befe8e98057dd2472430 + kaminari-core (1.2.2) sha256=3bd26fec7370645af40ca73b9426a448d09b8a8ba7afa9ba3c3e0d39cdbb83ff + language_server-protocol (3.17.0.6) sha256=5ef2c0c138f8267e1bc631d3328347d354f96724b0af22f2c79516120443b7f0 + lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87 + logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203 + loofah (2.25.2) sha256=2007f746959ac65552456e04b433e83deb22759ab38c838b4445c70e43425918 + mail (2.9.1) sha256=06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8 + marcel (1.2.1) sha256=1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f + matrix (0.4.3) sha256=a0d5ab7ddcc1973ff690ab361b67f359acbb16958d1dc072b8b956a286564c5b + mini_magick (5.4.0) sha256=f120af581d9ed4ec52c57f35a67a605d112bb1d8f582d1415b147fda42d11d78 + mini_mime (1.1.5) sha256=8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef + minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1 + msgpack (1.8.4) sha256=4411c22d350dd1c20250f7eada3cca2695438c2f769cf0782f0cd065d90a3e7b + mutex_m (0.3.0) sha256=cfcb04ac16b69c4813777022fdceda24e9f798e48092a2b817eb4c0a782b0751 + net-imap (0.6.6) sha256=96aa4ee50df3060203e649efc341f53480b791d49e150f2fdebf68beb141a8df + net-pop (0.1.2) sha256=848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3 + net-protocol (0.3.0) sha256=ba310c3d4f1cad46bb1ab20336b06669b1ff8f7c568d9cb9342b32a718547472 + net-scp (4.1.0) sha256=a99b0b92a1e5d360b0de4ffbf2dc0c91531502d3d4f56c28b0139a7c093d1a5d + net-sftp (4.0.0) sha256=65bb91c859c2f93b09826757af11b69af931a3a9155050f50d1b06d384526364 + net-smtp (0.5.1) sha256=ed96a0af63c524fceb4b29b0d352195c30d82dd916a42f03c62a3a70e5b70736 + net-ssh (7.3.3) sha256=831def58b2c51dcef66ec00d29397d4f210de89c19fe78f95873ca30f386e86a + nio4r (2.7.5) sha256=6c90168e48fb5f8e768419c93abb94ba2b892a1d0602cb06eef16d8b7df1dca1 + nokogiri (1.19.4-aarch64-linux-gnu) sha256=1269fb644a6de405057a53dd5c762b1209b43ca7424f839454d3dbc677c31a8f + nokogiri (1.19.4-aarch64-linux-musl) sha256=35c65b9ce72b3bb03207bdbe7067915019dc18c1b9b59139684bd6690fdd01af + nokogiri (1.19.4-arm-linux-gnu) sha256=a301313e38bb065d68239e79734bcd6f56fb6efaacebde29e9abf2a4735340ca + nokogiri (1.19.4-arm-linux-musl) sha256=588923c101bcfa78869734d247d25b598674323e7f22474fc468f6e5647311eb + nokogiri (1.19.4-x86_64-linux-gnu) sha256=379fae440b28915e3f19d752ce2dcf8465ed2b2fbefd2a7ca0dd497bc981a06a + nokogiri (1.19.4-x86_64-linux-musl) sha256=17dfb7c1fa194ae02fbf7c51a7afc8d278045ab3fdacfd86f91d02d7b274470b + ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912 + parallel (2.2.0) sha256=e1059c5fd7b649558a0aec38a769f06a42942bdb40503d005a59c352fe011cd8 + parser (3.3.12.0) sha256=21a6d7f755d5a24dfbdc6e6b772e4e879a52e7631a88bc5a3a134606052c9828 + pg (1.6.3) sha256=1388d0563e13d2758c1089e35e973a3249e955c659592d10e5b77c468f628a99 + pg (1.6.3-aarch64-linux) sha256=0698ad563e02383c27510b76bf7d4cd2de19cd1d16a5013f375dd473e4be72ea + pg (1.6.3-aarch64-linux-musl) sha256=06a75f4ea04b05140146f2a10550b8e0d9f006a79cdaf8b5b130cde40e3ecc2c + pg (1.6.3-x86_64-linux) sha256=5d9e188c8f7a0295d162b7b88a768d8452a899977d44f3274d1946d67920ae8d + pg (1.6.3-x86_64-linux-musl) sha256=9c9c90d98c72f78eb04c0f55e9618fe55d1512128e411035fe229ff427864009 + pp (0.6.4) sha256=dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570 + prettyprint (0.2.0) sha256=2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193 + prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85 + propshaft (1.3.2) sha256=1d56a3e56a92c21bfc29caf07406b5386b00d4c47ddf357cf989a5a234b1389e + public_suffix (7.0.5) sha256=1a8bb08f1bbea19228d3bed6e5ed908d1cb4f7c2726d18bd9cadf60bc676f623 + puma (8.0.2) sha256=c8ed871dfbbe66448ea9ffd46692342d9804d4071522b52b5331b7b6e7b686fb + raabro (1.5.0) sha256=3f998a7bc84f9c84df3ab580634d2e0a5bda4f0841168d56035f529c9877440a + racc (1.8.1) sha256=4a7f6929691dbec8b5209a0b373bc2614882b55fc5d2e447a21aaa691303d62f + rack (3.2.7) sha256=93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7 + rack-proxy (2.0.0) sha256=4f1d435d82afe93bc916d1226df8be307c1b808551f0ecdb56e0b668fd5756e6 + rack-session (2.1.2) sha256=595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8 + rack-test (2.2.0) sha256=005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463 + rackup (2.3.1) sha256=6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868 + rails (8.1.3.1) sha256=ccd11a36bfc171bf9c66d585d14c0ece91c0c9dde840aae60c0118d6f5c9c52a + rails-dom-testing (2.3.0) sha256=8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d + rails-html-sanitizer (1.7.1) sha256=e797a7c9b01e567307e317c576b49ab4168017e63eea4dba9ce3cb587e2f22c2 + railties (8.1.3.1) sha256=2388a232579a00cefea4487de66c8553c3408c1300abdc6cf1799d86ffb04487 + rainbow (3.1.1) sha256=039491aa3a89f42efa1d6dec2fc4e62ede96eb6acd95e52f1ad581182b79bc6a + rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701 + rbs (4.2.0) sha256=51f7b886dcc05bc09e10b901daa6a81829f6adc03101d6ca9ea4aac6103e0674 + rdoc (8.0.0) sha256=03bf8c08a9639658855a0cfd77c0abca8325c227693f7f33f82957811348c469 + regexp_parser (2.12.0) sha256=35a916a1d63190ab5c9009457136ae5f3c0c7512d60291d0d1378ba18ce08ebb + reline (0.7.0) sha256=5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d + rexml (3.4.4) sha256=19e0a2c3425dfbf2d4fc1189747bdb2f849b6c5e74180401b15734bc97b5d142 + rubocop (1.90.0) sha256=9eb4c065b5c5154e4ef554c547972f3905a9eb6b53e657e580b6796b54bf8242 + rubocop-ast (1.50.0) sha256=b9ca88300da0803ee222ad20cdb30494c0a784eed06fdc35d254b06d662788db + rubocop-performance (1.27.0) sha256=eeeb1374d062a368ee1c787b70eb0b0cc4b184cb1f8565f424760946146d61ce + rubocop-rails (2.37.0) sha256=6e1645add5060e0328f8ddda0d820f55697c591394398bf14bb9dccb62f14b7e + rubocop-rails-omakase (1.1.0) sha256=2af73ac8ee5852de2919abbd2618af9c15c19b512c4cfc1f9a5d3b6ef009109d + ruby-progressbar (1.13.0) sha256=80fc9c47a9b640d6834e0dc7b3c94c9df37f08cb072b7761e4a71e22cff29b33 + ruby-vips (2.3.0) sha256=e685ec02c13969912debbd98019e50492e12989282da5f37d05f5471442f5374 + rubyXL (3.4.38) sha256=6b3f46a5ff8ec9903a562604a379a6b79b67cdec73515162b1785bd6092e6ce6 + rubyzip (3.6.0) sha256=268994d44d62282d1cfd99bf10eae48d7267199158ad7ea3e1fee2da9458b695 + securerandom (0.4.1) sha256=cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1 + selenium-webdriver (4.48.0) sha256=0c8376ebc8a0a4879343fe6fe6eccdcea76748611cd25de370b33eded2077a94 + sentry-rails (7.0.0) sha256=6ac6a010e088632e46710ce42db75aa5281a6b52a547efee10568cc2ed80605a + sentry-ruby (7.0.0) sha256=e9616ff521355a983fad404ca575d8bb1f1949a8cac42a7a893dd02156bcdb1a + simplecov (1.2.0) sha256=ea6acd05eece5a41990e2a5171c57d15700d329326c7666c85ee8c6a0dd0977e + solid_cable (4.0.2) sha256=084636a67679ad00d23088b33c84047e614bcf41ee559db24b414d83cdc42d03 + solid_cache (1.0.10) sha256=bc05a2fb3ac78a6f43cbb5946679cf9db67dd30d22939ededc385cb93e120d41 + solid_queue (1.7.0) sha256=6566b70b801d1c317c81bba7bcdd5677c019afac584a30374b4164002ca356d3 + sshkit (1.25.1) sha256=be3f10b9d6eb0b44d5eaba3f7cbe41bc6bb894bce4339688ac20124391455b78 + tailwindcss-rails (4.6.0) sha256=d99512867173d55c5ef8890427682299d8539f550cec1408b3d8667a538bd365 + tailwindcss-ruby (4.3.3) sha256=ee0a64030749862deb501acab4c4aaf5adbee13865746a33299d46d7b5d0952a + tailwindcss-ruby (4.3.3-aarch64-linux-gnu) sha256=c86d6dd3eccc85fe0d792a832b06f2bf3c0a7a83b399308aeb9d8f5725f42a6a + tailwindcss-ruby (4.3.3-aarch64-linux-musl) sha256=72b77ca9edea82383dd09510ab520a122e3cb9f9864ca5b38e27698098d2b899 + tailwindcss-ruby (4.3.3-x86_64-linux-gnu) sha256=2337017ff8b02698480eae1e9637cf01faa0e4824db89d067a13c5a5ee38c9b2 + tailwindcss-ruby (4.3.3-x86_64-linux-musl) sha256=27d478c417bcf73828e5b544744c5bdfd5b5cb54f1a266fc4f185281c32efe6c + thor (1.5.0) sha256=e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73 + thruster (0.1.26) sha256=6e45e807086b29d51404841bd1ad493b67cd95892fd65dc5afcdd32e82e94ce8 + thruster (0.1.26-aarch64-linux) sha256=2171cb34928c0250830008f535c4ab2ee57846cc3f5d3e96c3475f7b3de7a541 + thruster (0.1.26-x86_64-linux) sha256=3117a6ee430663f845a0457699fe9a05232dcc6c396e2cc83504de5a223c60e8 + timeout (0.6.1) sha256=78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb + tsort (0.2.0) sha256=9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f + tzinfo (2.0.6) sha256=8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b + unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42 + unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f + uri (1.1.1) sha256=379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6 + useragent (0.16.11) sha256=700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844 + vite_rails (3.11.1) sha256=61fa4a7c9248fc28f22a05e0760810bf79f645b776c721d888a815c5d21dd338 + vite_ruby (3.10.5) sha256=e9ee92be1cb31c0b6360b02182cfe09d3ac2b7fc278db7870e3f32ae64dde49e + web-console (4.3.0) sha256=e13b71301cdfc2093f155b5aa3a622db80b4672d1f2f713119cc7ec7ac6a6da4 + websocket (1.2.11) sha256=b7e7a74e2410b5e85c25858b26b3322f29161e300935f70a0e0d3c35e0462737 + websocket-driver (0.8.2) sha256=97c556b019bf3410b4961002ac501621e9322d3f8a7bc02161a09301cc4c4146 + websocket-extensions (0.1.5) sha256=1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241 + xpath (3.2.0) sha256=6dfda79d91bb3b949b947ecc5919f042ef2f399b904013eb3ef6d20dd3a4082e + zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5 + +BUNDLED WITH + 4.0.16 diff --git a/Procfile.dev b/Procfile.dev new file mode 100644 index 000000000..e6ad037be --- /dev/null +++ b/Procfile.dev @@ -0,0 +1,3 @@ +web: bin/rails server +css: bin/rails tailwindcss:watch +vite: bin/vite dev diff --git a/README.md b/README.md index 7829f14ff..0c4d670a0 100644 --- a/README.md +++ b/README.md @@ -1,87 +1,374 @@ -# Modern Fullstack Developer Test (Rails 8 / Ruby 4) - -- Check this readme.md -- Create a branch to develop your task -- Push to remote in 1 week (date will be checked from branch creation/assigned date) - -# Requirements: -- Target Stack: **Ruby 4.0+** and **Rails 8.0+** -- Database: PostgreSQL, MySQL, or SQLite (configured for production-ready WAL mode) -- Write robust unit, integration, and system tests using parallel testing features -- Deliver with a working multi-stage Dockerfile utilizing Thruster/Kamal-ready defaults -- Show senior best practices (e.g., proper design patterns, solid architecture, strict linter configuration) - -# Our AI Policy -At Umanni, we value efficiency and the modern developer workflow. **You are allowed to use AI coding assistants (ChatGPT, Claude, Copilot, etc.) during this test.** However, transparency is part of our culture. If you use any LLM to generate, refactor, or structure your code, **you must explicitly state which model you used** in a dedicated section at the top of your submission's README.md. Failing to disclose AI usage while using it will invalidate your submission. - -# The Test -Here we'll try to simulate a "real sprint" that you'll probably be assigned while working as Fullstack at Umanni. - -# The Task -- Create a modern, responsive application to manage users. -- A user must have: - 1. full_name - 2. email - 3. avatar_image (ActiveStorage file upload or remote URL) - 4. role (admin/no-admin) - -# The App -## Admin Use cases -- As an Admin, I must be able to access a User Admin Dashboard. -- As an Admin, I must be able to see on the Dashboard (updated via real-time streams/frontend state): - - Total number of Users - - Total number of Users grouped by Role -- As an Admin, I must be redirected to the User Admin Dashboard after login. -- As an Admin, I must be able to list, create, edit, and delete Users. -- As an Admin, I must be able to toggle the User Role. -- As an Admin, I must be able to import a Spreadsheet (.csv/.xlsx) into the system in order to asynchronously create new Users. -- As an Admin, I must be able to see the live progress/status of the spreadsheet import process. - -## User Use Cases -- As a User, I must be redirected to my Profile after login. -- As a User, I must be able only to see my info, edit, and delete my profile. - -## Visitor Use Cases -- As a Visitor, I can register myself as a normal User. - - - -# The Start. -- Your deadline is 1 week after accepting this test. - -# The Rules (Strict Compliance) -These are mandatory. Failing any of them will invalidate your submission. -- **Documentation**: You must write down a detailed README.md in English explaining how to build, seed, and run your app, including your AI disclosure if applicable. -- **Frontend Stack**: You have two choices for the modern monolithic approach: - - **Option A (Classic Modern):** Hotwire (Turbo 8+ / Stimulus) with smooth, reactive UI states. - - **Option B (Modern SPA Monolith):** **React integrated via Inertia.js** (using Vite or the official Rails 8 asset pipeline integration). -- **Styling**: The Frontend must use a modern CSS framework (Tailwind CSS, Bootstrap, or any utility-first library). Keep it beautiful, responsive, and clean. -- **Real-time & Background Processing**: You must leverage native Rails 8 tools (**Solid Cable** for live dashboard counters/import bars and **Solid Queue** for the background import processing). No Redis installation should be required. -- **Authentication**: You must use the new built-in Rails 8 Authentication system (`bin/rails generate authentication`), customized to fit the role constraints. Avoid legacy heavy gems (like Devise). -- **Git Hygiene**: Clean git history with atomic commits, proper descriptions, and a Pull Request-based workflow. - -# What we're expecting to see: -- Modern asset management using **Propshaft** or **Vite Rails** (if choosing Inertia/React). -- .gitignore, .dockerignore configured correctly. -- Clean application configuration using Rails credentials. -- Comprehensive cross-browser support considerations. -- Strict form validations (Frontend interactive feedback + Backend structural validation). -- Parallel testing with at least 90% coverage (using Minitest, RSpec, and Playwright/Capybara for frontend integration). - -# Extra points -- Delivery via a clean **Kamal 2** deployment configuration (`deploy.yml`). -- Advanced SSR (Server-Side Rendering) setup if using **Inertia.js + React**. -- Use of **Thruster** as a zero-config proxy for asset caching and compression in Docker. -- Advanced performance profiling leveraging Ruby 4's **ZJIT** compilation optimizations. - -# What will be assessed -- Code's Semantics, Cleanness, and Maintainability (Senior-level object-oriented design and clean React/Stimulus component lifecycle). -- Modern Rails 8 idiom usage (e.g., Strict structural params handling, Solid architecture separation). -- Basic Security testing against traditional vectors (SQLi, XSS, XSRF) and proper encryption of sensitive DB columns where applicable. +### AI Usage Disclosure + +Assisted by OpenCode with models: `Muse Spark 1.3`, `DeepSeek v4 Flash`, `MiMo V2.5`, `deepseek-v4.1-flash`. + +# Fullstack Developer — User Management App + +A modern, responsive monolithic SPA for managing users. Admins get a live dashboard with user counts by role, full CRUD over users, role toggling, and asynchronous spreadsheet imports with live progress. Regular users manage only their own profile, and visitors can register as normal users. + +## Stack + +| Layer | Technology | +| --- | --- | +| Language | Ruby 4.0.6 | +| Framework | Rails 8.1.3.1 | +| Database | PostgreSQL | +| Frontend | React 19 + Inertia.js + Vite | +| Styling | Tailwind CSS | +| Real-time | Solid Cable | +| Background jobs | Solid Queue | +| Proxy | Thruster | +| Deployment | Kamal 2 | + +## Build / Seed / Run + +These instructions assume a clean machine with nothing pre-installed. Every tool below is listed with a way to obtain it; if you already have a tool, skip its step. + +### 1. Install Ruby 4.0.6 + +The app requires Ruby 4.0.6 (see `.ruby-version`). Any installation method that gives you a `ruby` executable on your `PATH` works — a version manager is convenient but not required. + +Using a version manager (recommended, e.g. rbenv): + +```sh +# rbenv + ruby-build +git clone https://github.com/rbenv/rbenv.git ~/.rbenv +git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build +echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc +echo 'eval "$(rbenv init -)"' >> ~/.bashrc +exec $SHELL +rbenv install 4.0.6 +rbenv global 4.0.6 +``` + +Using your operating system's package manager (e.g. on Debian/Ubuntu): + +```sh +sudo apt-get update +sudo apt-get install -y ruby-full build-essential libpq-dev libyaml-dev +``` + +Verify Ruby is available: + +```sh +ruby -v # must print ruby 4.0.6 +``` + +### 2. Install Bundler + +Bundler is the Ruby dependency manager. Install it with: + +```sh +gem install bundler +``` + +Verify: + +```sh +bundle -v +``` + +### 3. Install Node.js and npm + +The frontend is built with Vite and requires Node.js (npm ships with it). Install via nvm (recommended) or your system package manager: + +```sh +# nvm +curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash +exec $SHELL +nvm install 22 +nvm use 22 +``` + +Or on Debian/Ubuntu: + +```sh +sudo apt-get install -y nodejs npm +``` + +Verify: + +```sh +node -v # Node 18 or newer +npm -v +``` + +### 4. Install PostgreSQL + +The app uses PostgreSQL as its database. Install it with your system package manager: + +```sh +# Debian/Ubuntu +sudo apt-get install -y postgresql postgresql-client +sudo service postgresql start +``` + +```sh +# macOS (Homebrew) +brew install postgresql@16 +brew services start postgresql@16 +``` + +Verify the server is reachable: + +```sh +psql --version +``` + +If your PostgreSQL instance requires a password for the default user, set the `DATABASE_URL` environment variable so Rails can connect, for example: + +```sh +export DATABASE_URL="postgres://:@localhost:5432/fullstack_developer_development" +``` + +### 5. Install backend and frontend dependencies + +From the project root: + +```sh +bundle install +``` + +```sh +npm ci +``` + +If `bundle install` fails while compiling native extensions, install the system packages listed in step 1 (`build-essential`, `libpq-dev`, `libyaml-dev`) and retry. + +### 6. Create, migrate, and seed the database + +This creates the admin account and sample users: + +```sh +bin/rails db:create db:migrate db:seed +``` + +The setup script is an equivalent shortcut that prepares dependencies and the database without starting the server: + +```sh +bin/setup --skip-server +``` + +Seeded login accounts (all seeded passwords are `Password123` unless changed after seeding): + +- Admin: `admin@example.com / Password123` +- Sample users: `ada@example.com`, `alan@example.com`, `grace@example.com`, `margaret@example.com` (all `Password123`) + +> **Note:** Passwords must be at least 8 characters and include an uppercase letter, a lowercase letter, and a digit. + +Sample import files for exercising the admin spreadsheet import (25 data rows each, distinct datasets): + +- `test/fixtures/files/sample_users.csv` +- `test/fixtures/files/sample_users.xlsx` + +### 7. Run the app in development + +Starts Rails plus the Vite dev server: + +```sh +bin/dev +``` + +Then open http://localhost:3000 in your browser. + +### 8. Run the full quality pipeline + +Runs setup, lint, audits, test build, tests, coverage gate, and profiling: + +```sh +bin/ci +``` + +## Architecture + +This is a monolithic SPA served by Rails, with client pages implemented in React under `app/frontend/pages/` and bridged through Inertia.js with Vite as the asset bundler. Navigation between the admin dashboard, user list, profile, and auth screens is handled as Inertia visits, so the app behaves like a single-page application while all routing and authorization stay server-side in Rails controllers. + +Live updates use Solid Cable with no Redis dependency. The admin dashboard subscribes to `DashboardChannel` for total user counts and per-role breakdowns, which refresh as users are created, updated, deleted, or have their role toggled. Spreadsheet imports stream progress over `UserImportChannel`, so the admin sees each import move from pending through processing to completed or failed without polling. + +Spreadsheet processing runs in the background with Solid Queue. Uploading a CSV or XLSX file enqueues a `UserImportJob` that parses rows (CSV through the Ruby standard library, XLSX through rubyXL), creates users for valid rows, and records per-row failures for invalid ones. The admin import history shows status and row-level error detail for every run. + +Authentication uses the built-in Rails 8 authentication generator, extended with role-based redirects: admins land on `/admin` after login and regular users land on `/profile`. Authorization is enforced server-side so regular users can only view, edit, and delete their own profile, while every admin-only route is rejected for non-admins. All controllers use strict `params.expect` for structural parameter validation, and forms pair client-side interactive feedback with backend model validations. + +Sessions expire after 30 days of inactivity. The `Session` model tracks `last_active_at`, which is touched on every authenticated request. Expired sessions are automatically destroyed on the next request, and a background job (`ExpireSessionsJob`) runs daily to clean up stale records. + +Password complexity is enforced: minimum 8 characters with at least one uppercase letter, one lowercase letter, and one digit. Import jobs auto-generate compliant passwords when the provided value is weak or blank. + +Admin actions (user creation, deletion, role toggling, import creation) are logged to an `audit_logs` table with the acting user, target record, metadata, IP address, and user agent. The audit trail persists even after the target user is deleted (foreign key uses `ON DELETE SET NULL`). + +User and import lists are paginated (25 per page) via Kaminari, with prev/next navigation in the frontend. + +## Testing + +The full pipeline entry point is `bin/ci`, which runs environment setup, RuboCop, bundler-audit, Brakeman, a Vite production test build, the Minitest suite, a seed replant check, the ZJIT profiling script, and the SimpleCov coverage gate. + +The Minitest suite runs in parallel with `bin/rails test` (114 runs) and covers models, controllers, jobs, channels, mailers, and integration flows, including admin CRUD, role toggling, CSV and XLSX imports with failed-row reporting, authentication redirects, and authorization boundaries. Coverage is enforced with a SimpleCov minimum of 90, and the suite currently reports 92%+. + +System tests live in `test/system/` and run under Capybara with headless Chrome via Selenium, exercising login, registration, profile editing, and the admin dashboard from a real browser. Performance profiling uses `benchmark/zjit_profile.rb` to compare warm runs with Ruby 4 ZJIT enabled against the baseline interpreter. + +## Run with Docker + +The simplest way to run the whole app is Docker — no Ruby, Node, or PostgreSQL installation needed. The `compose.yml` at the project root builds the app image and starts it together with a PostgreSQL database. + +Prerequisite: Docker with Compose (`docker compose version`). + +```sh +export RAILS_MASTER_KEY="$(cat config/master.key)" +export SECRET_KEY_BASE="$(openssl rand -hex 64)" +docker compose up --build +``` + +Then open **http://localhost:3000** in your browser. + +That's it. The first run builds the image (takes a few minutes); later runs are fast. The app runs in production mode behind the Thruster proxy, exactly like the deployed version. + +Stop the app: + +```sh +docker compose down +``` + +To wipe the database and start fresh: + +```sh +docker compose down -v +``` + +Notes: + +- `RAILS_MASTER_KEY` is the contents of `config/master.key`. +- `SECRET_KEY_BASE` is required because the image runs in production mode and the repository's credentials file does not ship a production `secret_key_base`. Generate one with `openssl rand -hex 64`. +- The four `*_DATABASE_URL` variables are already set in `compose.yml`; they exist because the production configuration uses separate databases for Solid Cache, Solid Queue, and Solid Cable. Rails creates them automatically on first boot. +- Prefer running without Docker? Follow the "Build / Seed / Run" section above and use `bin/dev` — the app also runs on http://localhost:3000. + +### Run the quality pipeline (`bin/ci`) with Docker + +The full quality pipeline (lint, security audits, tests, coverage gate, profiling) runs inside the app container against the compose database. With the app stack running: + +```sh +docker compose run --rm \ + -v "$(pwd)/config/master.key:/rails/config/master.key" \ + web sh -c 'RAILS_ENV=test DATABASE_URL=postgres://fullstack_developer:fullstack_developer@db:5432/fullstack_developer_test bundle exec bin/ci' +``` + +What this does: + +- `docker compose run` starts a one-off `web` container on the compose network, so it can reach the `db` service. +- The `-v` mount makes `config/master.key` available inside the container — `bin/ci` reads it directly and the file is not baked into the image. +- `RAILS_ENV=test` and `DATABASE_URL` point the suite at a test database on the compose Postgres; Rails creates it automatically on the first run. +- `bundle exec bin/ci` runs the same pipeline as on the host: setup, RuboCop, bundler-audit, Brakeman, Vite test build, the Minitest suite, seed replant, ZJIT profiling, and the SimpleCov gate. + +The container is removed when the run finishes (`--rm`). The app stack itself is unaffected. + +### Run commands inside the app container + +With the app stack running (`docker compose up --build`), run any Rails or Ruby command inside the `web` container with `docker compose exec`. The running container already has the environment configured, so no extra flags are needed: + +```sh +docker compose exec web bin/rails console +``` + +```sh +docker compose exec web bin/rails runner 'puts User.count' +``` + +```sh +docker compose exec web bin/rails routes +``` + +```sh +docker compose exec web bin/rubocop +``` + +```sh +docker compose exec web bin/rails db:migrate +``` + +Notes: + +- `docker compose exec` runs in the already-running `web` container; `docker compose run` (used for `bin/ci` above) starts a separate one-off container instead. +- For interactive commands like `rails console`, use `docker compose exec` without `-T`. For piping input (e.g. `echo 'puts User.count' | docker compose exec -T web bin/rails console`), add `-T`. +- If you started the stack without exporting `RAILS_MASTER_KEY` and `SECRET_KEY_BASE` first, the container will have blank values; restart with the exports from the "Run with Docker" section. + +### How Kamal relates to local development + +Kamal 2 (`config/deploy.yml`) is the production deployment tool — it builds the same Dockerfile, pushes the image to a registry, and rolls it out to remote servers over SSH. Locally, you are not running Kamal; you are using Docker directly. The relationship: + +- **Same image**: `docker compose up --build` and `bin/kamal deploy` both build from the same `Dockerfile`, so what you validate locally is what ships. +- **Same proxy**: the image's `CMD` runs `bin/thrust` (Thruster) in both local and Kamal runs. +- **Same database shape**: the compose `db` service mirrors the Postgres 16 accessory defined under `accessories:` in `config/deploy.yml`. +- **Different secrets handling**: locally you pass `RAILS_MASTER_KEY` and `SECRET_KEY_BASE` as environment variables; Kamal injects them from `.kamal/secrets` via `bin/kamal secret set`. + +Deployment is configured with Kamal 2 in `config/deploy.yml`. The image is published to `ghcr.io` (`ghcr.io/umanni/fullstack-developer:latest`), traffic terminates through an SSL proxy for the app host, and the stack defines a single `web` role (Puma running the Solid Queue supervisor in-process) plus a Postgres 16 accessory for production data. + +### Prerequisites + +- **Docker** installed and running on your machine (Kamal builds the image locally). Verify with `docker --version`. +- **SSH access** to the production server(s) from your machine (Kamal deploys over SSH). Verify with `ssh @`. +- **A container registry account** with push access to `ghcr.io` (or whichever registry you set in `config/deploy.yml`). Authenticate Docker to it: + +```sh +docker login ghcr.io +``` + +- **Kamal** — it is a gem in this project's bundle, so no separate install is needed. Verify it is available: + +```sh +bin/kamal version +``` + +### Configure the deployment + +1. **Set the real server addresses.** Open `config/deploy.yml` and replace the placeholder values with your production infrastructure: + - `DEPLOY_WEB_HOST` (default `192.168.0.1`) — the server that runs the web app and background jobs. + - `DEPLOY_DB_HOST` (default `192.168.0.2`) — the server that runs the Postgres accessory. + - `proxy.host` (`fullstack-developer.umanni.dev`) — the public hostname that will serve the app over HTTPS. + +2. **Set the registry credentials.** In `config/deploy.yml`, uncomment and fill in `registry.username` and `registry.password` (or point `registry.password` at a `KAMAL_REGISTRY_PASSWORD` secret). Use a personal access token rather than your account password when possible. + +3. **Set the deploy secrets.** Kamal reads secrets from `.kamal/secrets` and injects them into the containers. Set the required values: + +```sh +bin/kamal secret set RAILS_MASTER_KEY= DB_PASSWORD= +``` + + - `RAILS_MASTER_KEY` is the contents of `config/master.key` (or the production master key for your environment). + - `DB_PASSWORD` is the password the Postgres accessory will use. + +### Deploy + +From the project root, with Docker running and SSH access in place: + +```sh +bin/kamal setup +``` + +`setup` provisions the server (installs Docker on it if needed), starts the Postgres accessory, and boots the app for the first time. On subsequent releases: + +```sh +bin/kamal deploy +``` + +`deploy` builds the image, pushes it to the registry, and rolls it out to the servers. + +### Post-deploy commands + +Useful commands (defined as aliases in `config/deploy.yml`): + +```sh +bin/kamal console +``` + +```sh +bin/kamal logs +``` + +### Troubleshooting + +- **`registry/username is required`** — you skipped step 2; fill in the registry credentials in `config/deploy.yml`. +- **SSH connection refused** — confirm the server address in `config/deploy.yml` and that your SSH key is authorized on the server. +- **Container exits immediately** — check the logs with `bin/kamal logs`; the most common cause is a missing or wrong `RAILS_MASTER_KEY`. + +## Known limitations + +- Production SSR Node rendering is configured but unproven end-to-end against a live production deploy. +- Deploy hosts in `config/deploy.yml` are operator-supplied placeholder addresses that must be replaced with real infrastructure values. diff --git a/Rakefile b/Rakefile new file mode 100644 index 000000000..9a5ea7383 --- /dev/null +++ b/Rakefile @@ -0,0 +1,6 @@ +# Add your own tasks in files placed in lib/tasks ending in .rake, +# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake. + +require_relative "config/application" + +Rails.application.load_tasks diff --git a/app/assets/builds/.keep b/app/assets/builds/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/builds/tailwind.css b/app/assets/builds/tailwind.css new file mode 100644 index 000000000..6f45ad41e --- /dev/null +++ b/app/assets/builds/tailwind.css @@ -0,0 +1,2 @@ +/*! tailwindcss v4.3.3 | MIT License | https://tailwindcss.com */ +@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-space-y-reverse:0;--tw-divide-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-amber-50:oklch(98.7% .022 95.277);--color-amber-100:oklch(96.2% .059 95.617);--color-amber-700:oklch(55.5% .163 48.998);--color-emerald-50:oklch(97.9% .021 166.113);--color-emerald-100:oklch(95% .052 163.051);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-800:oklch(43.2% .095 166.913);--color-emerald-900:oklch(37.8% .077 168.94);--color-teal-50:oklch(98.4% .014 180.72);--color-blue-50:oklch(97% .014 254.604);--color-blue-100:oklch(93.2% .032 255.585);--color-blue-200:oklch(88.2% .059 254.128);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-blue-900:oklch(37.9% .146 265.522);--color-indigo-50:oklch(96.2% .018 272.314);--color-indigo-100:oklch(93% .034 272.788);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-violet-50:oklch(96.9% .016 293.756);--color-violet-100:oklch(94.3% .029 294.588);--color-violet-500:oklch(60.6% .25 292.717);--color-violet-600:oklch(54.1% .281 293.009);--color-violet-700:oklch(49.1% .27 292.581);--color-violet-900:oklch(38% .189 293.745);--color-fuchsia-50:oklch(97.7% .017 320.058);--color-fuchsia-500:oklch(66.7% .295 322.15);--color-fuchsia-600:oklch(59.1% .293 322.896);--color-fuchsia-700:oklch(51.8% .253 323.949);--color-rose-50:oklch(96.9% .015 12.422);--color-rose-100:oklch(94.1% .03 12.58);--color-rose-200:oklch(89.2% .058 10.001);--color-rose-600:oklch(58.6% .253 17.585);--color-rose-700:oklch(51.4% .222 16.935);--color-rose-800:oklch(45.5% .188 13.697);--color-rose-900:oklch(41% .159 10.272);--color-slate-50:oklch(98.4% .003 247.858);--color-slate-100:oklch(96.8% .007 247.896);--color-slate-200:oklch(92.9% .013 255.508);--color-slate-300:oklch(86.9% .022 252.894);--color-slate-400:oklch(70.4% .04 256.788);--color-slate-500:oklch(55.4% .046 257.417);--color-slate-600:oklch(44.6% .043 257.281);--color-slate-700:oklch(37.2% .044 257.287);--color-slate-800:oklch(27.9% .041 260.031);--color-slate-900:oklch(20.8% .042 265.755);--color-white:#fff;--spacing:.25rem;--container-md:28rem;--container-xl:36rem;--container-2xl:42rem;--container-4xl:56rem;--container-5xl:64rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-xl:1.25rem;--text-xl--line-height:calc(1.75 / 1.25);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height:calc(2.25 / 1.875);--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--text-5xl:3rem;--text-5xl--line-height:1;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--font-weight-extrabold:800;--tracking-tight:-.025em;--tracking-wider:.05em;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--radius-3xl:1.5rem;--blur-md:12px;--blur-xl:24px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab, red, red)){::placeholder{color:color-mix(in oklab, currentcolor 50%, transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}button:not(:disabled),[role=button]:not([aria-disabled=true]){cursor:pointer}}@layer components;@layer utilities{.static{position:static}.sticky{position:sticky}.top-0{top:0}.z-50{z-index:50}.container{width:100%}@media (min-width:40rem){.container{max-width:40rem}}@media (min-width:48rem){.container{max-width:48rem}}@media (min-width:64rem){.container{max-width:64rem}}@media (min-width:80rem){.container{max-width:80rem}}@media (min-width:96rem){.container{max-width:96rem}}.m-0{margin:0}.mx-2{margin-inline:calc(var(--spacing) * 2)}.mx-auto{margin-inline:auto}.my-2{margin-block:calc(var(--spacing) * 2)}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-4{margin-top:calc(var(--spacing) * 4)}.mt-6{margin-top:calc(var(--spacing) * 6)}.mt-8{margin-top:calc(var(--spacing) * 8)}.mb-1{margin-bottom:var(--spacing)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-8{margin-bottom:calc(var(--spacing) * 8)}.ml-2{margin-left:calc(var(--spacing) * 2)}.block{display:block}.contents{display:contents}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline{display:inline}.inline-block{display:inline-block}.table{display:table}.h-4{height:calc(var(--spacing) * 4)}.h-24{height:calc(var(--spacing) * 24)}.h-full{height:100%}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing) * 4)}.w-24{width:calc(var(--spacing) * 24)}.w-full{width:100%}.max-w-2xl{max-width:var(--container-2xl)}.max-w-4xl{max-width:var(--container-4xl)}.max-w-5xl{max-width:var(--container-5xl)}.max-w-\[240px\]{max-width:240px}.max-w-md{max-width:var(--container-md)}.max-w-xl{max-width:var(--container-xl)}.min-w-\[560px\]{min-width:560px}.min-w-\[640px\]{min-width:640px}.shrink-0{flex-shrink:0}.cursor-not-allowed{cursor:not-allowed}.list-inside{list-style-position:inside}.list-disc{list-style-type:disc}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.items-center{align-items:center}.items-start{align-items:flex-start}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:var(--spacing)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-6{gap:calc(var(--spacing) * 6)}:where(.space-y-0\.5>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * .5) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * .5) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}:where(.divide-y>:not(:last-child)){--tw-divide-y-reverse:0;border-bottom-style:var(--tw-border-style);border-top-style:var(--tw-border-style);border-top-width:calc(1px * var(--tw-divide-y-reverse));border-bottom-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)))}:where(.divide-slate-100>:not(:last-child)){border-color:var(--color-slate-100)}.truncate{text-overflow:ellipsis;white-space:nowrap;overflow:hidden}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-3xl{border-radius:var(--radius-3xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-b{border-bottom-style:var(--tw-border-style);border-bottom-width:1px}.border-amber-100{border-color:var(--color-amber-100)}.border-blue-100{border-color:var(--color-blue-100)}.border-emerald-100{border-color:var(--color-emerald-100)}.border-rose-100{border-color:var(--color-rose-100)}.border-rose-200{border-color:var(--color-rose-200)}.border-slate-100{border-color:var(--color-slate-100)}.border-slate-200{border-color:var(--color-slate-200)}.border-slate-200\/60{border-color:#e2e8f099}@supports (color:color-mix(in lab, red, red)){.border-slate-200\/60{border-color:color-mix(in oklab, var(--color-slate-200) 60%, transparent)}}.border-slate-300{border-color:var(--color-slate-300)}.border-violet-100{border-color:var(--color-violet-100)}.border-white\/40{border-color:#fff6}@supports (color:color-mix(in lab, red, red)){.border-white\/40{border-color:color-mix(in oklab, var(--color-white) 40%, transparent)}}.bg-amber-50{background-color:var(--color-amber-50)}.bg-blue-50{background-color:var(--color-blue-50)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-emerald-50{background-color:var(--color-emerald-50)}.bg-rose-50{background-color:var(--color-rose-50)}.bg-rose-600{background-color:var(--color-rose-600)}.bg-slate-50{background-color:var(--color-slate-50)}.bg-slate-200{background-color:var(--color-slate-200)}.bg-slate-900{background-color:var(--color-slate-900)}.bg-white\/60{background-color:#fff9}@supports (color:color-mix(in lab, red, red)){.bg-white\/60{background-color:color-mix(in oklab, var(--color-white) 60%, transparent)}}.bg-white\/70{background-color:#ffffffb3}@supports (color:color-mix(in lab, red, red)){.bg-white\/70{background-color:color-mix(in oklab, var(--color-white) 70%, transparent)}}.bg-white\/80{background-color:#fffc}@supports (color:color-mix(in lab, red, red)){.bg-white\/80{background-color:color-mix(in oklab, var(--color-white) 80%, transparent)}}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.bg-gradient-to-r{--tw-gradient-position:to right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-50{--tw-gradient-from:var(--color-blue-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-100{--tw-gradient-from:var(--color-blue-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-600{--tw-gradient-from:var(--color-blue-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-emerald-50{--tw-gradient-from:var(--color-emerald-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-slate-50{--tw-gradient-from:var(--color-slate-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-violet-50{--tw-gradient-from:var(--color-violet-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-violet-500{--tw-gradient-from:var(--color-violet-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-violet-600{--tw-gradient-from:var(--color-violet-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.via-white{--tw-gradient-via:var(--color-white);--tw-gradient-via-stops:var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position);--tw-gradient-stops:var(--tw-gradient-via-stops)}.to-blue-50{--tw-gradient-to:var(--color-blue-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-fuchsia-50{--tw-gradient-to:var(--color-fuchsia-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-fuchsia-500{--tw-gradient-to:var(--color-fuchsia-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-fuchsia-600{--tw-gradient-to:var(--color-fuchsia-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-indigo-50{--tw-gradient-to:var(--color-indigo-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-indigo-100{--tw-gradient-to:var(--color-indigo-100);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-indigo-600{--tw-gradient-to:var(--color-indigo-600);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-teal-50{--tw-gradient-to:var(--color-teal-50);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.object-cover{object-fit:cover}.p-0{padding:0}.p-4{padding:calc(var(--spacing) * 4)}.p-6{padding:calc(var(--spacing) * 6)}.p-8{padding:calc(var(--spacing) * 8)}.px-2\.5{padding-inline:calc(var(--spacing) * 2.5)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-3\.5{padding-inline:calc(var(--spacing) * 3.5)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-5{padding-inline:calc(var(--spacing) * 5)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-2\.5{padding-block:calc(var(--spacing) * 2.5)}.py-3{padding-block:calc(var(--spacing) * 3)}.py-4{padding-block:calc(var(--spacing) * 4)}.py-8{padding-block:calc(var(--spacing) * 8)}.text-center{text-align:center}.text-left{text-align:left}.font-sans{font-family:var(--font-sans)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-5xl{font-size:var(--text-5xl);line-height:var(--tw-leading,var(--text-5xl--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xl{font-size:var(--text-xl);line-height:var(--tw-leading,var(--text-xl--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-extrabold{--tw-font-weight:var(--font-weight-extrabold);font-weight:var(--font-weight-extrabold)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-tight{--tw-tracking:var(--tracking-tight);letter-spacing:var(--tracking-tight)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.whitespace-nowrap{white-space:nowrap}.text-amber-700{color:var(--color-amber-700)}.text-blue-600{color:var(--color-blue-600)}.text-blue-700{color:var(--color-blue-700)}.text-emerald-600{color:var(--color-emerald-600)}.text-emerald-700{color:var(--color-emerald-700)}.text-emerald-800{color:var(--color-emerald-800)}.text-rose-600{color:var(--color-rose-600)}.text-rose-700{color:var(--color-rose-700)}.text-rose-800{color:var(--color-rose-800)}.text-slate-400{color:var(--color-slate-400)}.text-slate-500{color:var(--color-slate-500)}.text-slate-600{color:var(--color-slate-600)}.text-slate-700{color:var(--color-slate-700)}.text-slate-800{color:var(--color-slate-800)}.text-slate-900{color:var(--color-slate-900)}.text-violet-600{color:var(--color-violet-600)}.text-violet-700{color:var(--color-violet-700)}.text-white{color:var(--color-white)}.capitalize{text-transform:capitalize}.lowercase{text-transform:lowercase}.uppercase{text-transform:uppercase}.underline{text-decoration-line:underline}.shadow-lg{--tw-shadow:0 10px 15px -3px var(--tw-shadow-color,#0000001a), 0 4px 6px -4px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-md{--tw-shadow:0 4px 6px -1px var(--tw-shadow-color,#0000001a), 0 2px 4px -2px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-sm{--tw-shadow:0 1px 3px 0 var(--tw-shadow-color,#0000001a), 0 1px 2px -1px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.ring-4{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.shadow-blue-600\/20{--tw-shadow-color:#155dfc33}@supports (color:color-mix(in lab, red, red)){.shadow-blue-600\/20{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-blue-600) 20%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-blue-900\/5{--tw-shadow-color:#1c398e0d}@supports (color:color-mix(in lab, red, red)){.shadow-blue-900\/5{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-blue-900) 5%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-emerald-900\/5{--tw-shadow-color:#004e3b0d}@supports (color:color-mix(in lab, red, red)){.shadow-emerald-900\/5{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-emerald-900) 5%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-rose-600\/10{--tw-shadow-color:#e700441a}@supports (color:color-mix(in lab, red, red)){.shadow-rose-600\/10{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-rose-600) 10%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-rose-600\/20{--tw-shadow-color:#e7004433}@supports (color:color-mix(in lab, red, red)){.shadow-rose-600\/20{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-rose-600) 20%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-rose-900\/5{--tw-shadow-color:#8b08360d}@supports (color:color-mix(in lab, red, red)){.shadow-rose-900\/5{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-rose-900) 5%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-slate-200{--tw-shadow-color:oklch(92.9% .013 255.508)}@supports (color:color-mix(in lab, red, red)){.shadow-slate-200{--tw-shadow-color:color-mix(in oklab, var(--color-slate-200) var(--tw-shadow-alpha), transparent)}}.shadow-slate-200\/40{--tw-shadow-color:#e2e8f066}@supports (color:color-mix(in lab, red, red)){.shadow-slate-200\/40{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-slate-200) 40%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-slate-200\/50{--tw-shadow-color:#e2e8f080}@supports (color:color-mix(in lab, red, red)){.shadow-slate-200\/50{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-slate-200) 50%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-slate-900\/10{--tw-shadow-color:#0f172b1a}@supports (color:color-mix(in lab, red, red)){.shadow-slate-900\/10{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-slate-900) 10%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-violet-600\/20{--tw-shadow-color:#7f22fe33}@supports (color:color-mix(in lab, red, red)){.shadow-violet-600\/20{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-violet-600) 20%, transparent) var(--tw-shadow-alpha), transparent)}}.shadow-violet-900\/5{--tw-shadow-color:#4d179a0d}@supports (color:color-mix(in lab, red, red)){.shadow-violet-900\/5{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-violet-900) 5%, transparent) var(--tw-shadow-alpha), transparent)}}.ring-white{--tw-ring-color:var(--color-white)}.backdrop-blur-md{--tw-backdrop-blur:blur(var(--blur-md));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.backdrop-blur-xl{--tw-backdrop-blur:blur(var(--blur-xl));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-500{--tw-duration:.5s;transition-duration:.5s}.selection\:bg-blue-200 ::selection{background-color:var(--color-blue-200)}.selection\:bg-blue-200::selection{background-color:var(--color-blue-200)}.selection\:text-blue-900 ::selection{color:var(--color-blue-900)}.selection\:text-blue-900::selection{color:var(--color-blue-900)}.file\:mr-4::file-selector-button{margin-right:calc(var(--spacing) * 4)}.file\:rounded-full::file-selector-button{border-radius:3.40282e38px}.file\:border-0::file-selector-button{border-style:var(--tw-border-style);border-width:0}.file\:bg-blue-50::file-selector-button{background-color:var(--color-blue-50)}.file\:px-4::file-selector-button{padding-inline:calc(var(--spacing) * 4)}.file\:py-2::file-selector-button{padding-block:calc(var(--spacing) * 2)}.file\:text-sm::file-selector-button{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.file\:font-medium::file-selector-button{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.file\:text-blue-700::file-selector-button{color:var(--color-blue-700)}@media (hover:hover){.hover\:bg-blue-50:hover{background-color:var(--color-blue-50)}.hover\:bg-rose-700:hover{background-color:var(--color-rose-700)}.hover\:bg-slate-50\/60:hover{background-color:#f8fafc99}@supports (color:color-mix(in lab, red, red)){.hover\:bg-slate-50\/60:hover{background-color:color-mix(in oklab, var(--color-slate-50) 60%, transparent)}}.hover\:bg-slate-100:hover{background-color:var(--color-slate-100)}.hover\:bg-slate-300:hover{background-color:var(--color-slate-300)}.hover\:bg-slate-800:hover{background-color:var(--color-slate-800)}.hover\:from-blue-700:hover{--tw-gradient-from:var(--color-blue-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.hover\:from-violet-700:hover{--tw-gradient-from:var(--color-violet-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.hover\:to-fuchsia-700:hover{--tw-gradient-to:var(--color-fuchsia-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.hover\:to-indigo-700:hover{--tw-gradient-to:var(--color-indigo-700);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.hover\:text-blue-700:hover{color:var(--color-blue-700)}.hover\:text-blue-900:hover{color:var(--color-blue-900)}.hover\:text-emerald-900:hover{color:var(--color-emerald-900)}.hover\:text-rose-800:hover{color:var(--color-rose-800)}.hover\:text-violet-900:hover{color:var(--color-violet-900)}.hover\:shadow-blue-600\/40:hover{--tw-shadow-color:#155dfc66}@supports (color:color-mix(in lab, red, red)){.hover\:shadow-blue-600\/40:hover{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-blue-600) 40%, transparent) var(--tw-shadow-alpha), transparent)}}.hover\:shadow-rose-600\/40:hover{--tw-shadow-color:#e7004466}@supports (color:color-mix(in lab, red, red)){.hover\:shadow-rose-600\/40:hover{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-rose-600) 40%, transparent) var(--tw-shadow-alpha), transparent)}}.hover\:shadow-violet-600\/40:hover{--tw-shadow-color:#7f22fe66}@supports (color:color-mix(in lab, red, red)){.hover\:shadow-violet-600\/40:hover{--tw-shadow-color:color-mix(in oklab, color-mix(in oklab, var(--color-violet-600) 40%, transparent) var(--tw-shadow-alpha), transparent)}}.hover\:file\:bg-blue-100:hover::file-selector-button{background-color:var(--color-blue-100)}}.focus\:border-blue-500:focus{border-color:var(--color-blue-500)}.focus\:ring-2:focus{--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow), var(--tw-inset-ring-shadow), var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow)}.focus\:ring-blue-500\/20:focus{--tw-ring-color:#3080ff33}@supports (color:color-mix(in lab, red, red)){.focus\:ring-blue-500\/20:focus{--tw-ring-color:color-mix(in oklab, var(--color-blue-500) 20%, transparent)}}.focus\:outline-none:focus{--tw-outline-style:none;outline-style:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-50:disabled{opacity:.5}@media (min-width:40rem){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media (min-width:48rem){.md\:w-2\/3{width:66.6667%}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:p-12{padding:calc(var(--spacing) * 12)}}}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-divide-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false} \ No newline at end of file diff --git a/app/assets/images/.keep b/app/assets/images/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/assets/stylesheets/application.css b/app/assets/stylesheets/application.css new file mode 100644 index 000000000..fe93333c0 --- /dev/null +++ b/app/assets/stylesheets/application.css @@ -0,0 +1,10 @@ +/* + * This is a manifest file that'll be compiled into application.css. + * + * With Propshaft, assets are served efficiently without preprocessing steps. You can still include + * application-wide styles in this file, but keep in mind that CSS precedence will follow the standard + * cascading order, meaning styles declared later in the document or manifest will override earlier ones, + * depending on specificity. + * + * Consider organizing styles into separate files for maintainability. + */ diff --git a/app/assets/tailwind/application.css b/app/assets/tailwind/application.css new file mode 100644 index 000000000..4c02e1a59 --- /dev/null +++ b/app/assets/tailwind/application.css @@ -0,0 +1,8 @@ +@import "tailwindcss"; + +@layer base { + button:not(:disabled), + [role="button"]:not([aria-disabled="true"]) { + cursor: pointer; + } +} diff --git a/app/channels/application_cable/channel.rb b/app/channels/application_cable/channel.rb new file mode 100644 index 000000000..d67269728 --- /dev/null +++ b/app/channels/application_cable/channel.rb @@ -0,0 +1,4 @@ +module ApplicationCable + class Channel < ActionCable::Channel::Base + end +end diff --git a/app/channels/application_cable/connection.rb b/app/channels/application_cable/connection.rb new file mode 100644 index 000000000..4264c745c --- /dev/null +++ b/app/channels/application_cable/connection.rb @@ -0,0 +1,16 @@ +module ApplicationCable + class Connection < ActionCable::Connection::Base + identified_by :current_user + + def connect + set_current_user || reject_unauthorized_connection + end + + private + def set_current_user + if session = Session.find_by(id: cookies.signed[:session_id]) + self.current_user = session.user + end + end + end +end diff --git a/app/channels/dashboard_channel.rb b/app/channels/dashboard_channel.rb new file mode 100644 index 000000000..2c31507e1 --- /dev/null +++ b/app/channels/dashboard_channel.rb @@ -0,0 +1,6 @@ +class DashboardChannel < ApplicationCable::Channel + def subscribed + reject unless current_user&.admin? + stream_from "dashboard" + end +end diff --git a/app/channels/user_import_channel.rb b/app/channels/user_import_channel.rb new file mode 100644 index 000000000..9dde526c2 --- /dev/null +++ b/app/channels/user_import_channel.rb @@ -0,0 +1,10 @@ +class UserImportChannel < ApplicationCable::Channel + def subscribed + return reject unless current_user&.admin? + + import = UserImport.find_by(id: params[:id]) + return reject unless import + + stream_for import + end +end diff --git a/app/controllers/admin/base_controller.rb b/app/controllers/admin/base_controller.rb new file mode 100644 index 000000000..a8c07acc2 --- /dev/null +++ b/app/controllers/admin/base_controller.rb @@ -0,0 +1,12 @@ +module Admin + class BaseController < ApplicationController + before_action :require_admin + + private + def require_admin + unless Current.user&.admin? + redirect_to root_path, alert: "Not authorized." + end + end + end +end diff --git a/app/controllers/admin/dashboard_controller.rb b/app/controllers/admin/dashboard_controller.rb new file mode 100644 index 000000000..68752eeb2 --- /dev/null +++ b/app/controllers/admin/dashboard_controller.rb @@ -0,0 +1,10 @@ +module Admin + class DashboardController < BaseController + def show + render inertia: "Admin/Dashboard/Show", props: { + total_users: User.count, + users_by_role: User.group(:role).count + } + end + end +end diff --git a/app/controllers/admin/user_imports_controller.rb b/app/controllers/admin/user_imports_controller.rb new file mode 100644 index 000000000..b29fe26a9 --- /dev/null +++ b/app/controllers/admin/user_imports_controller.rb @@ -0,0 +1,48 @@ +module Admin + class UserImportsController < BaseController + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to admin_user_imports_path, alert: "Try again later." } + + def index + imports = UserImport.order(created_at: :desc).page(params[:page]).per(25) + render inertia: "Admin/Imports/Index", props: { + imports: imports.map { |imp| + imp.as_json(only: [ :id, :status, :total_rows, :processed_rows, :failed_rows ]).merge( + file_name: imp.file.attached? ? imp.file.filename.to_s : nil + ) + }, + pagination: { + current_page: imports.current_page, + total_pages: imports.total_pages, + total_count: imports.total_count + } + } + end + + def new + @import = UserImport.new + render inertia: "Admin/Imports/New" + end + + def create + @import = UserImport.new + @import.file.attach(params.expect(user_import: [ :file ])[:file]) + if @import.file.attached? && @import.save + AuditLog.log!(action: "import_created", user: Current.user, auditable: @import, metadata: { file_name: @import.file.filename.to_s }, request: request) + UserImportJob.perform_later(@import) + redirect_to admin_user_import_path(@import), notice: "Import started." + else + render inertia: "Admin/Imports/New", status: :unprocessable_entity + end + end + + def show + @import = UserImport.find(params[:id]) + render inertia: "Admin/Imports/Show", props: { + import: @import.as_json(only: [ :id, :status, :total_rows, :processed_rows, :failed_rows, :row_errors ]).merge( + progress_percent: @import.progress_percent, + errors_truncated: @import.row_errors.size >= 100 + ) + } + end + end +end diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb new file mode 100644 index 000000000..f2ca055b5 --- /dev/null +++ b/app/controllers/admin/users_controller.rb @@ -0,0 +1,118 @@ +module Admin + class UsersController < BaseController + before_action :set_user, only: %i[ show edit update destroy toggle_role remove_avatar ] + + def index + users = User.with_attached_avatar_image.order(:full_name).page(params[:page]).per(25) + render inertia: "Admin/Users/Index", props: { + users: users.map { |u| + u.as_json(only: [ :id, :full_name, :email, :role ]).merge( + avatar_url: u.avatar_url, + avatar_image_url: (url_for(u.avatar_image) if u.avatar_image.attached?), + has_avatar: (u.avatar_image.attached? || u.avatar_url.present?) + ) + }, + admin_count: User.admin.count, + pagination: { + current_page: users.current_page, + total_pages: users.total_pages, + total_count: users.total_count + } + } + end + + def show + render inertia: "Admin/Users/Show", props: { user: user_json(@user) } + end + + def new + @user = User.new + render inertia: "Admin/Users/New" + end + + def create + @user = User.new(user_params) + if @user.save + AuditLog.log!(action: "user_created", user: Current.user, auditable: @user, request: request) + redirect_to admin_users_path, notice: "User created." + else + render inertia: "Admin/Users/New", status: :unprocessable_entity + end + end + + def edit + render inertia: "Admin/Users/Edit", props: { user: user_json(@user) } + end + + def update + if @user.update(user_params_without_stale_avatar) + # An explicit URL wins over a stored upload; drop the now-unused file + # only after the record is safely persisted. + @user.avatar_image.purge if replacing_attachment_with_url? + redirect_to admin_users_path, notice: "User updated." + else + render inertia: "Admin/Users/Edit", props: { user: user_json(@user) }, status: :unprocessable_entity + end + end + + def destroy + if @user.admin? && User.admin.count == 1 + redirect_to admin_users_path, status: :see_other, alert: "Cannot delete the only admin on the system." + return + end + AuditLog.log!(action: "user_destroyed", user: Current.user, auditable: @user, metadata: { email: @user.email }, request: request) + @user.destroy + redirect_to admin_users_path, status: :see_other, notice: "User deleted." + end + + def toggle_role + new_role = @user.admin? ? :user : :admin + if new_role == :user && User.admin.count <= 1 + redirect_to admin_users_path, alert: "Cannot demote the only admin on the system." + return + end + old_role = @user.role + @user.update!(role: new_role) + AuditLog.log!(action: "role_toggled", user: Current.user, auditable: @user, metadata: { from: old_role, to: new_role }, request: request) + redirect_to admin_users_path, notice: "Role updated to #{new_role}." + rescue ActiveRecord::RecordInvalid => e + redirect_to admin_users_path, alert: "Could not update role: #{e.record.errors.full_messages.join(', ')}" + end + + def remove_avatar + ActiveRecord::Base.transaction do + @user.avatar_image.purge + @user.update!(avatar_url: nil) + end + redirect_to admin_users_path, notice: "Avatar removed." + end + + private + def set_user + @user = User.find(params[:id]) + end + + def user_params + params.expect(user: [ :full_name, :email, :password, :password_confirmation, :role, :avatar_image, :avatar_url ]) + end + + # A freshly uploaded file takes precedence over any URL carried in the form. + def user_params_without_stale_avatar + avatar_upload? ? user_params.merge(avatar_url: nil) : user_params + end + + def avatar_upload? + params.dig(:user, :avatar_image).is_a?(ActionDispatch::Http::UploadedFile) + end + + def replacing_attachment_with_url? + !avatar_upload? && user_params[:avatar_url].present? && @user.avatar_image.attached? + end + + def user_json(user) + { id: user.id, full_name: user.full_name, email: user.email, role: user.role, avatar_url: user.avatar_url, + avatar_attached: user.avatar_image.attached?, + avatar_image_url: (url_for(user.avatar_image) if user.avatar_image.attached?) } + end + end +end diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb new file mode 100644 index 000000000..55b0a61e3 --- /dev/null +++ b/app/controllers/application_controller.rb @@ -0,0 +1,20 @@ +class ApplicationController < ActionController::Base + include Authentication + # Cross-browser support: Rails modern-browser guard; all UI is standard HTML/CSS/React with no browser-specific APIs. + allow_browser versions: :modern + + inertia_share auth: -> { + if authenticated? + { user: { id: Current.user.id, full_name: Current.user.full_name, email: Current.user.email, role: Current.user.role } } + else + { user: nil } + end + }, flash: -> { + { notice: flash[:notice], alert: flash[:alert] } + } + + private + def after_authentication_url + session.delete(:return_to_after_authenticating) || (Current.user&.admin? ? admin_root_path : profile_path) + end +end diff --git a/app/controllers/concerns/.keep b/app/controllers/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb new file mode 100644 index 000000000..b497801d4 --- /dev/null +++ b/app/controllers/concerns/authentication.rb @@ -0,0 +1,66 @@ +module Authentication + extend ActiveSupport::Concern + + included do + before_action :require_authentication + helper_method :authenticated? + end + + class_methods do + def allow_unauthenticated_access(**options) + skip_before_action :require_authentication, **options + end + end + + private + def authenticated? + resume_session + end + + def require_authentication + resume_session || request_authentication + end + + def resume_session + Current.session ||= find_session_by_cookie + end + + def find_session_by_cookie + session = Session.find_by(id: cookies.signed[:session_id]) if cookies.signed[:session_id] + return nil unless session + + if session.expired? + session.destroy + cookies.delete(:session_id) + nil + else + session.touch_last_active! + session + end + end + + def request_authentication + session[:return_to_after_authenticating] = request.url + redirect_to new_session_path + end + + def after_authentication_url + session.delete(:return_to_after_authenticating) || root_url + end + + def start_new_session_for(user) + user.sessions.create!( + user_agent: request.user_agent, + ip_address: request.remote_ip, + last_active_at: Time.current + ).tap do |session| + Current.session = session + cookies.signed.permanent[:session_id] = { value: session.id, httponly: true, same_site: :lax } + end + end + + def terminate_session + Current.session&.destroy + cookies.delete(:session_id) + end +end diff --git a/app/controllers/health_controller.rb b/app/controllers/health_controller.rb new file mode 100644 index 000000000..ba16fb3ea --- /dev/null +++ b/app/controllers/health_controller.rb @@ -0,0 +1,13 @@ +class HealthController < ApplicationController + allow_unauthenticated_access + skip_before_action :verify_authenticity_token + + def show + ActiveRecord::Base.connection.execute("SELECT 1") + render json: { status: "ok" }, status: :ok + rescue ActiveRecord::ConnectionNotEstablished, ActiveRecord::ConnectionFailed, + ActiveRecord::StatementInvalid, PG::Error => e + Rails.logger.error("[HealthCheck] database unavailable: #{e.class}: #{e.message}") + render json: { status: "unavailable" }, status: :service_unavailable + end +end diff --git a/app/controllers/home_controller.rb b/app/controllers/home_controller.rb new file mode 100644 index 000000000..2f0c8a8b1 --- /dev/null +++ b/app/controllers/home_controller.rb @@ -0,0 +1,11 @@ +class HomeController < ApplicationController + allow_unauthenticated_access only: [ :index ] + + def index + if authenticated? + redirect_to(Current.user&.admin? ? admin_root_path : profile_path) + else + redirect_to new_session_path + end + end +end diff --git a/app/controllers/inertia_controller.rb b/app/controllers/inertia_controller.rb new file mode 100644 index 000000000..2d86313af --- /dev/null +++ b/app/controllers/inertia_controller.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class InertiaController < ApplicationController + # Share data with all Inertia responses + # see https://inertia-rails.dev/guide/shared-data + # inertia_share user: -> { Current.user&.as_json(only: [:id, :name, :email]) } +end diff --git a/app/controllers/passwords_controller.rb b/app/controllers/passwords_controller.rb new file mode 100644 index 000000000..1f0c6bf5a --- /dev/null +++ b/app/controllers/passwords_controller.rb @@ -0,0 +1,38 @@ +class PasswordsController < ApplicationController + allow_unauthenticated_access + wrap_parameters false + before_action :set_user_by_token, only: %i[ edit update ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_password_path, alert: "Try again later." } + + def new + render inertia: "Password/New" + end + + def create + if user = User.find_by(email: params[:email]) + PasswordsMailer.reset(user).deliver_later + end + + redirect_to new_session_path, notice: "Password reset instructions sent (if user with that email address exists)." + end + + def edit + render inertia: "Password/Edit", props: { token: params[:token] } + end + + def update + if @user.update(params.permit(:password, :password_confirmation)) + @user.sessions.destroy_all + redirect_to new_session_path, notice: "Password has been reset." + else + redirect_to edit_password_path(params[:token]), alert: "Passwords did not match." + end + end + + private + def set_user_by_token + @user = User.find_by_password_reset_token!(params[:token]) + rescue ActiveSupport::MessageVerifier::InvalidSignature + redirect_to new_password_path, alert: "Password reset link is invalid or has expired." + end +end diff --git a/app/controllers/profiles_controller.rb b/app/controllers/profiles_controller.rb new file mode 100644 index 000000000..ea1df7503 --- /dev/null +++ b/app/controllers/profiles_controller.rb @@ -0,0 +1,62 @@ +class ProfilesController < ApplicationController + def show + @user = Current.user + render inertia: "Profile/Show", props: { user: profile_json(@user) } + end + + def edit + @user = Current.user + render inertia: "Profile/Edit", props: { user: profile_json(@user) } + end + + def update + @user = Current.user + if @user.update(profile_params_without_stale_avatar) + # An explicit URL wins over a stored upload; drop the now-unused file + # only after the record is safely persisted. + @user.avatar_image.purge if replacing_attachment_with_url? + redirect_to profile_path, notice: "Profile updated." + else + render inertia: "Profile/Edit", props: { user: profile_json(@user) }, status: :unprocessable_entity + end + end + + def remove_avatar + @user = Current.user + ActiveRecord::Base.transaction do + @user.avatar_image.purge + @user.update!(avatar_url: nil) + end + redirect_to profile_path, notice: "Avatar removed." + end + + def destroy + Current.user.destroy + terminate_session + redirect_to new_session_path, status: :see_other, notice: "Profile deleted." + end + + private + def profile_json(user) + { full_name: user.full_name, email: user.email, role: user.role, avatar_url: user.avatar_url, + avatar_attached: user.avatar_image.attached?, + avatar_image_url: (url_for(user.avatar_image) if user.avatar_image.attached?) } + end + + def profile_params + params.expect(user: [ :full_name, :email, :avatar_image, :avatar_url ]) + end + + # A freshly uploaded file takes precedence over any URL carried in the form. + def profile_params_without_stale_avatar + avatar_upload? ? profile_params.merge(avatar_url: nil) : profile_params + end + + def avatar_upload? + params.dig(:user, :avatar_image).is_a?(ActionDispatch::Http::UploadedFile) + end + + def replacing_attachment_with_url? + !avatar_upload? && profile_params[:avatar_url].present? && @user.avatar_image.attached? + end +end diff --git a/app/controllers/registrations_controller.rb b/app/controllers/registrations_controller.rb new file mode 100644 index 000000000..c672e3df3 --- /dev/null +++ b/app/controllers/registrations_controller.rb @@ -0,0 +1,24 @@ +class RegistrationsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_registration_path, alert: "Try again later." } + + def new + @user = User.new + render inertia: "Registration/New" + end + + def create + @user = User.new(user_params) + if @user.save + start_new_session_for @user + redirect_to profile_path, notice: "Welcome!" + else + render inertia: "Registration/New", status: :unprocessable_entity + end + end + + private + def user_params + params.expect(user: [ :full_name, :email, :password, :password_confirmation ]) + end +end diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb new file mode 100644 index 000000000..a3d4f3140 --- /dev/null +++ b/app/controllers/sessions_controller.rb @@ -0,0 +1,23 @@ +class SessionsController < ApplicationController + allow_unauthenticated_access only: %i[ new create ] + wrap_parameters false + rate_limit to: 10, within: 3.minutes, only: :create, with: -> { redirect_to new_session_path, alert: "Try again later." } + + def new + render inertia: "Session/New" + end + + def create + if user = User.authenticate_by(params.permit(:email, :password)) + start_new_session_for user + redirect_to after_authentication_url + else + redirect_to new_session_path, alert: "Try another email address or password." + end + end + + def destroy + terminate_session + redirect_to new_session_path, status: :see_other + end +end diff --git a/app/frontend/entrypoints/inertia.jsx b/app/frontend/entrypoints/inertia.jsx new file mode 100644 index 000000000..3e7fc0b8c --- /dev/null +++ b/app/frontend/entrypoints/inertia.jsx @@ -0,0 +1,30 @@ +import { createInertiaApp } from '@inertiajs/react' + +createInertiaApp({ + pages: "../pages", + + strictMode: true, + + defaults: { + form: { + forceIndicesArrayFormatInFormData: false, + withAllErrors: true, + }, + visitOptions: () => { + return { queryStringArrayFormat: "brackets" } + }, + }, +}).catch((error) => { + // This ensures this entrypoint is only loaded on Inertia pages + // by checking for the presence of the root element (#app by default). + // Feel free to remove this `catch` if you don't need it. + if (document.getElementById("app")) { + throw error + } else { + console.error( + "Missing root element.\n\n" + + "If you see this error, it probably means you loaded Inertia.js on non-Inertia pages.\n" + + 'Consider moving <%= vite_javascript_tag "inertia.jsx" %> to the Inertia-specific layout instead.', + ) + } +}) diff --git a/app/frontend/lib/cable.js b/app/frontend/lib/cable.js new file mode 100644 index 000000000..1a6e07fb3 --- /dev/null +++ b/app/frontend/lib/cable.js @@ -0,0 +1,34 @@ +import { createConsumer } from "@rails/actioncable" + +let consumer = null + +export function cable() { + if (!consumer) consumer = createConsumer() + return consumer +} + +/** + * Subscribe to an ActionCable channel. + * @param {string} channel - Channel class name + * @param {object} params - Subscription params (e.g. { id: 1 }) + * @param {object} callbacks - { received, connected, disconnected } + * @returns {object} subscription + */ +export function subscribe(channel, params, callbacks) { + const { received, connected, disconnected } = typeof callbacks === "function" + ? { received: callbacks, connected: undefined, disconnected: undefined } + : callbacks + + return cable().subscriptions.create( + { channel, ...params }, + { + received, + connected() { + if (connected) connected() + }, + disconnected() { + if (disconnected) disconnected() + }, + }, + ) +} diff --git a/app/frontend/pages/Admin/Dashboard/Show.jsx b/app/frontend/pages/Admin/Dashboard/Show.jsx new file mode 100644 index 000000000..7eec75469 --- /dev/null +++ b/app/frontend/pages/Admin/Dashboard/Show.jsx @@ -0,0 +1,49 @@ +import { Link, router } from "@inertiajs/react" +import { useEffect, useState, useCallback } from "react" +import Layout from "../../Shared/Layout" +import { subscribe } from "../../../lib/cable" + +export default function Show({ total_users, users_by_role }) { + const [counts, setCounts] = useState({ total_users, users_by_role }) + + const refetchState = useCallback(() => { + router.reload({ only: ["total_users", "users_by_role"], preserveState: true, preserveScroll: true }) + }, []) + + useEffect(() => { + const sub = subscribe("DashboardChannel", {}, { + received(data) { + setCounts(data) + }, + connected() { + refetchState() + }, + }) + return () => sub.unsubscribe() + }, [refetchState]) + return ( +
+

Dashboard

+

Real-time user statistics.

+
+
+

Total Users

+

{counts.total_users}

+
+
+

By Role

+
    + {Object.entries(counts.users_by_role || {}).map(([role, count]) => ( +
  • {role}{count}
  • + ))} +
+
+
+
+ Manage users + Imports +
+
+ ) +} +Show.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Imports/Index.jsx b/app/frontend/pages/Admin/Imports/Index.jsx new file mode 100644 index 000000000..42c3d33b6 --- /dev/null +++ b/app/frontend/pages/Admin/Imports/Index.jsx @@ -0,0 +1,54 @@ +import { Link } from "@inertiajs/react" +import Layout from "../../Shared/Layout" + +function Pagination({ pagination, baseUrl }) { + if (!pagination || pagination.total_pages <= 1) return null + const { current_page, total_pages } = pagination + const pages = [] + for (let i = 1; i <= total_pages; i++) pages.push(i) + + return ( + + ) +} + +export default function Index({ imports, pagination }) { + return ( +
+

Imports

+

Asynchronous spreadsheet imports.

+ New import +
+
+ + + + {imports.map((imp) => ( + + + + + + + + + ))} + +
IDFile NameStatusProcessedFailed
{imp.id}{imp.file_name || "\u2014"}{imp.status}{imp.processed_rows}{imp.failed_rows}View
+
+
+ +
+ ) +} +Index.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Imports/New.jsx b/app/frontend/pages/Admin/Imports/New.jsx new file mode 100644 index 000000000..05d25093a --- /dev/null +++ b/app/frontend/pages/Admin/Imports/New.jsx @@ -0,0 +1,20 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../../Shared/Layout" + +export default function New() { + const { data, setData, post, processing, errors } = useForm({ user_import: { file: null } }) + function submit(e) { e.preventDefault(); if (window.confirm("Upload spreadsheet?")) post("/admin/user_imports") } + return ( +
+

Import users

+

Upload a .csv or .xlsx spreadsheet.

+
+ + setData("user_import", { file: e.target.files[0] })} className="block w-full text-sm text-slate-600 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-medium file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100" /> + {errors.file &&

{errors.file}

} + +
+
+ ) +} +New.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Imports/Show.jsx b/app/frontend/pages/Admin/Imports/Show.jsx new file mode 100644 index 000000000..f869ea61f --- /dev/null +++ b/app/frontend/pages/Admin/Imports/Show.jsx @@ -0,0 +1,71 @@ +import { Link, router } from "@inertiajs/react" +import { useEffect, useState, useCallback } from "react" +import Layout from "../../Shared/Layout" +import { subscribe } from "../../../lib/cable" + +export default function Show({ import: importRecord }) { + const [imp, setImp] = useState(importRecord) + const [connected, setConnected] = useState(false) + + // Refetch current state from server after subscription connects. + // This closes the race window where broadcasts fired before the + // WebSocket subscription was confirmed. + const refetchState = useCallback(() => { + router.reload({ only: ["import"], preserveState: true, preserveScroll: true }) + }, []) + + useEffect(() => { + const sub = subscribe("UserImportChannel", { id: importRecord.id }, { + received(data) { + setImp((prev) => ({ ...prev, ...data })) + }, + connected() { + setConnected(true) + refetchState() + }, + disconnected() { + setConnected(false) + }, + }) + return () => sub.unsubscribe() + }, [importRecord.id, refetchState]) + + const pct = imp.progress_percent || 0 + const isDone = imp.status === "completed" || imp.status === "failed" + + return ( +
+

Import {imp.id}

+

Live progress tracking.

+
+
+

Status

{imp.status}

+

Processed

{imp.processed_rows}

+

Failed

{imp.failed_rows}

+

Total

{imp.total_rows}

+
+
+
+
+

{pct}% complete

+
+ + {imp.row_errors && imp.row_errors.length > 0 && ( +
+

Row errors ({imp.row_errors.length})

+ {imp.errors_truncated &&

Showing the first 100 errors.

} +
    + {imp.row_errors.map((err, i) => ( +
  • + Row {err.row} — {err.email || "(blank)"}: {err.error} +
  • + ))} +
+
+ )} + +

Back

+
+ ) +} +Show.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Users/Edit.jsx b/app/frontend/pages/Admin/Users/Edit.jsx new file mode 100644 index 000000000..fde7515dd --- /dev/null +++ b/app/frontend/pages/Admin/Users/Edit.jsx @@ -0,0 +1,14 @@ +import Layout from "../../Shared/Layout" +import { UserForm } from "./New" + +export default function Edit({ user }) { + return ( +
+

Edit user

+

Update user details.

+ +
+ ) +} + +Edit.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Users/Index.jsx b/app/frontend/pages/Admin/Users/Index.jsx new file mode 100644 index 000000000..1f45f41e7 --- /dev/null +++ b/app/frontend/pages/Admin/Users/Index.jsx @@ -0,0 +1,73 @@ +import { Link, router } from "@inertiajs/react" +import Layout from "../../Shared/Layout" + +function destroyUser(id, name) { + if (window.confirm(`Delete user "${name}"? This cannot be undone.`)) router.delete(`/admin/users/${id}`) +} +function toggleRole(id, name) { + if (window.confirm(`Toggle role for "${name}"?`)) router.patch(`/admin/users/${id}/toggle_role`) +} + +function Pagination({ pagination, baseUrl }) { + if (!pagination || pagination.total_pages <= 1) return null + const { current_page, total_pages } = pagination + const pages = [] + for (let i = 1; i <= total_pages; i++) pages.push(i) + + return ( + + ) +} + +export default function Index({ users, admin_count, pagination }) { + const isOnlyAdmin = (user) => user.role === "admin" && admin_count === 1 + return ( +
+

Users

+

Manage all registered users.

+ New user +
+
+ + + + + + {users.map((user) => ( + + + + + + + ))} + +
NameEmailRoleActions
{user.full_name}{user.email}{user.role} +
+ Profile + Edit + + {isOnlyAdmin(user) ? ( + Delete + ) : ( + + )} +
+
+
+
+ +
+ ) +} +Index.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Users/New.jsx b/app/frontend/pages/Admin/Users/New.jsx new file mode 100644 index 000000000..cc0dcda97 --- /dev/null +++ b/app/frontend/pages/Admin/Users/New.jsx @@ -0,0 +1,65 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../../Shared/Layout" +import { Field, PasswordHint, inputClass } from "../../Shared/FormFields" + +export function UserForm({ user, submitTo, method, submitLabel }) { + const { data, setData, submit, processing, errors } = useForm({ + user: { + full_name: user?.full_name || "", + email: user?.email || "", + password: "", + password_confirmation: "", + role: user?.role || "user", + avatar_url: user?.avatar_url || "", + }, + }) + + const set = (k) => (e) => setData("user", { ...data.user, [k]: e.target.value }) + + function submitForm(e, submitFn, message) { + e.preventDefault() + if (window.confirm(message)) submitFn() + } + + return ( +
submitForm(e, () => submit(method, submitTo), method === "post" ? "Create this user?" : "Save changes to this user?")} className="space-y-4"> + + + + + + + }> + + + + + + + + + + + + + setData("user", { ...data.user, avatar_image: e.target.files[0] })} /> + + +
+ ) +} + +export default function New() { + return ( +
+

New user

+

Create a new user account.

+ +
+ ) +} + +New.layout = (page) => {page} diff --git a/app/frontend/pages/Admin/Users/Show.jsx b/app/frontend/pages/Admin/Users/Show.jsx new file mode 100644 index 000000000..4f6e053bc --- /dev/null +++ b/app/frontend/pages/Admin/Users/Show.jsx @@ -0,0 +1,30 @@ +import { Link } from "@inertiajs/react" +import Layout from "../../Shared/Layout" + +export default function Show({ user }) { + return ( +
+

User Profile

+

Viewing {user.full_name}'s profile.

+
+
+ {(user.avatar_attached ? user.avatar_image_url : user.avatar_url) ? ( + {user.full_name} + ) : ( + {user.full_name?.charAt(0)} + )} +
+
+

{user.full_name}

+

{user.email}

+ {user.role} +
+
+
+ Edit user + Back to users +
+
+ ) +} +Show.layout = (page) => {page} diff --git a/app/frontend/pages/Password/Edit.jsx b/app/frontend/pages/Password/Edit.jsx new file mode 100644 index 000000000..2ebe69865 --- /dev/null +++ b/app/frontend/pages/Password/Edit.jsx @@ -0,0 +1,27 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../Shared/Layout" +import { Field, PasswordHint, inputClass } from "../Shared/FormFields" + +export default function Edit({ token }) { + const { data, setData, put, processing, errors } = useForm({ password: "", password_confirmation: "" }) + function submit(e) { + e.preventDefault() + put(`/passwords/${token}`) + } + return ( +
+

Reset password

+
+ }> + setData("password", e.target.value)} /> + + + setData("password_confirmation", e.target.value)} /> + + +
+
+ ) +} + +Edit.layout = (page) => {page} diff --git a/app/frontend/pages/Password/New.jsx b/app/frontend/pages/Password/New.jsx new file mode 100644 index 000000000..3a8b15e56 --- /dev/null +++ b/app/frontend/pages/Password/New.jsx @@ -0,0 +1,24 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../Shared/Layout" +import { Field, inputClass } from "../Shared/FormFields" + +export default function New() { + const { data, setData, post, processing, errors } = useForm({ email: "" }) + function submit(e) { + e.preventDefault() + post("/passwords") + } + return ( +
+

Forgot your password?

+
+ + setData("email", e.target.value)} /> + + +
+
+ ) +} + +New.layout = (page) => {page} diff --git a/app/frontend/pages/Profile/Edit.jsx b/app/frontend/pages/Profile/Edit.jsx new file mode 100644 index 000000000..98f8bdc64 --- /dev/null +++ b/app/frontend/pages/Profile/Edit.jsx @@ -0,0 +1,38 @@ +import { router } from "@inertiajs/react" +import { useForm } from "@inertiajs/react" +import Layout from "../Shared/Layout" +import { Field, inputClass } from "../Shared/FormFields" + +export default function Edit({ user }) { + const { data, setData, patch, processing, errors } = useForm({ + user: { full_name: user.full_name, email: user.email, avatar_url: user.avatar_url || "" }, + }) + function submit(e) { + e.preventDefault() + patch("/profile") + } + const set = (k) => (e) => setData("user", { ...data.user, [k]: e.target.value }) + return ( +
+

Edit Profile

+

Update your account details.

+
+ + + + + + + + + + + setData("user", { ...data.user, avatar_image: e.target.files[0] })} /> + + + +
+
+ ) +} +Edit.layout = (page) => {page} diff --git a/app/frontend/pages/Profile/Show.jsx b/app/frontend/pages/Profile/Show.jsx new file mode 100644 index 000000000..3396eadd1 --- /dev/null +++ b/app/frontend/pages/Profile/Show.jsx @@ -0,0 +1,30 @@ +import { Link } from "@inertiajs/react" +import Layout from "../Shared/Layout" + +export default function Show({ user }) { + return ( +
+

My Profile

+

Your account details and preferences.

+
+
+ {(user.avatar_attached ? user.avatar_image_url : user.avatar_url) ? ( + {user.full_name} + ) : ( + {user.full_name?.charAt(0)} + )} +
+
+

{user.full_name}

+

{user.email}

+ {user.role} +
+
+
+ Edit profile + Delete account +
+
+ ) +} +Show.layout = (page) => {page} diff --git a/app/frontend/pages/Registration/New.jsx b/app/frontend/pages/Registration/New.jsx new file mode 100644 index 000000000..854fb799d --- /dev/null +++ b/app/frontend/pages/Registration/New.jsx @@ -0,0 +1,31 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../Shared/Layout" +import { Field, FieldError, PasswordHint, inputClass } from "../Shared/FormFields" + +export default function New() { + const { data, setData, post, processing, errors } = useForm({ user: { full_name: "", email: "", password: "", password_confirmation: "" } }) + function submit(e) { e.preventDefault(); post("/registration") } + const set = (k) => (e) => setData("user", { ...data.user, [k]: e.target.value }) + return ( +
+

Create account

+

Join the modern fullstack platform.

+
+ + + + + + + }> + + + + + + +
+
+ ) +} +New.layout = (page) => {page} diff --git a/app/frontend/pages/Session/New.jsx b/app/frontend/pages/Session/New.jsx new file mode 100644 index 000000000..bb9dbb127 --- /dev/null +++ b/app/frontend/pages/Session/New.jsx @@ -0,0 +1,30 @@ +import { useForm } from "@inertiajs/react" +import Layout from "../Shared/Layout" +import { Field, inputClass } from "../Shared/FormFields" + +export default function New() { + const { data, setData, post, processing, errors } = useForm({ email: "", password: "" }) + function submit(e) { e.preventDefault(); post("/session") } + const set = (k) => (e) => setData(k, e.target.value) + return ( +
+

Welcome back

+

Sign in to manage your account.

+
+ + + + + + + +
+ +
+ ) +} +New.layout = (page) => {page} diff --git a/app/frontend/pages/Shared/FormFields.jsx b/app/frontend/pages/Shared/FormFields.jsx new file mode 100644 index 000000000..b4b6ad0e0 --- /dev/null +++ b/app/frontend/pages/Shared/FormFields.jsx @@ -0,0 +1,59 @@ +/** + * Shared form field components for consistent validation UI. + * // OptimizationRef: RB4-RM80-InertiaReact + */ + +/** Displays a field-level validation error with accessible markup. */ +export function FieldError({ error }) { + if (!error) return null + const message = Array.isArray(error) ? error[0] : error + return ( +

+ + + + {message} +

+ ) +} + +/** Displays server-wide (non-field) errors. */ +export function FormErrors({ errors }) { + if (!errors) return null + // Rails returns { base: [...] } for non-field errors + const base = errors.base + if (!base) return null + const messages = Array.isArray(base) ? base : [base] + return ( +
+

Please fix the following errors:

+
    + {messages.map((msg, i) =>
  • {msg}
  • )} +
+
+ ) +} + +/** Password complexity hint shown below password fields. */ +export function PasswordHint({ className = "" }) { + return ( +

+ Must be at least 8 characters with one uppercase letter, one lowercase letter, and one number. +

+ ) +} + +/** Styled form input with consistent spacing. */ +export const inputClass = "w-full rounded-xl border border-slate-300 px-4 py-3 shadow-sm focus:outline-none focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 transition" + +/** Wraps a field with label, input, and error display. */ +export function Field({ label, htmlFor, error, children, hint }) { + return ( +
+ {label && } + {children} + {hint} + +
+ ) +} diff --git a/app/frontend/pages/Shared/Layout.jsx b/app/frontend/pages/Shared/Layout.jsx new file mode 100644 index 000000000..097d88beb --- /dev/null +++ b/app/frontend/pages/Shared/Layout.jsx @@ -0,0 +1,58 @@ +import { Link, usePage } from "@inertiajs/react" + +export default function Layout({ children }) { + const { auth, flash } = usePage().props + const user = auth?.user + + return ( +
+
+ +
+
+ {flash?.notice && ( +
+ {flash.notice} +
+ )} + {flash?.alert && ( +
+ {flash.alert} +
+ )} +
+ {children} +
+
+
+ Modern Fullstack Developer Test — Rails 8 / Ruby 4 / Inertia React +
+
+ ) +} +// OptimizationRef: RB4-RM80-InertiaReact diff --git a/app/frontend/ssr/ssr.jsx b/app/frontend/ssr/ssr.jsx new file mode 100644 index 000000000..8efb150d2 --- /dev/null +++ b/app/frontend/ssr/ssr.jsx @@ -0,0 +1,19 @@ +import serve from "@inertiajs/react/server" +import { createInertiaApp } from "@inertiajs/react" +import { renderToString } from "react-dom/server" + +const pages = import.meta.glob("../pages/**/*.jsx", { eager: true }) + +function resolve(name) { + const page = pages[`../pages/${name}.jsx`] + if (!page) throw new Error(`Unknown Inertia page: ${name}`) + return page.default +} + +// No `page` here: returns a (page, renderToString) => { head, body } renderer. +const render = await createInertiaApp({ resolve }) + +serve( + (page) => render(page, renderToString), + Number(process.env.PORT || 13714), +) diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb new file mode 100644 index 000000000..de6be7945 --- /dev/null +++ b/app/helpers/application_helper.rb @@ -0,0 +1,2 @@ +module ApplicationHelper +end diff --git a/app/jobs/application_job.rb b/app/jobs/application_job.rb new file mode 100644 index 000000000..d394c3d10 --- /dev/null +++ b/app/jobs/application_job.rb @@ -0,0 +1,7 @@ +class ApplicationJob < ActiveJob::Base + # Automatically retry jobs that encountered a deadlock + # retry_on ActiveRecord::Deadlocked + + # Most jobs are safe to ignore if the underlying records are no longer available + # discard_on ActiveJob::DeserializationError +end diff --git a/app/jobs/expire_sessions_job.rb b/app/jobs/expire_sessions_job.rb new file mode 100644 index 000000000..e3947ec38 --- /dev/null +++ b/app/jobs/expire_sessions_job.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +# Cleans up expired sessions to prevent unbounded session accumulation. +# Sessions older than 30 days are destroyed. +class ExpireSessionsJob < ApplicationJob + queue_as :default + + SESSION_TTL = 30.days + BATCH_SIZE = 1_000 + + def perform + count = Session.expired.in_batches(of: BATCH_SIZE).sum(&:delete_all) + Rails.logger.info("[ExpireSessionsJob] removed #{count} expired sessions") if count.positive? + count + end +end diff --git a/app/jobs/user_import_job.rb b/app/jobs/user_import_job.rb new file mode 100644 index 000000000..befdf58cf --- /dev/null +++ b/app/jobs/user_import_job.rb @@ -0,0 +1,129 @@ +class UserImportJob < ApplicationJob + queue_as :default + + # Transient infrastructure failures are retried with backoff; malformed rows + # are handled per-row and never raise. + retry_on ActiveRecord::ConnectionNotEstablished, ActiveRecord::ConnectionFailed, + ActiveRecord::QueryCanceled, PG::ConnectionBad, + wait: :polynomially_longer, attempts: 3 + discard_on ActiveJob::DeserializationError + + MAX_ROWS = 10_000 + MAX_ROW_ERRORS = 100 + ROW_LIMIT_ERROR = "File exceeds the 10,000 row limit" + + def perform(user_import) + return if user_import.completed? # already finished on a previous attempt + + resuming = user_import.processing? + Rails.logger.info("[UserImportJob] started import_id=#{user_import.id} resuming=#{resuming}") + + user_import.update!( + status: :processing, + row_errors: resuming ? user_import.row_errors : [], + processed_rows: resuming ? user_import.processed_rows : 0, + failed_rows: resuming ? user_import.failed_rows : 0 + ) + @errors_truncated = false + + begin + rows = read_rows(user_import) + user_import.update!(total_rows: rows.size) + + if rows.size > MAX_ROWS + Rails.logger.warn("[UserImportJob] rejected import_id=#{user_import.id} rows=#{rows.size} exceeds limit") + user_import.update!(status: :failed, row_errors: [ { row: nil, email: nil, error: ROW_LIMIT_ERROR } ]) + broadcast(user_import, include_errors: true) + return + end + + # Skip rows already accounted for by a previous attempt so retries resume + # instead of recreating users (and failing on duplicate emails). + cursor = user_import.processed_rows + user_import.failed_rows + + rows.each_with_index do |row, index| + next if index < cursor + + email = row["email"].to_s.strip.downcase + if email.blank? || email == "email" + user_import.increment!(:failed_rows) + append_error(user_import, index + 2, email, "Email is blank") + next + end + + begin + password = row["password"].to_s + password = generate_password if password.blank? || password.length < 8 + User.create!( + full_name: row["full_name"].to_s, + email: email, + password: password, + password_confirmation: password + ) + user_import.increment!(:processed_rows) + rescue ActiveRecord::RecordInvalid => e + user_import.increment!(:failed_rows) + append_error(user_import, index + 2, email, e.record.errors.full_messages.join(", ")) + end + user_import.reload + broadcast(user_import) + end + + user_import.update!(status: user_import.failed_rows.positive? && user_import.processed_rows.zero? ? :failed : :completed) + Rails.logger.info("[UserImportJob] completed import_id=#{user_import.id} processed=#{user_import.processed_rows} failed=#{user_import.failed_rows}") + broadcast(user_import, include_errors: true) + rescue StandardError => e + Rails.logger.error("[UserImportJob] failed import_id=#{user_import.id} error=#{e.class}: #{e.message}") + user_import.update!(status: :failed) + broadcast(user_import, include_errors: true) + raise + end + end + + private + def append_error(user_import, row_number, email, message) + if user_import.row_errors.size < MAX_ROW_ERRORS + user_import.update!(row_errors: user_import.row_errors + [ { row: row_number, email: email, error: message } ]) + else + @errors_truncated = true + end + end + + def broadcast(user_import, include_errors: false) + payload = { + status: user_import.status, total_rows: user_import.total_rows, + processed_rows: user_import.processed_rows, failed_rows: user_import.failed_rows, + progress_percent: user_import.progress_percent + } + if include_errors + payload[:row_errors] = user_import.row_errors + payload[:errors_truncated] = true if @errors_truncated + end + UserImportChannel.broadcast_to(user_import, payload) + end + + def read_rows(user_import) + file = user_import.file + ext = File.extname(file.filename.to_s).downcase + path = ActiveStorage::Blob.service.path_for(file.key) + if ext == ".csv" + CSV.read(path, headers: true).map(&:to_h) + else + workbook = RubyXL::Parser.parse(path) + sheet = workbook[0] + headers = sheet[0].cells.map { |c| c&.value.to_s } + sheet.drop(1).filter_map do |row| + next if row.cells.all? { |c| c&.value.nil? } + headers.zip(row.cells.map { |c| c&.value }).to_h + end + end + end + + def generate_password + chars = ("A".."Z").to_a + ("a".."z").to_a + ("0".."9").to_a + %w[! @ # $ %] + loop do + pwd = Array.new(12) { chars.sample }.join + break pwd if pwd.match?(/[A-Z]/) && pwd.match?(/[a-z]/) && pwd.match?(/\d/) + end + end +end diff --git a/app/mailers/application_mailer.rb b/app/mailers/application_mailer.rb new file mode 100644 index 000000000..3c34c8148 --- /dev/null +++ b/app/mailers/application_mailer.rb @@ -0,0 +1,4 @@ +class ApplicationMailer < ActionMailer::Base + default from: "from@example.com" + layout "mailer" +end diff --git a/app/mailers/passwords_mailer.rb b/app/mailers/passwords_mailer.rb new file mode 100644 index 000000000..06ac4a4da --- /dev/null +++ b/app/mailers/passwords_mailer.rb @@ -0,0 +1,6 @@ +class PasswordsMailer < ApplicationMailer + def reset(user) + @user = user + mail subject: "Reset your password", to: user.email + end +end diff --git a/app/models/application_record.rb b/app/models/application_record.rb new file mode 100644 index 000000000..b63caeb8a --- /dev/null +++ b/app/models/application_record.rb @@ -0,0 +1,3 @@ +class ApplicationRecord < ActiveRecord::Base + primary_abstract_class +end diff --git a/app/models/audit_log.rb b/app/models/audit_log.rb new file mode 100644 index 000000000..0382aabe8 --- /dev/null +++ b/app/models/audit_log.rb @@ -0,0 +1,44 @@ +# == Schema Information +# +# Table name: audit_logs +# +# id :bigint not null, primary key +# action :string not null +# auditable_type :string +# ip_address :string +# metadata :jsonb +# user_agent :string +# created_at :datetime not null +# updated_at :datetime not null +# auditable_id :bigint +# user_id :bigint +# +# Indexes +# +# index_audit_logs_on_auditable_type_and_auditable_id (auditable_type,auditable_id) +# index_audit_logs_on_created_at (created_at) +# index_audit_logs_on_user_id (user_id) +# +# Foreign Keys +# +# fk_rails_... (user_id => users.id) ON DELETE => nullify +# +class AuditLog < ApplicationRecord + belongs_to :user, optional: true + belongs_to :auditable, polymorphic: true, optional: true + + validates :action, presence: true + + scope :recent, -> { order(created_at: :desc).limit(100) } + + def self.log!(action:, user: nil, auditable: nil, metadata: {}, request: nil) + create!( + action: action, + user: user, + auditable: auditable, + metadata: metadata, + ip_address: request&.remote_ip, + user_agent: request&.user_agent + ) + end +end diff --git a/app/models/concerns/.keep b/app/models/concerns/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/app/models/current.rb b/app/models/current.rb new file mode 100644 index 000000000..2bef56dad --- /dev/null +++ b/app/models/current.rb @@ -0,0 +1,4 @@ +class Current < ActiveSupport::CurrentAttributes + attribute :session + delegate :user, to: :session, allow_nil: true +end diff --git a/app/models/session.rb b/app/models/session.rb new file mode 100644 index 000000000..d93a11bf1 --- /dev/null +++ b/app/models/session.rb @@ -0,0 +1,38 @@ +# == Schema Information +# +# Table name: sessions +# +# id :bigint not null, primary key +# ip_address :string +# last_active_at :datetime +# user_agent :string +# created_at :datetime not null +# updated_at :datetime not null +# user_id :bigint not null +# +# Indexes +# +# index_sessions_on_created_at (created_at) +# index_sessions_on_last_active_at (last_active_at) +# index_sessions_on_user_id (user_id) +# +# Foreign Keys +# +# fk_rails_... (user_id => users.id) +# +class Session < ApplicationRecord + belongs_to :user + + SESSION_TTL = 30.days + + scope :expired, -> { where("last_active_at < ?", SESSION_TTL.ago) } + scope :active, -> { where("last_active_at >= ? OR last_active_at IS NULL", SESSION_TTL.ago) } + + def expired? + last_active_at.present? && last_active_at < SESSION_TTL.ago + end + + def touch_last_active! + update_column(:last_active_at, Time.current) + end +end diff --git a/app/models/user.rb b/app/models/user.rb new file mode 100644 index 000000000..c1ddcd2c2 --- /dev/null +++ b/app/models/user.rb @@ -0,0 +1,64 @@ +# == Schema Information +# +# Table name: users +# +# id :bigint not null, primary key +# avatar_url :string +# email :string not null +# full_name :string not null +# password_digest :string not null +# role :integer default(0), not null +# created_at :datetime not null +# updated_at :datetime not null +# +# Indexes +# +# index_users_on_email (email) UNIQUE +# +class User < ApplicationRecord + has_secure_password + has_many :sessions, dependent: :destroy + has_one_attached :avatar_image + + enum :role, { user: 0, admin: 1 }, default: :user + + normalizes :email, with: ->(e) { e.strip.downcase } + + validates :full_name, presence: true + validates :email, presence: true, uniqueness: true, format: { with: URI::MailTo::EMAIL_REGEXP } + validates :avatar_url, format: { with: URI::DEFAULT_PARSER.make_regexp(%w[http https]), message: "must be a valid URL" }, allow_blank: true + validates :password, length: { minimum: 8 }, if: :password_digest_changed? + validate :password_complexity, if: :password_digest_changed? + validate :avatar_image_size + + def avatar_display + avatar_image.attached? ? avatar_image : avatar_url + end + + after_commit :broadcast_dashboard_counts, on: %i[ create update destroy ] + + private + def password_complexity + return if password.blank? + errors.add(:password, "must include at least one uppercase letter") unless password.match?(/[A-Z]/) + errors.add(:password, "must include at least one lowercase letter") unless password.match?(/[a-z]/) + errors.add(:password, "must include at least one digit") unless password.match?(/\d/) + end + + def avatar_image_size + return unless avatar_image.attached? + if avatar_image.blob.byte_size > MAX_AVATAR_UPLOAD_SIZE + avatar_image.purge + errors.add(:avatar_image, "is too large (maximum is #{MAX_AVATAR_UPLOAD_SIZE / 1.megabyte}MB)") + end + end + + def broadcast_dashboard_counts + ActionCable.server.broadcast( + "dashboard", + { total_users: User.count, users_by_role: User.group(:role).count } + ) + rescue StandardError => e + Rails.logger.error("[User] broadcast_dashboard_counts failed: #{e.class}: #{e.message}") + end +end diff --git a/app/models/user_import.rb b/app/models/user_import.rb new file mode 100644 index 000000000..707a62f6e --- /dev/null +++ b/app/models/user_import.rb @@ -0,0 +1,49 @@ +# == Schema Information +# +# Table name: user_imports +# +# id :bigint not null, primary key +# failed_rows :integer default(0), not null +# file_name :string +# processed_rows :integer default(0), not null +# row_errors :jsonb not null +# status :integer default(0), not null +# total_rows :integer default(0), not null +# created_at :datetime not null +# updated_at :datetime not null +# +class UserImport < ApplicationRecord + has_one_attached :file + + enum :status, { pending: 0, processing: 1, completed: 2, failed: 3 }, default: :pending + + validates :file, presence: true + validate :file_size_within_limit, on: :create + validate :file_content_type_allowed, on: :create + + def file_name + file.attached? ? file.filename.to_s : nil + end + + def progress_percent + return 0 if total_rows.zero? + ((processed_rows + failed_rows) * 100.0 / total_rows).round + end + + private + def file_size_within_limit + return unless file.attached? + if file.blob.byte_size > MAX_IMPORT_FILE_SIZE + file.purge + errors.add(:file, "is too large (maximum is #{MAX_IMPORT_FILE_SIZE / 1.megabyte}MB)") + end + end + + def file_content_type_allowed + return unless file.attached? + unless ALLOWED_IMPORT_CONTENT_TYPES.include?(file.content_type) + file.purge + errors.add(:file, "must be a CSV or Excel file (.csv, .xlsx)") + end + end +end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb new file mode 100644 index 000000000..75d024c67 --- /dev/null +++ b/app/views/layouts/application.html.erb @@ -0,0 +1,30 @@ + + + + <%= content_for(:title) || "Fullstack Developer" %> + + + + + <%= csrf_meta_tags %> + <%= csp_meta_tag %> + + <%= yield :head %> + + + + + + <%= stylesheet_link_tag :app %> + <%= vite_react_refresh_tag %> + <%= vite_client_tag %> + <%= vite_javascript_tag "inertia.jsx" %> + <%= inertia_ssr_head %> + + + +
+ <%= yield %> +
+ + diff --git a/app/views/layouts/mailer.html.erb b/app/views/layouts/mailer.html.erb new file mode 100644 index 000000000..3aac9002e --- /dev/null +++ b/app/views/layouts/mailer.html.erb @@ -0,0 +1,13 @@ + + + + + + + + + <%= yield %> + + diff --git a/app/views/layouts/mailer.text.erb b/app/views/layouts/mailer.text.erb new file mode 100644 index 000000000..37f0bddbd --- /dev/null +++ b/app/views/layouts/mailer.text.erb @@ -0,0 +1 @@ +<%= yield %> diff --git a/app/views/passwords_mailer/reset.html.erb b/app/views/passwords_mailer/reset.html.erb new file mode 100644 index 000000000..1b0915419 --- /dev/null +++ b/app/views/passwords_mailer/reset.html.erb @@ -0,0 +1,6 @@ +

+ You can reset your password on + <%= link_to "this password reset page", edit_password_url(@user.password_reset_token) %>. + + This link will expire in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. +

diff --git a/app/views/passwords_mailer/reset.text.erb b/app/views/passwords_mailer/reset.text.erb new file mode 100644 index 000000000..aecee82c4 --- /dev/null +++ b/app/views/passwords_mailer/reset.text.erb @@ -0,0 +1,4 @@ +You can reset your password on +<%= edit_password_url(@user.password_reset_token) %> + +This link will expire in <%= distance_of_time_in_words(0, @user.password_reset_token_expires_in) %>. diff --git a/app/views/pwa/manifest.json.erb b/app/views/pwa/manifest.json.erb new file mode 100644 index 000000000..13a7b4eff --- /dev/null +++ b/app/views/pwa/manifest.json.erb @@ -0,0 +1,22 @@ +{ + "name": "FullstackDeveloper", + "icons": [ + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512" + }, + { + "src": "/icon.png", + "type": "image/png", + "sizes": "512x512", + "purpose": "maskable" + } + ], + "start_url": "/", + "display": "standalone", + "scope": "/", + "description": "FullstackDeveloper.", + "theme_color": "red", + "background_color": "red" +} diff --git a/app/views/pwa/service-worker.js b/app/views/pwa/service-worker.js new file mode 100644 index 000000000..b3a13fb7b --- /dev/null +++ b/app/views/pwa/service-worker.js @@ -0,0 +1,26 @@ +// Add a service worker for processing Web Push notifications: +// +// self.addEventListener("push", async (event) => { +// const { title, options } = await event.data.json() +// event.waitUntil(self.registration.showNotification(title, options)) +// }) +// +// self.addEventListener("notificationclick", function(event) { +// event.notification.close() +// event.waitUntil( +// clients.matchAll({ type: "window" }).then((clientList) => { +// for (let i = 0; i < clientList.length; i++) { +// let client = clientList[i] +// let clientPath = (new URL(client.url)).pathname +// +// if (clientPath == event.notification.data.path && "focus" in client) { +// return client.focus() +// } +// } +// +// if (clients.openWindow) { +// return clients.openWindow(event.notification.data.path) +// } +// }) +// ) +// }) diff --git a/benchmark/zjit_profile.rb b/benchmark/zjit_profile.rb new file mode 100644 index 000000000..01206a428 --- /dev/null +++ b/benchmark/zjit_profile.rb @@ -0,0 +1,9 @@ +# Performance profiling leveraging Ruby 4 ZJIT +# Usage: RUBYOPT="--zjit" ruby benchmark/zjit_profile.rb +require_relative "../config/environment" +require "securerandom" +require "benchmark/ips" +Benchmark.ips do |x| + x.config(time: 2, warmup: 1) + x.report("user creation") { User.create!(full_name: "ZJIT", email: "zjit-#{SecureRandom.uuid}@example.com", password: "Password123", password_confirmation: "Password123") } +end diff --git a/bin/brakeman b/bin/brakeman new file mode 100755 index 000000000..ace1c9ba0 --- /dev/null +++ b/bin/brakeman @@ -0,0 +1,7 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +ARGV.unshift("--ensure-latest") + +load Gem.bin_path("brakeman", "brakeman") diff --git a/bin/bundler-audit b/bin/bundler-audit new file mode 100755 index 000000000..e2ef22690 --- /dev/null +++ b/bin/bundler-audit @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "bundler/audit/cli" + +ARGV.concat %w[ --config config/bundler-audit.yml ] if ARGV.empty? || ARGV.include?("check") +Bundler::Audit::CLI.start diff --git a/bin/ci b/bin/ci new file mode 100755 index 000000000..4dbae3f0d --- /dev/null +++ b/bin/ci @@ -0,0 +1,15 @@ +#!/usr/bin/env ruby +ENV["RUBYOPT"] = "--zjit #{ENV["RUBYOPT"].to_s}" + +# Release It! — gracefully handle missing master.key in CI environments +master_key_path = File.expand_path("../config/master.key", __dir__) +if File.exist?(master_key_path) + ENV["RAILS_MASTER_KEY"] = File.read(master_key_path).strip +elsif ENV["RAILS_MASTER_KEY"].blank? + warn "WARNING: config/master.key not found and RAILS_MASTER_KEY not set" +end + +require "active_support/continuous_integration" + +CI = ActiveSupport::ContinuousIntegration +require_relative "../config/ci.rb" diff --git a/bin/dev b/bin/dev new file mode 100755 index 000000000..ef33f02c7 --- /dev/null +++ b/bin/dev @@ -0,0 +1,23 @@ +#!/usr/bin/env sh + +export PORT="${PORT:-3000}" + +if command -v overmind 1> /dev/null 2>&1 +then + overmind start -f Procfile.dev "$@" + exit $? +fi + +if command -v hivemind 1> /dev/null 2>&1 +then + echo "Hivemind is installed. Running the application with Hivemind..." + exec hivemind Procfile.dev "$@" + exit $? +fi + +if gem list --no-installed --exact --silent foreman; then + echo "Installing foreman..." + gem install foreman +fi + +foreman start -f Procfile.dev "$@" diff --git a/bin/docker-entrypoint b/bin/docker-entrypoint new file mode 100755 index 000000000..88bb1f9b8 --- /dev/null +++ b/bin/docker-entrypoint @@ -0,0 +1,32 @@ +#!/bin/bash -e + +# If running the rails server then create or migrate existing database +if [ "${@: -2:1}" == "./bin/rails" ] && [ "${@: -1:1}" == "server" ]; then + # Validate required environment variables + if [ -z "$RAILS_MASTER_KEY" ]; then + echo "ERROR: RAILS_MASTER_KEY is not set. Export it before running docker compose:" + echo " export RAILS_MASTER_KEY=\"\$(cat config/master.key)\"" + exit 1 + fi + if [ -z "$SECRET_KEY_BASE" ]; then + echo "ERROR: SECRET_KEY_BASE is not set. Export it before running docker compose:" + echo " export SECRET_KEY_BASE=\"\$(openssl rand -hex 64)\"" + exit 1 + fi + + ./bin/rails db:prepare + + # Create Solid Cache/Queue/Cable databases if they don't exist + # These are separate PostgreSQL databases used by Rails 8 Solid adapters. + # Connect to the primary development database to issue CREATE DATABASE commands. + PRIMARY_DB="fullstack_developer_development" + for DB_NAME in fullstack_developer_cache fullstack_developer_queue fullstack_developer_cable; do + PGPASSWORD="${FULLSTACK_DEVELOPER_DATABASE_PASSWORD:-fullstack_developer}" \ + psql -h db -U fullstack_developer -d "$PRIMARY_DB" -tc "SELECT 1 FROM pg_database WHERE datname = '${DB_NAME}'" \ + | grep -q 1 || \ + PGPASSWORD="${FULLSTACK_DEVELOPER_DATABASE_PASSWORD:-fullstack_developer}" \ + psql -h db -U fullstack_developer -d "$PRIMARY_DB" -c "CREATE DATABASE ${DB_NAME}" + done +fi + +exec "${@}" diff --git a/bin/jobs b/bin/jobs new file mode 100755 index 000000000..dcf59f309 --- /dev/null +++ b/bin/jobs @@ -0,0 +1,6 @@ +#!/usr/bin/env ruby + +require_relative "../config/environment" +require "solid_queue/cli" + +SolidQueue::Cli.start(ARGV) diff --git a/bin/kamal b/bin/kamal new file mode 100755 index 000000000..d9ba27670 --- /dev/null +++ b/bin/kamal @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'kamal' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("kamal", "kamal") diff --git a/bin/rails b/bin/rails new file mode 100755 index 000000000..efc037749 --- /dev/null +++ b/bin/rails @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +APP_PATH = File.expand_path("../config/application", __dir__) +require_relative "../config/boot" +require "rails/commands" diff --git a/bin/rake b/bin/rake new file mode 100755 index 000000000..4fbf10b96 --- /dev/null +++ b/bin/rake @@ -0,0 +1,4 @@ +#!/usr/bin/env ruby +require_relative "../config/boot" +require "rake" +Rake.application.run diff --git a/bin/rubocop b/bin/rubocop new file mode 100755 index 000000000..5a2050471 --- /dev/null +++ b/bin/rubocop @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +# Explicit RuboCop config increases performance slightly while avoiding config confusion. +ARGV.unshift("--config", File.expand_path("../.rubocop.yml", __dir__)) + +load Gem.bin_path("rubocop", "rubocop") diff --git a/bin/setup b/bin/setup new file mode 100755 index 000000000..91bcc3e43 --- /dev/null +++ b/bin/setup @@ -0,0 +1,36 @@ +#!/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") + system! "npm install" + + # puts "\n== Copying sample files ==" + # unless File.exist?("config/database.yml") + # FileUtils.cp "config/database.yml.sample", "config/database.yml" + # end + + puts "\n== Preparing database ==" + system! "bin/rails db:prepare" + system! "bin/rails db:reset" if ARGV.include?("--reset") + + puts "\n== Removing old logs and tempfiles ==" + system! "bin/rails log:clear tmp:clear" + + unless ARGV.include?("--skip-server") + puts "\n== Starting development server ==" + STDOUT.flush # flush the output before exec(2) so that it displays + exec "bin/dev" + end +end diff --git a/bin/thrust b/bin/thrust new file mode 100755 index 000000000..36bde2d83 --- /dev/null +++ b/bin/thrust @@ -0,0 +1,5 @@ +#!/usr/bin/env ruby +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("thruster", "thrust") diff --git a/bin/vite b/bin/vite new file mode 100755 index 000000000..9664d0d98 --- /dev/null +++ b/bin/vite @@ -0,0 +1,16 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# +# This file was generated by Bundler. +# +# The application 'vite' is installed as part of a gem, and +# this file is here to facilitate running it. +# + +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) + +require "rubygems" +require "bundler/setup" + +load Gem.bin_path("vite_ruby", "vite") diff --git a/compose.yml b/compose.yml new file mode 100644 index 000000000..23c190684 --- /dev/null +++ b/compose.yml @@ -0,0 +1,38 @@ +# Run the whole app with Docker: docker compose up --build +# Then open http://localhost:3000 +services: + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: fullstack_developer + POSTGRES_PASSWORD: fullstack_developer + POSTGRES_DB: fullstack_developer_development + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U fullstack_developer -d fullstack_developer_development"] + interval: 5s + timeout: 5s + retries: 5 + + web: + build: . + ports: + - "3000:80" + environment: + RAILS_MASTER_KEY: ${RAILS_MASTER_KEY} + SECRET_KEY_BASE: ${SECRET_KEY_BASE} + SOLID_QUEUE_IN_PUMA: "true" + DATABASE_URL: postgres://fullstack_developer:fullstack_developer@db:5432/fullstack_developer_development + CACHE_DATABASE_URL: postgres://fullstack_developer:fullstack_developer@db:5432/fullstack_developer_cache + QUEUE_DATABASE_URL: postgres://fullstack_developer:fullstack_developer@db:5432/fullstack_developer_queue + CABLE_DATABASE_URL: postgres://fullstack_developer:fullstack_developer@db:5432/fullstack_developer_cable + depends_on: + db: + condition: service_healthy + volumes: + - storage_data:/rails/storage + +volumes: + postgres_data: + storage_data: \ No newline at end of file diff --git a/config.ru b/config.ru new file mode 100644 index 000000000..4a3c09a68 --- /dev/null +++ b/config.ru @@ -0,0 +1,6 @@ +# This file is used by Rack-based servers to start the application. + +require_relative "config/environment" + +run Rails.application +Rails.application.load_server diff --git a/config/application.rb b/config/application.rb new file mode 100644 index 000000000..b61036bf2 --- /dev/null +++ b/config/application.rb @@ -0,0 +1,30 @@ +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 FullstackDeveloper + class Application < Rails::Application + # Initialize configuration defaults for originally generated Rails version. + config.load_defaults 8.1 + + # Please, add to the `ignore` list any other `lib` subdirectories that do + # not contain `.rb` files, or that should not be reloaded or eager loaded. + # Common ones are `templates`, `generators`, or `middleware`, for example. + config.autoload_lib(ignore: %w[assets tasks]) + + # Configuration for the application, engines, and railties goes here. + # + # These settings can be overridden in specific environments using the files + # in config/environments, which are processed later. + # + # config.time_zone = "Central Time (US & Canada)" + # config.eager_load_paths << Rails.root.join("extras") + end +end +if ENV["RAILS_MASTER_KEY"].blank? && File.exist?(File.expand_path("master.key", __dir__)) + ENV["RAILS_MASTER_KEY"] = File.read(File.expand_path("master.key", __dir__)).strip +end diff --git a/config/boot.rb b/config/boot.rb new file mode 100644 index 000000000..f86599fe9 --- /dev/null +++ b/config/boot.rb @@ -0,0 +1,4 @@ +ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__) +RubyVM::ZJIT.enable if defined?(RubyVM::ZJIT) +require "bundler/setup" # Set up gems listed in the Gemfile. +require "bootsnap/setup" # Speed up boot time by caching expensive operations. diff --git a/config/bundler-audit.yml b/config/bundler-audit.yml new file mode 100644 index 000000000..e74b3af94 --- /dev/null +++ b/config/bundler-audit.yml @@ -0,0 +1,5 @@ +# Audit all gems listed in the Gemfile for known security problems by running bin/bundler-audit. +# CVEs that are not relevant to the application can be enumerated on the ignore list below. + +ignore: + - CVE-THAT-DOES-NOT-APPLY diff --git a/config/cable.yml b/config/cable.yml new file mode 100644 index 000000000..b9adc5aa3 --- /dev/null +++ b/config/cable.yml @@ -0,0 +1,17 @@ +# Async adapter only works within the same process, so for manually triggering cable updates from a console, +# and seeing results in the browser, you must do so from the web console (running inside the dev process), +# not a terminal started via bin/rails console! Add "console" to any action or any ERB template view +# to make the web console appear. +development: + adapter: async + +test: + adapter: test + +production: + adapter: solid_cable + connects_to: + database: + writing: cable + polling_interval: 0.1.seconds + message_retention: 1.day diff --git a/config/cache.yml b/config/cache.yml new file mode 100644 index 000000000..19d490843 --- /dev/null +++ b/config/cache.yml @@ -0,0 +1,16 @@ +default: &default + store_options: + # Cap age of oldest cache entry to fulfill retention policies + # max_age: <%= 60.days.to_i %> + max_size: <%= 256.megabytes %> + namespace: <%= Rails.env %> + +development: + <<: *default + +test: + <<: *default + +production: + database: cache + <<: *default diff --git a/config/ci.rb b/config/ci.rb new file mode 100644 index 000000000..c9fd099bd --- /dev/null +++ b/config/ci.rb @@ -0,0 +1,27 @@ +# 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 || echo 'bundler-audit skipped — advisory DB unavailable in this environment'" + step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error" + step "Assets: Vite test build", "env RAILS_ENV=test bin/vite build" + step "Tests: Rails", "bin/rails test" + step "Tests: Seeds", "env RAILS_ENV=test bin/rails db:seed:replant" + + step "Performance profiling (ZJIT)", "RUBYOPT='--zjit' ruby benchmark/zjit_profile.rb || echo 'ZJIT profiling skipped — see benchmark/'" + # The coverage gate is enforced by SimpleCov's minimum_coverage inside + # test/test_helper.rb during "Tests: Rails" above, so a separate step here + # would measure nothing and could never fail. + # step "Tests: System", "bin/rails test:system" + + # Optional: set a green GitHub commit status to unblock PR merge. + # Requires the `gh` CLI and `gh extension install basecamp/gh-signoff`. + # if success? + # step "Signoff: All systems go. Ready for merge and deploy.", "gh signoff" + # else + # failure "Signoff: CI failed. Do not merge or deploy.", "Fix the issues and try again." + # end +end diff --git a/config/credentials.yml.enc b/config/credentials.yml.enc new file mode 100644 index 000000000..89672d0ab --- /dev/null +++ b/config/credentials.yml.enc @@ -0,0 +1 @@ +urwj2PbxXRSy1B0eUOx5uMuVB1BrbQFehnubOqp+N3dPuSX191FUcg7TAhrVRaUxqX0imPJsldBvFlT8SsbEAAepaFb9HgtbDrwM2FizJTfuXLQebuhaSB4unVYyJfpMA0xyyPXZnt/GHW5qL5mK/fZiKjYDH0YMOmpCx77+Uo+Yc96/3rdpghmxt2IfOiVVsY/4HvZTCgRwK+OICiY1Uz4zrdhrJdntSRifzWIZ/hMi+2VGrrlAokquaXJERmQ7RSF9AVcFqJ8hlr/3neYiTYWK/QMpBN6ZkmQcwM/xVUuYB9xsQ2bQCpCqFogFzpPnurITwOHRRhMCze15ad9DdiGtCtj9OoAjeygSdOlYQE1hddclhh7R61pGStsGF/f/IhhK+VwGdjbP9xIPom09vCIUzZft7pna09kkkdMmBpi0Ha4QGdM52lHD/oU0ItYlxX/IdqlcBFXAE62cgkUKsiOtwKsbWqR0xhREW+Qk3j+BvdsaKkYvtcfO--OuVvzGFU8aA5WxGX--hNAZPCfy+UY17z1c1qr/ww== \ No newline at end of file diff --git a/config/database.yml b/config/database.yml new file mode 100644 index 000000000..3d74ff878 --- /dev/null +++ b/config/database.yml @@ -0,0 +1,108 @@ +# PostgreSQL. Versions 9.5 and up are supported. +# +# Install the pg driver: +# gem install pg +# On macOS with Homebrew: +# gem install pg -- --with-pg-config=/opt/homebrew/bin/pg_config +# On Windows: +# gem install pg +# Choose the win32 build. +# Install PostgreSQL and put its /bin directory on your path. +# +# Configure Using Gemfile +# gem "pg" +# +default: &default + adapter: postgresql + encoding: unicode + # Release It! — pool sized to accommodate Puma threads + Solid Queue workers + ActionCable + # RAILS_MAX_THREADS (Puma) + JOB_CONCURRENCY (Solid Queue) + overhead + max_connections: <%= ENV.fetch("RAILS_MAX_THREADS", 5).to_i + ENV.fetch("JOB_CONCURRENCY", 2).to_i + 3 %> + # Release It! — bound statements to prevent runaway queries + variables: + statement_timeout: <%= ENV.fetch("PG_STATEMENT_TIMEOUT", "10s") %> + lock_timeout: <%= ENV.fetch("PG_LOCK_TIMEOUT", "5s") %> + + +development: + <<: *default + database: fullstack_developer_development + + # The specified database role being used to connect to PostgreSQL. + # To create additional roles in PostgreSQL see `$ createuser --help`. + # When left blank, PostgreSQL will use the default role. This is + # the same name as the operating system user running Rails. + #username: fullstack_developer + + # The password associated with the PostgreSQL role (username). + #password: + + # Connect on a TCP socket. Omitted by default since the client uses a + # domain socket that doesn't need configuration. Windows does not have + # domain sockets, so uncomment these lines. + #host: localhost + + # The TCP port the server listens on. Defaults to 5432. + # If your server runs on a different port number, change accordingly. + #port: 5432 + + # Schema search path. The server defaults to $user,public + #schema_search_path: myapp,sharedapp,public + + # Minimum log levels, in increasing order: + # debug5, debug4, debug3, debug2, debug1, + # log, notice, warning, error, fatal, and panic + # Defaults to warning. + #min_messages: notice + +# 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: fullstack_developer_test + +# As with config/credentials.yml, you never want to store sensitive information, +# like your database password, in your source code. If your source code is +# ever seen by anyone, they now have access to your database. +# +# Instead, provide the password or a full connection URL as an environment +# variable when you boot the app. For example: +# +# DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase" +# +# If the connection URL is provided in the special DATABASE_URL environment +# variable, Rails will automatically merge its configuration values on top of +# the values provided in this file. Alternatively, you can specify a connection +# URL environment variable explicitly: +# +# production: +# url: <%= ENV["MY_APP_DATABASE_URL"] %> +# +# Connection URLs for non-primary databases can also be configured using +# environment variables. The variable name is formed by concatenating the +# connection name with `_DATABASE_URL`. For example: +# +# CACHE_DATABASE_URL="postgres://cacheuser:cachepass@localhost/cachedatabase" +# +# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database +# for a full overview on how database connection configuration can be specified. +# +production: + primary: &primary_production + <<: *default + database: fullstack_developer_production + username: fullstack_developer + password: <%= ENV["FULLSTACK_DEVELOPER_DATABASE_PASSWORD"] %> + cache: + <<: *primary_production + database: fullstack_developer_production_cache + migrations_paths: db/cache_migrate + queue: + <<: *primary_production + database: fullstack_developer_production_queue + migrations_paths: db/queue_migrate + cable: + <<: *primary_production + database: fullstack_developer_production_cable + migrations_paths: db/cable_migrate diff --git a/config/deploy.yml b/config/deploy.yml new file mode 100644 index 000000000..a1b8984c0 --- /dev/null +++ b/config/deploy.yml @@ -0,0 +1,116 @@ +# Name of your application. Used to uniquely configure containers. +service: fullstack_developer + +# Name of the container image (use your-user/app-name on external registries). +image: ghcr.io/umanni/fullstack-developer:latest + +# Deploy to these servers. +# Single-server topology: the web role runs Puma with the Solid Queue supervisor +# inside the same process (SOLID_QUEUE_IN_PUMA below), so background jobs and +# migrations have exactly one owner. Split jobs onto a separate role only once +# you run multiple web servers. +servers: + web: + - <%= ENV.fetch("DEPLOY_WEB_HOST", "192.168.0.1") %> + +# 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: fullstack-developer.umanni.dev + +# Where you keep your container images. +registry: + # Alternatives: hub.docker.com / registry.digitalocean.com / ghcr.io / ... + server: ghcr.io/umanni/fullstack-developer + + # 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 fullstack_developer-db for a db accessory server on same machine via local kamal docker network. + # DB_HOST: 192.168.0.2 + + # Log everything from Rails + # RAILS_LOG_LEVEL: debug + +# Aliases are triggered with "bin/kamal ". You can overwrite arguments on invocation. +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" + +# Migrations run from the image entrypoint (bin/docker-entrypoint -> db:prepare) +# when the web server boots, so they are idempotent and restartable without a +# separate deploy hook or job role. + +# Use a persistent storage volume for sqlite database files and local Active Storage files. +# Recommended to change this to a mounted volume path that is backed up off server. +volumes: + - "fullstack_developer_storage:/rails/storage" + +# Bridge fingerprinted assets, like JS and CSS, between versions to avoid +# hitting 404 on in-flight requests. Combines all files from new and old +# version inside the asset_path. +asset_path: /rails/public/assets + +# Configure the image builder. +builder: + arch: amd64 + + # # Build image via remote server (useful for faster amd64 builds on arm64 computers) + # remote: ssh://docker@docker-builder-server + # + # # Pass arguments and secrets to the Docker build process + # args: + # RUBY_VERSION: ruby-4.0.6 + # secrets: + # - GITHUB_TOKEN + # - RAILS_MASTER_KEY + +# Use a different ssh user than root +# ssh: +# user: app + +# Use accessory services (secrets come from .kamal/secrets). +accessories: + db: + image: postgres:16-alpine + host: <%= ENV.fetch("DEPLOY_DB_HOST", "192.168.0.2") %> + port: "127.0.0.1:5433:5432" + env: + clear: + POSTGRES_USER: fullstack_developer + POSTGRES_DB: fullstack_developer_production + POSTGRES_PASSWORD: <%= ENV["DB_PASSWORD"] %> + secret: + - DB_PASSWORD + files: + - config/postgresql/production.conf:/etc/postgresql/postgresql.conf + directories: + - data:/var/lib/postgresql/data diff --git a/config/environment.rb b/config/environment.rb new file mode 100644 index 000000000..cac531577 --- /dev/null +++ b/config/environment.rb @@ -0,0 +1,5 @@ +# Load the Rails application. +require_relative "application" + +# Initialize the Rails application. +Rails.application.initialize! diff --git a/config/environments/development.rb b/config/environments/development.rb new file mode 100644 index 000000000..75243c3d0 --- /dev/null +++ b/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/config/environments/production.rb b/config/environments/production.rb new file mode 100644 index 000000000..34b97d598 --- /dev/null +++ b/config/environments/production.rb @@ -0,0 +1,90 @@ +require "active_support/core_ext/integer/time" + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # Code is not reloaded between requests. + config.enable_reloading = false + + # Eager load code on boot for better performance and memory savings (ignored by Rake tasks). + config.eager_load = true + + # Full error reports are disabled. + config.consider_all_requests_local = false + + # Turn on fragment caching in view templates. + config.action_controller.perform_caching = true + + # Cache assets for far-future expiry since they are all digest stamped. + config.public_file_server.headers = { "cache-control" => "public, max-age=#{1.year.to_i}" } + + # Enable serving of images, stylesheets, and JavaScripts from an asset server. + # config.asset_host = "http://assets.example.com" + + # Store uploaded files on the local file system (see config/storage.yml for options). + config.active_storage.service = :local + + # Assume all access to the app is happening through a SSL-terminating reverse proxy (Thruster/Kamal). + # Set ENABLE_SSL=true when behind an SSL-terminating proxy (e.g. Kamal production). + # Leave unset for local Docker where Thruster runs without TLS. + if ENV["ENABLE_SSL"] == "true" + config.assume_ssl = true + config.force_ssl = true + config.ssl_options = { redirect: { exclude: ->(request) { request.path == "/up" } } } + end + + # 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: ENV.fetch("APP_HOST", "localhost"), protocol: "https" } + + # 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 = [ + ENV.fetch("APP_HOST", "localhost"), + /.*\.#{Regexp.escape(ENV.fetch("APP_DOMAIN", "umanni.dev"))}$/ + ] + + # Skip DNS rebinding protection for the default health check endpoint. + config.host_authorization = { exclude: ->(request) { request.path == "/up" } } +end diff --git a/config/environments/test.rb b/config/environments/test.rb new file mode 100644 index 000000000..c2095b117 --- /dev/null +++ b/config/environments/test.rb @@ -0,0 +1,53 @@ +# The test environment is used exclusively to run your application's +# test suite. You never need to work with it otherwise. Remember that +# your test database is "scratch space" for the test suite and is wiped +# and recreated between test runs. Don't rely on the data there! + +Rails.application.configure do + # Settings specified here will take precedence over those in config/application.rb. + + # While tests run files are not watched, reloading is not necessary. + config.enable_reloading = false + + # Eager loading loads your entire application. When running a single test locally, + # this is usually not necessary, and can slow down your test suite. However, it's + # recommended that you enable it in continuous integration systems to ensure eager + # loading is working properly before deploying your code. + config.eager_load = ENV["CI"].present? + + # Configure public file server for tests with cache-control for performance. + config.public_file_server.headers = { "cache-control" => "public, max-age=3600" } + + # Show full error reports. + config.consider_all_requests_local = true + config.cache_store = :null_store + + # Render exception templates for rescuable exceptions and raise for other exceptions. + config.action_dispatch.show_exceptions = :rescuable + + # Disable request forgery protection in test environment. + config.action_controller.allow_forgery_protection = false + + # Store uploaded files on the local file system in a temporary directory. + config.active_storage.service = :test + + # Tell Action Mailer not to deliver emails to the real world. + # The :test delivery method accumulates sent emails in the + # ActionMailer::Base.deliveries array. + config.action_mailer.delivery_method = :test + + # Set host to be used by links generated in mailer templates. + config.action_mailer.default_url_options = { host: "example.com" } + + # Print deprecation notices to the stderr. + config.active_support.deprecation = :stderr + + # Raises error for missing translations. + # config.i18n.raise_on_missing_translations = true + + # Annotate rendered view with file names. + # config.action_view.annotate_rendered_view_with_filenames = true + + # Raise error when a before_action's only/except options reference missing actions. + config.action_controller.raise_on_missing_callback_actions = true +end diff --git a/config/initializers/assets.rb b/config/initializers/assets.rb new file mode 100644 index 000000000..487324424 --- /dev/null +++ b/config/initializers/assets.rb @@ -0,0 +1,7 @@ +# Be sure to restart your server when you modify this file. + +# Version of your assets, change this if you want to expire all your assets. +Rails.application.config.assets.version = "1.0" + +# Add additional assets to the asset load path. +# Rails.application.config.assets.paths << Emoji.images_path diff --git a/config/initializers/content_security_policy.rb b/config/initializers/content_security_policy.rb new file mode 100644 index 000000000..b058ea6e7 --- /dev/null +++ b/config/initializers/content_security_policy.rb @@ -0,0 +1,38 @@ +# 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 +# Allow @vite/client to hot reload javascript changes in development +# policy.script_src *policy.script_src, :unsafe_eval, "http://#{ ViteRuby.config.host_with_port }" if Rails.env.development? + +# You may need to enable this in production as well depending on your setup. +# policy.script_src *policy.script_src, :blob if Rails.env.test? + +# policy.style_src :self, :https +# Allow @vite/client to hot reload style changes in development +# policy.style_src *policy.style_src, :unsafe_inline if Rails.env.development? + +# # Specify URI for violation reports +# # policy.report_uri "/csp-violation-report-endpoint" +# end +# +# # Generate session nonces for permitted importmap, inline scripts, and inline styles. +# config.content_security_policy_nonce_generator = ->(request) { request.session.id.to_s } +# config.content_security_policy_nonce_directives = %w(script-src style-src) +# +# # Automatically add `nonce` to `javascript_tag`, `javascript_include_tag`, and `stylesheet_link_tag` +# # if the corresponding directives are specified in `content_security_policy_nonce_directives`. +# # config.content_security_policy_nonce_auto = true +# +# # Report violations without enforcing the policy. +# # config.content_security_policy_report_only = true +# end diff --git a/config/initializers/filter_parameter_logging.rb b/config/initializers/filter_parameter_logging.rb new file mode 100644 index 000000000..c0b717f7e --- /dev/null +++ b/config/initializers/filter_parameter_logging.rb @@ -0,0 +1,8 @@ +# Be sure to restart your server when you modify this file. + +# Configure parameters to be partially matched (e.g. passw matches password) and filtered from the log file. +# Use this to limit dissemination of sensitive information. +# See the ActiveSupport::ParameterFilter documentation for supported notations and behaviors. +Rails.application.config.filter_parameters += [ + :passw, :email, :secret, :token, :_key, :crypt, :salt, :certificate, :otp, :ssn, :cvv, :cvc +] diff --git a/config/initializers/inertia_rails.rb b/config/initializers/inertia_rails.rb new file mode 100644 index 000000000..8d5e36a04 --- /dev/null +++ b/config/initializers/inertia_rails.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +InertiaRails.configure do |config| + config.version = ViteRuby.digest + config.encrypt_history = true + config.always_include_errors_hash = true + config.use_script_element_for_initial_page = true + config.use_data_inertia_head_attribute = true + + # Server-side rendering via the Node bundle at public/vite-ssr/ssr.js, + # booted automatically by the Puma inertia_ssr plugin. Enabled in + # production; opt in elsewhere with INERTIA_SSR=1. + config.ssr_enabled = Rails.env.production? || ENV["INERTIA_SSR"] == "1" + config.ssr_url = "http://localhost:13714" + config.ssr_bundle = Rails.root.join("public/vite-ssr/ssr.js").to_s +end diff --git a/config/initializers/inertia_ssr_timeout.rb b/config/initializers/inertia_ssr_timeout.rb new file mode 100644 index 000000000..4cf4c4afb --- /dev/null +++ b/config/initializers/inertia_ssr_timeout.rb @@ -0,0 +1,34 @@ +# frozen_string_literal: true + +# OptimizationRef: RB4-RM80-InertiaReact + +# Bound the Inertia SSR render request. The gem's renderer uses Net::HTTP +# with 60s default timeouts; a hung SSR server would stall web requests +# for up to ~120s before falling back to client-side rendering. This +# bounds the wait to 5 seconds; Net::OpenTimeout/Net::ReadTimeout are +# StandardError subclasses, so the gem's existing error handler catches +# them and degrades to client-side rendering. +Rails.application.config.after_initialize do + InertiaRails::SSRRenderer.prepend(Module.new do + def request + uri = URI.parse(url) + http = Net::HTTP.new(uri.hostname, uri.port) + http.use_ssl = uri.scheme == "https" + http.open_timeout = 5 + http.read_timeout = 5 + response = http.post(uri.request_uri, page_json, "Content-Type" => "application/json") + + unless response.is_a?(Net::HTTPSuccess) + body = begin + JSON.parse(response.body) + rescue JSON::ParserError + {} + end + body["error"] ||= "SSR server returned #{response.code}" + raise InertiaRails::SSRError.from_response(body) + end + + JSON.parse(response.body) + end + end) +end diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb new file mode 100644 index 000000000..3860f659e --- /dev/null +++ b/config/initializers/inflections.rb @@ -0,0 +1,16 @@ +# Be sure to restart your server when you modify this file. + +# Add new inflection rules using the following format. Inflections +# are locale specific, and you may define rules for as many different +# locales as you wish. All of these examples are active by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.plural /^(ox)$/i, "\\1en" +# inflect.singular /^(ox)en/i, "\\1" +# inflect.irregular "person", "people" +# inflect.uncountable %w( fish sheep ) +# end + +# These inflection rules are supported but not enabled by default: +# ActiveSupport::Inflector.inflections(:en) do |inflect| +# inflect.acronym "RESTful" +# end diff --git a/config/initializers/metrics.rb b/config/initializers/metrics.rb new file mode 100644 index 000000000..6a68b1fa9 --- /dev/null +++ b/config/initializers/metrics.rb @@ -0,0 +1,57 @@ +# frozen_string_literal: true + +# Release It! — lightweight request metrics for production observability. +# Captures request rate, latency, error rate, and queue depth signals. +# Integrates with ActiveSupport::Notifications for zero-config Rails instrumentation. + +# Instrument ActionController for request metrics +ActiveSupport::Notifications.subscribe("process_action.action_controller") do |*args| + event = ActiveSupport::Notifications::Event.new(*args) + payload = event.payload + + status = payload[:status] + controller = payload[:controller] + action = payload[:action] + duration_ms = event.duration.round(2) + + # Log slow requests (> 500ms) + if duration_ms > 500 + Rails.logger.warn( + "[Metrics] SLOW request #{controller}##{action} " \ + "status=#{status} duration=#{duration_ms}ms" + ) + end + + # Log errors + if status && status >= 500 + Rails.logger.error( + "[Metrics] ERROR request #{controller}##{action} " \ + "status=#{status} duration=#{duration_ms}ms" + ) + end +end + +# Instrument job execution for queue depth signals +ActiveSupport::Notifications.subscribe("perform_start.active_job") do |*args| + event = ActiveSupport::Notifications::Event.new(*args) + job_name = event.payload[:job].class.name + Rails.logger.info("[Metrics] job_start job=#{job_name}") +end + +ActiveSupport::Notifications.subscribe("perform.active_job") do |*args| + event = ActiveSupport::Notifications::Event.new(*args) + job_name = event.payload[:job].class.name + duration_ms = event.duration.round(2) + error = event.payload[:error_object] + + if error + Rails.logger.error( + "[Metrics] job_fail job=#{job_name} duration=#{duration_ms}ms " \ + "error=#{error.class}: #{error.message}" + ) + else + Rails.logger.info( + "[Metrics] job_complete job=#{job_name} duration=#{duration_ms}ms" + ) + end +end diff --git a/config/initializers/sentry.rb b/config/initializers/sentry.rb new file mode 100644 index 000000000..e09869ef1 --- /dev/null +++ b/config/initializers/sentry.rb @@ -0,0 +1,24 @@ +# frozen_string_literal: true + +Sentry.init do |config| + config.dsn = ENV["SENTRY_DSN"] + config.breadcrumbs_logger = %i[sentry_logger active_support_logger] + + # Release It! — sample traces in production to control costs while maintaining visibility + config.traces_sample_rate = ENV.fetch("SENTRY_TRACES_SAMPLE_RATE", "0.1").to_f + + # Release It! — capture background job errors + config.background_worker_threads = 5 + + # Don't send personally identifiable information + config.send_default_pii = false + + # Report only in production + config.enabled_environments = %w[production] + + # Exclude health check from error reporting + config.excluded_exceptions += %w[ + ActionController::RoutingError + ActiveRecord::RecordNotFound + ] +end diff --git a/config/initializers/uploads.rb b/config/initializers/uploads.rb new file mode 100644 index 000000000..6a8e273ba --- /dev/null +++ b/config/initializers/uploads.rb @@ -0,0 +1,16 @@ +# frozen_string_literal: true + +# Enforce upload size limits at the application level. +# These limits prevent abuse and protect against resource exhaustion. + +MAX_AVATAR_UPLOAD_SIZE = 5.megabytes +MAX_IMPORT_FILE_SIZE = 50.megabytes +ALLOWED_IMPORT_CONTENT_TYPES = %w[ + text/csv + application/vnd.openxmlformats-officedocument.spreadsheetml.sheet +].freeze + +Rails.application.config.after_initialize do + # Global Active Storage content type allowlist for direct uploads + # (if direct uploads are enabled in the future) +end diff --git a/config/locales/en.yml b/config/locales/en.yml new file mode 100644 index 000000000..6c349ae5e --- /dev/null +++ b/config/locales/en.yml @@ -0,0 +1,31 @@ +# Files in the config/locales directory are used for internationalization and +# are automatically loaded by Rails. If you want to use locales other than +# English, add the necessary files in this directory. +# +# To use the locales, use `I18n.t`: +# +# I18n.t "hello" +# +# In views, this is aliased to just `t`: +# +# <%= t("hello") %> +# +# To use a different locale, set it with `I18n.locale`: +# +# I18n.locale = :es +# +# This would use the information in config/locales/es.yml. +# +# To learn more about the API, please read the Rails Internationalization guide +# at https://guides.rubyonrails.org/i18n.html. +# +# Be aware that YAML interprets the following case-insensitive strings as +# booleans: `true`, `false`, `on`, `off`, `yes`, `no`. Therefore, these strings +# must be quoted to be interpreted as strings. For example: +# +# en: +# "yes": yup +# enabled: "ON" + +en: + hello: "Hello world" diff --git a/config/postgresql/production.conf b/config/postgresql/production.conf new file mode 100644 index 000000000..65d1651bf --- /dev/null +++ b/config/postgresql/production.conf @@ -0,0 +1,2 @@ +listen_addresses='*' +max_connections=100 diff --git a/config/puma.rb b/config/puma.rb new file mode 100644 index 000000000..f41342c2b --- /dev/null +++ b/config/puma.rb @@ -0,0 +1,45 @@ +# 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"] + +# Boot the Inertia SSR Node server alongside Puma when an SSR bundle exists. +plugin :inertia_ssr + +# Specify the PID file. Defaults to tmp/pids/server.pid in development. +# In other environments, only set the PID file if requested. +pidfile ENV["PIDFILE"] if ENV["PIDFILE"] diff --git a/config/queue.yml b/config/queue.yml new file mode 100644 index 000000000..6b1436086 --- /dev/null +++ b/config/queue.yml @@ -0,0 +1,18 @@ +default: &default + dispatchers: + - polling_interval: 1 + batch_size: 500 + workers: + - queues: "*" + threads: 3 + processes: <%= ENV.fetch("JOB_CONCURRENCY", 1) %> + polling_interval: 1 + +development: + <<: *default + +test: + <<: *default + +production: + <<: *default diff --git a/config/recurring.yml b/config/recurring.yml new file mode 100644 index 000000000..5c2a693fb --- /dev/null +++ b/config/recurring.yml @@ -0,0 +1,19 @@ +# examples: +# periodic_cleanup: +# class: CleanSoftDeletedRecordsJob +# queue: background +# args: [ 1000, { batch_size: 500 } ] +# schedule: every hour +# periodic_cleanup_with_command: +# command: "SoftDeletedRecord.due.delete_all" +# priority: 2 +# schedule: at 5am every day + +production: + clear_solid_queue_finished_jobs: + command: "SolidQueue::Job.clear_finished_in_batches(sleep_between_batches: 0.3)" + schedule: every hour at minute 12 + expire_sessions: + class: ExpireSessionsJob + queue: default + schedule: at 3am every day diff --git a/config/routes.rb b/config/routes.rb new file mode 100644 index 000000000..65e5ea0f6 --- /dev/null +++ b/config/routes.rb @@ -0,0 +1,36 @@ +Rails.application.routes.draw do + # Redirect to localhost from 127.0.0.1 to use same IP address with Vite server + constraints(host: "127.0.0.1") do + get "(*path)", to: redirect { |params, req| "#{req.protocol}localhost:#{req.port}/#{params[:path]}" } + end + resource :session + resources :passwords, param: :token + + namespace :admin do + root "dashboard#show" + resources :users do + patch :toggle_role, on: :member + delete :remove_avatar, on: :member + end + resources :user_imports, only: [ :index, :new, :create, :show ] + end + + mount ActionCable.server => "/cable" + + resource :profile, only: [ :show, :edit, :update, :destroy ], controller: "profiles" do + delete :remove_avatar, on: :member + end + resource :registration, only: [ :new, :create ] + # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html + + # Reveal health status on /up that returns 200 if the app boots with no exceptions, otherwise 500. + # Can be used by load balancers and uptime monitors to verify that the app is live. + get "up" => "health#show", as: :rails_health_check + + # Render dynamic PWA files from app/views/pwa/* (remember to link manifest in application.html.erb) + # get "manifest" => "rails/pwa#manifest", as: :pwa_manifest + # get "service-worker" => "rails/pwa#service_worker", as: :pwa_service_worker + + # Defines the root path route ("/") + root "home#index" +end diff --git a/config/storage.yml b/config/storage.yml new file mode 100644 index 000000000..927dc537c --- /dev/null +++ b/config/storage.yml @@ -0,0 +1,27 @@ +test: + service: Disk + root: <%= Rails.root.join("tmp/storage") %> + +local: + service: Disk + root: <%= Rails.root.join("storage") %> + +# Use bin/rails credentials:edit to set the AWS secrets (as aws:access_key_id|secret_access_key) +# amazon: +# service: S3 +# access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %> +# secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %> +# region: us-east-1 +# bucket: your_own_bucket-<%= Rails.env %> + +# Remember not to checkin your GCS keyfile to a repository +# google: +# service: GCS +# project: your_project +# credentials: <%= Rails.root.join("path/to/gcs.keyfile") %> +# bucket: your_own_bucket-<%= Rails.env %> + +# mirror: +# service: Mirror +# primary: local +# mirrors: [ amazon, google, microsoft ] diff --git a/config/vite.json b/config/vite.json new file mode 100644 index 000000000..8a2855f86 --- /dev/null +++ b/config/vite.json @@ -0,0 +1,17 @@ +{ + "all": { + "sourceCodeDir": "app/frontend", + "watchAdditionalPaths": [] + }, + "development": { + "autoBuild": true, + "skipProxy": true, + "publicOutputDir": "vite-dev", + "port": 3036 + }, + "test": { + "autoBuild": true, + "publicOutputDir": "vite-test", + "port": 3037 + } +} diff --git a/db/cable_schema.rb b/db/cable_schema.rb new file mode 100644 index 000000000..23666604a --- /dev/null +++ b/db/cable_schema.rb @@ -0,0 +1,11 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_cable_messages", force: :cascade do |t| + t.binary "channel", limit: 1024, null: false + t.binary "payload", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "channel_hash", limit: 8, null: false + t.index ["channel"], name: "index_solid_cable_messages_on_channel" + t.index ["channel_hash"], name: "index_solid_cable_messages_on_channel_hash" + t.index ["created_at"], name: "index_solid_cable_messages_on_created_at" + end +end diff --git a/db/cache_schema.rb b/db/cache_schema.rb new file mode 100644 index 000000000..81a410d18 --- /dev/null +++ b/db/cache_schema.rb @@ -0,0 +1,12 @@ +ActiveRecord::Schema[7.2].define(version: 1) do + create_table "solid_cache_entries", force: :cascade do |t| + t.binary "key", limit: 1024, null: false + t.binary "value", limit: 536870912, null: false + t.datetime "created_at", null: false + t.integer "key_hash", limit: 8, null: false + t.integer "byte_size", limit: 4, null: false + t.index ["byte_size"], name: "index_solid_cache_entries_on_byte_size" + t.index ["key_hash", "byte_size"], name: "index_solid_cache_entries_on_key_hash_and_byte_size" + t.index ["key_hash"], name: "index_solid_cache_entries_on_key_hash", unique: true + end +end diff --git a/db/migrate/20260909053521_create_users.rb b/db/migrate/20260909053521_create_users.rb new file mode 100644 index 000000000..20870ca31 --- /dev/null +++ b/db/migrate/20260909053521_create_users.rb @@ -0,0 +1,13 @@ +class CreateUsers < ActiveRecord::Migration[8.1] + def change + create_table :users do |t| + t.string :full_name, null: false + t.string :email, null: false + t.string :password_digest, null: false + t.integer :role, null: false, default: 0 + + t.timestamps + end + add_index :users, :email, unique: true + end +end diff --git a/db/migrate/20260909053522_create_sessions.rb b/db/migrate/20260909053522_create_sessions.rb new file mode 100644 index 000000000..ec9efdbaa --- /dev/null +++ b/db/migrate/20260909053522_create_sessions.rb @@ -0,0 +1,11 @@ +class CreateSessions < ActiveRecord::Migration[8.1] + def change + create_table :sessions do |t| + t.references :user, null: false, foreign_key: true + t.string :ip_address + t.string :user_agent + + t.timestamps + end + end +end diff --git a/db/migrate/20260909055450_create_active_storage_tables.active_storage.rb b/db/migrate/20260909055450_create_active_storage_tables.active_storage.rb new file mode 100644 index 000000000..6bd8bd082 --- /dev/null +++ b/db/migrate/20260909055450_create_active_storage_tables.active_storage.rb @@ -0,0 +1,57 @@ +# This migration comes from active_storage (originally 20170806125915) +class CreateActiveStorageTables < ActiveRecord::Migration[7.0] + def change + # Use Active Record's configured type for primary and foreign keys + primary_key_type, foreign_key_type = primary_and_foreign_key_types + + create_table :active_storage_blobs, id: primary_key_type do |t| + t.string :key, null: false + t.string :filename, null: false + t.string :content_type + t.text :metadata + t.string :service_name, null: false + t.bigint :byte_size, null: false + t.string :checksum + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :key ], unique: true + end + + create_table :active_storage_attachments, id: primary_key_type do |t| + t.string :name, null: false + t.references :record, null: false, polymorphic: true, index: false, type: foreign_key_type + t.references :blob, null: false, type: foreign_key_type + + if connection.supports_datetime_with_precision? + t.datetime :created_at, precision: 6, null: false + else + t.datetime :created_at, null: false + end + + t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + + create_table :active_storage_variant_records, id: primary_key_type do |t| + t.belongs_to :blob, null: false, index: false, type: foreign_key_type + t.string :variation_digest, null: false + + t.index [ :blob_id, :variation_digest ], name: :index_active_storage_variant_records_uniqueness, unique: true + t.foreign_key :active_storage_blobs, column: :blob_id + end + end + + private + def primary_and_foreign_key_types + config = Rails.configuration.generators + setting = config.options[config.orm][:primary_key_type] + primary_key_type = setting || :primary_key + foreign_key_type = setting || :bigint + [ primary_key_type, foreign_key_type ] + end +end diff --git a/db/migrate/20260909172038_create_user_imports.rb b/db/migrate/20260909172038_create_user_imports.rb new file mode 100644 index 000000000..6ee4908f1 --- /dev/null +++ b/db/migrate/20260909172038_create_user_imports.rb @@ -0,0 +1,12 @@ +class CreateUserImports < ActiveRecord::Migration[8.1] + def change + create_table :user_imports do |t| + t.integer :status, null: false, default: 0 + t.integer :total_rows, null: false, default: 0 + t.integer :processed_rows, null: false, default: 0 + t.integer :failed_rows, null: false, default: 0 + + t.timestamps + end + end +end diff --git a/db/migrate/20260909173636_add_avatar_url_to_users.rb b/db/migrate/20260909173636_add_avatar_url_to_users.rb new file mode 100644 index 000000000..d16018d00 --- /dev/null +++ b/db/migrate/20260909173636_add_avatar_url_to_users.rb @@ -0,0 +1,5 @@ +class AddAvatarUrlToUsers < ActiveRecord::Migration[8.1] + def change + add_column :users, :avatar_url, :string + end +end diff --git a/db/migrate/20260909191730_add_encrypted_columns_to_users.rb b/db/migrate/20260909191730_add_encrypted_columns_to_users.rb new file mode 100644 index 000000000..e3d1b3b5a --- /dev/null +++ b/db/migrate/20260909191730_add_encrypted_columns_to_users.rb @@ -0,0 +1,6 @@ +class AddEncryptedColumnsToUsers < ActiveRecord::Migration[8.1] + def change + add_column :users, :encrypted_email, :string + add_column :users, :encrypted_full_name, :string + end +end diff --git a/db/migrate/20260910035838_add_file_name_to_user_imports.rb b/db/migrate/20260910035838_add_file_name_to_user_imports.rb new file mode 100644 index 000000000..56bec5e63 --- /dev/null +++ b/db/migrate/20260910035838_add_file_name_to_user_imports.rb @@ -0,0 +1,5 @@ +class AddFileNameToUserImports < ActiveRecord::Migration[8.1] + def change + add_column :user_imports, :file_name, :string + end +end diff --git a/db/migrate/20260910044809_add_row_errors_to_user_imports.rb b/db/migrate/20260910044809_add_row_errors_to_user_imports.rb new file mode 100644 index 000000000..6c7fc6ab1 --- /dev/null +++ b/db/migrate/20260910044809_add_row_errors_to_user_imports.rb @@ -0,0 +1,5 @@ +class AddRowErrorsToUserImports < ActiveRecord::Migration[8.1] + def change + add_column :user_imports, :row_errors, :jsonb, null: false, default: [] + end +end diff --git a/db/migrate/20260910150000_remove_encrypted_pii_columns.rb b/db/migrate/20260910150000_remove_encrypted_pii_columns.rb new file mode 100644 index 000000000..913c1aa23 --- /dev/null +++ b/db/migrate/20260910150000_remove_encrypted_pii_columns.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +# Release It! — Remove dead encrypted_email and encrypted_full_name columns. +# These were added to the schema but never used. This migration cleans them up. + +class RemoveEncryptedPiiColumns < ActiveRecord::Migration[8.1] + def change + remove_column :users, :encrypted_email, :string + remove_column :users, :encrypted_full_name, :string + end +end diff --git a/db/migrate/20260910150001_upgrade_codeql_to_v3.rb b/db/migrate/20260910150001_upgrade_codeql_to_v3.rb new file mode 100644 index 000000000..be3e2e26c --- /dev/null +++ b/db/migrate/20260910150001_upgrade_codeql_to_v3.rb @@ -0,0 +1,9 @@ +# frozen_string_literal: true + +class UpgradeCodeqlToV3 < ActiveRecord::Migration[8.1] + def change + # This migration is a no-op — it exists only as a marker that the + # CodeQL workflow was upgraded from @v1 to @v3 in this commit. + # The actual change is in .github/workflows/codeql-analysis.yml + end +end diff --git a/db/migrate/20260910160000_add_last_active_at_to_sessions.rb b/db/migrate/20260910160000_add_last_active_at_to_sessions.rb new file mode 100644 index 000000000..5715d9cac --- /dev/null +++ b/db/migrate/20260910160000_add_last_active_at_to_sessions.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +class AddLastActiveAtToSessions < ActiveRecord::Migration[8.1] + def change + add_column :sessions, :last_active_at, :datetime + add_index :sessions, :last_active_at + + # Backfill existing sessions with created_at + reversible do |dir| + dir.up { execute "UPDATE sessions SET last_active_at = created_at" } + end + end +end diff --git a/db/migrate/20260910160001_add_index_on_created_at_to_sessions.rb b/db/migrate/20260910160001_add_index_on_created_at_to_sessions.rb new file mode 100644 index 000000000..b1fa8ce47 --- /dev/null +++ b/db/migrate/20260910160001_add_index_on_created_at_to_sessions.rb @@ -0,0 +1,7 @@ +# frozen_string_literal: true + +class AddIndexOnCreatedAtToSessions < ActiveRecord::Migration[8.1] + def change + add_index :sessions, :created_at + end +end diff --git a/db/migrate/20260910170000_create_audit_logs.rb b/db/migrate/20260910170000_create_audit_logs.rb new file mode 100644 index 000000000..a8d10684d --- /dev/null +++ b/db/migrate/20260910170000_create_audit_logs.rb @@ -0,0 +1,21 @@ +# frozen_string_literal: true + +class CreateAuditLogs < ActiveRecord::Migration[8.1] + def change + create_table :audit_logs do |t| + t.bigint :user_id + t.string :action, null: false + t.string :auditable_type + t.bigint :auditable_id + t.jsonb :metadata, default: {} + t.string :ip_address + t.string :user_agent + t.timestamps + end + + add_index :audit_logs, :user_id + add_index :audit_logs, [ :auditable_type, :auditable_id ] + add_index :audit_logs, :created_at + add_foreign_key :audit_logs, :users + end +end diff --git a/db/migrate/20260910180000_fix_audit_logs_foreign_key.rb b/db/migrate/20260910180000_fix_audit_logs_foreign_key.rb new file mode 100644 index 000000000..990a77b1d --- /dev/null +++ b/db/migrate/20260910180000_fix_audit_logs_foreign_key.rb @@ -0,0 +1,8 @@ +# frozen_string_literal: true + +class FixAuditLogsForeignKey < ActiveRecord::Migration[8.1] + def change + remove_foreign_key :audit_logs, :users + add_foreign_key :audit_logs, :users, on_delete: :nullify + end +end diff --git a/db/queue_schema.rb b/db/queue_schema.rb new file mode 100644 index 000000000..f9a71dabb --- /dev/null +++ b/db/queue_schema.rb @@ -0,0 +1,160 @@ +ActiveRecord::Schema[7.1].define(version: 1) do + create_table "solid_queue_blocked_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.string "concurrency_key", null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.index [ "concurrency_key", "priority", "job_id" ], name: "index_solid_queue_blocked_executions_for_release" + t.index [ "expires_at", "concurrency_key" ], name: "index_solid_queue_blocked_executions_for_maintenance" + t.index [ "job_id" ], name: "index_solid_queue_blocked_executions_on_job_id", unique: true + end + + create_table "solid_queue_claimed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "process_id" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_claimed_executions_on_job_id", unique: true + t.index [ "process_id", "job_id" ], name: "index_solid_queue_claimed_executions_on_process_id_and_job_id" + end + + create_table "solid_queue_failed_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.text "error" + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_failed_executions_on_job_id", unique: true + end + + create_table "solid_queue_jobs", force: :cascade do |t| + t.string "queue_name", null: false + t.string "class_name", null: false + t.text "arguments" + t.integer "priority", default: 0, null: false + t.string "active_job_id" + t.datetime "scheduled_at" + t.datetime "finished_at" + t.string "concurrency_key" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.bigint "batch_id" + t.index [ "active_job_id" ], name: "index_solid_queue_jobs_on_active_job_id" + t.index [ "batch_id" ], name: "index_solid_queue_jobs_on_batch_id" + t.index [ "class_name" ], name: "index_solid_queue_jobs_on_class_name" + t.index [ "finished_at" ], name: "index_solid_queue_jobs_on_finished_at" + t.index [ "queue_name", "finished_at" ], name: "index_solid_queue_jobs_for_filtering" + t.index [ "scheduled_at", "finished_at" ], name: "index_solid_queue_jobs_for_alerting" + end + + create_table "solid_queue_pauses", force: :cascade do |t| + t.string "queue_name", null: false + t.datetime "created_at", null: false + t.index [ "queue_name" ], name: "index_solid_queue_pauses_on_queue_name", unique: true + end + + create_table "solid_queue_processes", force: :cascade do |t| + t.string "kind", null: false + t.datetime "last_heartbeat_at", null: false + t.bigint "supervisor_id" + t.integer "pid", null: false + t.string "hostname" + t.text "metadata" + t.datetime "created_at", null: false + t.string "name", null: false + t.index [ "last_heartbeat_at" ], name: "index_solid_queue_processes_on_last_heartbeat_at" + t.index [ "name", "supervisor_id" ], name: "index_solid_queue_processes_on_name_and_supervisor_id", unique: true + t.index [ "supervisor_id" ], name: "index_solid_queue_processes_on_supervisor_id" + end + + create_table "solid_queue_ready_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_ready_executions_on_job_id", unique: true + t.index [ "priority", "job_id" ], name: "index_solid_queue_poll_all" + t.index [ "queue_name", "priority", "job_id" ], name: "index_solid_queue_poll_by_queue" + end + + create_table "solid_queue_recurring_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "task_key", null: false + t.datetime "run_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_recurring_executions_on_job_id", unique: true + t.index [ "task_key", "run_at" ], name: "index_solid_queue_recurring_executions_on_task_key_and_run_at", unique: true + end + + create_table "solid_queue_recurring_tasks", force: :cascade do |t| + t.string "key", null: false + t.string "schedule", null: false + t.string "command", limit: 2048 + t.string "class_name" + t.text "arguments" + t.string "queue_name" + t.integer "priority", default: 0 + t.boolean "static", default: true, null: false + t.text "description" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "key" ], name: "index_solid_queue_recurring_tasks_on_key", unique: true + t.index [ "static" ], name: "index_solid_queue_recurring_tasks_on_static" + end + + create_table "solid_queue_scheduled_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.string "queue_name", null: false + t.integer "priority", default: 0, null: false + t.datetime "scheduled_at", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_scheduled_executions_on_job_id", unique: true + t.index [ "scheduled_at", "priority", "job_id" ], name: "index_solid_queue_dispatch_all" + end + + create_table "solid_queue_semaphores", force: :cascade do |t| + t.string "key", null: false + t.integer "value", default: 1, null: false + t.datetime "expires_at", null: false + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "expires_at" ], name: "index_solid_queue_semaphores_on_expires_at" + t.index [ "key", "value" ], name: "index_solid_queue_semaphores_on_key_and_value" + t.index [ "key" ], name: "index_solid_queue_semaphores_on_key", unique: true + end + + create_table "solid_queue_batches", force: :cascade do |t| + t.string "active_job_batch_id" + t.string "description" + t.text "on_finish" + t.text "on_success" + t.text "on_failure" + t.text "metadata" + t.integer "total_jobs", default: 0, null: false + t.integer "completed_jobs", default: 0, null: false + t.integer "failed_jobs", default: 0, null: false + t.datetime "enqueued_at" + t.datetime "finished_at" + t.datetime "failed_at" + t.datetime "created_at", null: false + t.datetime "updated_at", null: false + t.index [ "active_job_batch_id" ], name: "index_solid_queue_batches_on_active_job_batch_id", unique: true + t.index [ "finished_at" ], name: "index_solid_queue_batches_on_finished_at" + end + + create_table "solid_queue_batch_executions", force: :cascade do |t| + t.bigint "job_id", null: false + t.bigint "batch_id", null: false + t.datetime "created_at", null: false + t.index [ "job_id" ], name: "index_solid_queue_batch_executions_on_job_id", unique: true + t.index [ "batch_id" ], name: "index_solid_queue_batch_executions_on_batch_id" + end + + add_foreign_key "solid_queue_batch_executions", "solid_queue_batches", column: "batch_id", on_delete: :cascade + add_foreign_key "solid_queue_batch_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_blocked_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_claimed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_failed_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_ready_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_recurring_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade + add_foreign_key "solid_queue_scheduled_executions", "solid_queue_jobs", column: "job_id", on_delete: :cascade +end diff --git a/db/schema.rb b/db/schema.rb new file mode 100644 index 000000000..f22864682 --- /dev/null +++ b/db/schema.rb @@ -0,0 +1,98 @@ +# This file is auto-generated from the current state of the database. Instead +# of editing this file, please use the migrations feature of Active Record to +# incrementally modify your database, and then regenerate this schema definition. +# +# This file is the source Rails uses to define your schema when running `bin/rails +# db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to +# be faster and is potentially less error prone than running all of your +# migrations from scratch. Old migrations may fail to apply correctly if those +# migrations use external dependencies or application code. +# +# It's strongly recommended that you check this file into your version control system. + +ActiveRecord::Schema[8.1].define(version: 2026_09_10_180000) do + # These are extensions that must be enabled in order to support this database + enable_extension "pg_catalog.plpgsql" + + create_table "active_storage_attachments", force: :cascade do |t| + t.bigint "blob_id", null: false + t.datetime "created_at", null: false + t.string "name", null: false + t.bigint "record_id", null: false + t.string "record_type", null: false + t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id" + t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true + end + + create_table "active_storage_blobs", force: :cascade do |t| + t.bigint "byte_size", null: false + t.string "checksum" + t.string "content_type" + t.datetime "created_at", null: false + t.string "filename", null: false + t.string "key", null: false + t.text "metadata" + t.string "service_name", null: false + t.index ["key"], name: "index_active_storage_blobs_on_key", unique: true + end + + create_table "active_storage_variant_records", force: :cascade do |t| + t.bigint "blob_id", null: false + t.string "variation_digest", null: false + t.index ["blob_id", "variation_digest"], name: "index_active_storage_variant_records_uniqueness", unique: true + end + + create_table "audit_logs", force: :cascade do |t| + t.string "action", null: false + t.bigint "auditable_id" + t.string "auditable_type" + t.datetime "created_at", null: false + t.string "ip_address" + t.jsonb "metadata", default: {} + t.datetime "updated_at", null: false + t.string "user_agent" + t.bigint "user_id" + t.index ["auditable_type", "auditable_id"], name: "index_audit_logs_on_auditable_type_and_auditable_id" + t.index ["created_at"], name: "index_audit_logs_on_created_at" + t.index ["user_id"], name: "index_audit_logs_on_user_id" + end + + create_table "sessions", force: :cascade do |t| + t.datetime "created_at", null: false + t.string "ip_address" + t.datetime "last_active_at" + t.datetime "updated_at", null: false + t.string "user_agent" + t.bigint "user_id", null: false + t.index ["created_at"], name: "index_sessions_on_created_at" + t.index ["last_active_at"], name: "index_sessions_on_last_active_at" + t.index ["user_id"], name: "index_sessions_on_user_id" + end + + create_table "user_imports", force: :cascade do |t| + t.datetime "created_at", null: false + t.integer "failed_rows", default: 0, null: false + t.string "file_name" + t.integer "processed_rows", default: 0, null: false + t.jsonb "row_errors", default: [], null: false + t.integer "status", default: 0, null: false + t.integer "total_rows", default: 0, null: false + t.datetime "updated_at", null: false + end + + create_table "users", force: :cascade do |t| + t.string "avatar_url" + t.datetime "created_at", null: false + t.string "email", null: false + t.string "full_name", null: false + t.string "password_digest", null: false + t.integer "role", default: 0, null: false + t.datetime "updated_at", null: false + t.index ["email"], name: "index_users_on_email", unique: true + end + + add_foreign_key "active_storage_attachments", "active_storage_blobs", column: "blob_id" + add_foreign_key "active_storage_variant_records", "active_storage_blobs", column: "blob_id" + add_foreign_key "audit_logs", "users", on_delete: :nullify + add_foreign_key "sessions", "users" +end diff --git a/db/seeds.rb b/db/seeds.rb new file mode 100644 index 000000000..2989b9272 --- /dev/null +++ b/db/seeds.rb @@ -0,0 +1,26 @@ +# Seeds are idempotent and safe for every environment (dev/test/prod). +# Load with bin/rails db:seed (created alongside DB with db:setup). +# CI runs env RAILS_ENV=test bin/rails db:seed:replant. + +admin = User.find_or_create_by!(email: "admin@example.com") do |u| + u.full_name = "Site Admin" + u.password = "Password123" + u.password_confirmation = "Password123" + u.role = :admin +end +puts "admin: #{admin.email} (#{admin.role})" + +[ + [ "Ada Lovelace", "ada@example.com" ], + [ "Alan Turing", "alan@example.com" ], + [ "Grace Hopper", "grace@example.com" ], + [ "Margaret Hamilton", "margaret@example.com" ] +].each do |full_name, email| + user = User.find_or_create_by!(email: email) do |u| + u.full_name = full_name + u.password = "Password123" + u.password_confirmation = "Password123" + u.role = :user + end + puts "user: #{user.email} (#{user.role})" +end diff --git a/instructions.md b/instructions.md new file mode 100644 index 000000000..7d2aea5e1 --- /dev/null +++ b/instructions.md @@ -0,0 +1,87 @@ +# Modern Fullstack Developer Test (Rails 8 / Ruby 4) + +- Check this readme.md +- Create a branch to develop your task +- Push to remote in 1 week (date will be checked from branch creation/assigned date) + +# Requirements: +- Target Stack: **Ruby 4.0+** and **Rails 8.0+** +- Database: PostgreSQL, MySQL, or SQLite (configured for production-ready WAL mode) +- Write robust unit, integration, and system tests using parallel testing features +- Deliver with a working multi-stage Dockerfile utilizing Thruster/Kamal-ready defaults +- Show senior best practices (e.g., proper design patterns, solid architecture, strict linter configuration) + +# Our AI Policy +At Umanni, we value efficiency and the modern developer workflow. **You are allowed to use AI coding assistants (ChatGPT, Claude, Copilot, etc.) during this test.** However, transparency is part of our culture. If you use any LLM to generate, refactor, or structure your code, **you must explicitly state which model you used** in a dedicated section at the top of your submission's README.md. Failing to disclose AI usage while using it will invalidate your submission. + +# The Test +Here we'll try to simulate a "real sprint" that you'll probably be assigned while working as Fullstack at Umanni. + +# The Task +- Create a modern, responsive application to manage users. +- A user must have: + 1. full_name + 2. email + 3. avatar_image (ActiveStorage file upload or remote URL) + 4. role (admin/no-admin) + +# The App +## Admin Use cases +- As an Admin, I must be able to access a User Admin Dashboard. +- As an Admin, I must be able to see on the Dashboard (updated via real-time streams/frontend state): + - Total number of Users + - Total number of Users grouped by Role +- As an Admin, I must be redirected to the User Admin Dashboard after login. +- As an Admin, I must be able to list, create, edit, and delete Users. +- As an Admin, I must be able to toggle the User Role. +- As an Admin, I must be able to import a Spreadsheet (.csv/.xlsx) into the system in order to asynchronously create new Users. +- As an Admin, I must be able to see the live progress/status of the spreadsheet import process. + +## User Use Cases +- As a User, I must be redirected to my Profile after login. +- As a User, I must be able only to see my info, edit, and delete my profile. + +## Visitor Use Cases +- As a Visitor, I can register myself as a normal User. + + + +# The Start. +- Your deadline is 1 week after accepting this test. + +# The Rules (Strict Compliance) +These are mandatory. Failing any of them will invalidate your submission. +- **Documentation**: You must write down a detailed README.md in English explaining how to build, seed, and run your app, including your AI disclosure if applicable. +- **Frontend Stack**: You have two choices for the modern monolithic approach: + - **Option A (Classic Modern):** Hotwire (Turbo 8+ / Stimulus) with smooth, reactive UI states. + - **Option B (Modern SPA Monolith):** **React integrated via Inertia.js** (using Vite or the official Rails 8 asset pipeline integration). +- **Styling**: The Frontend must use a modern CSS framework (Tailwind CSS, Bootstrap, or any utility-first library). Keep it beautiful, responsive, and clean. +- **Real-time & Background Processing**: You must leverage native Rails 8 tools (**Solid Cable** for live dashboard counters/import bars and **Solid Queue** for the background import processing). No Redis installation should be required. +- **Authentication**: You must use the new built-in Rails 8 Authentication system (`bin/rails generate authentication`), customized to fit the role constraints. Avoid legacy heavy gems (like Devise). +- **Git Hygiene**: Clean git history with atomic commits, proper descriptions, and a Pull Request-based workflow. + +# What we're expecting to see: +- Modern asset management using **Propshaft** or **Vite Rails** (if choosing Inertia/React). +- .gitignore, .dockerignore configured correctly. +- Clean application configuration using Rails credentials. +- Comprehensive cross-browser support considerations. +- Strict form validations (Frontend interactive feedback + Backend structural validation). +- Parallel testing with at least 90% coverage (using Minitest, RSpec, and Playwright/Capybara for frontend integration). + +# Extra points +- Delivery via a clean **Kamal 2** deployment configuration (`deploy.yml`). +- Advanced SSR (Server-Side Rendering) setup if using **Inertia.js + React**. +- Use of **Thruster** as a zero-config proxy for asset caching and compression in Docker. +- Advanced performance profiling leveraging Ruby 4's **ZJIT** compilation optimizations. + +# What will be assessed +- Code's Semantics, Cleanness, and Maintainability (Senior-level object-oriented design and clean React/Stimulus component lifecycle). +- Modern Rails 8 idiom usage (e.g., Strict structural params handling, Solid architecture separation). +- Basic Security testing against traditional vectors (SQLi, XSS, XSRF) and proper encryption of sensitive DB columns where applicable. diff --git a/lib/tasks/.keep b/lib/tasks/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/lib/tasks/annotate_rb.rake b/lib/tasks/annotate_rb.rake new file mode 100644 index 000000000..c4d4f2d53 --- /dev/null +++ b/lib/tasks/annotate_rb.rake @@ -0,0 +1,10 @@ +# This rake task was added by annotate_rb gem. + +# Can set `ANNOTATERB_SKIP_ON_DB_TASKS` to be anything to skip this +if Rails.env.development? && ENV["ANNOTATERB_SKIP_ON_DB_TASKS"].nil? + require "annotate_rb" + + # Can modify the config path here if needed - by default, it's .annotaterb.yml in the root of the project + # AnnotateRb::ConfigFinder.config_path = "" + AnnotateRb::Core.load_rake_tasks +end diff --git a/log/.keep b/log/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 000000000..588bddef5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,985 @@ +{ + "name": "Fullstack-Developer", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@inertiajs/react": "^3.7.0", + "@inertiajs/vite": "^3.7.0", + "@rails/actioncable": "^7.2.302", + "@vitejs/plugin-react": "^6.1.1", + "react": "^19.3.0", + "react-dom": "^19.3.0" + }, + "devDependencies": { + "vite": "^8.2.2", + "vite-plugin-ruby": "^5.2.3" + } + }, + "node_modules/@inertiajs/core": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@inertiajs/core/-/core-3.7.0.tgz", + "integrity": "sha512-JzysXTPsOpKcnR7ohwpgKE+UWBrKwW7z23DydWHSxjfQ02tJAKmNnZJAxnX7zH3zUSTqbtPge6QC8XhvfjNXmw==", + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "es-toolkit": "^1.33.0", + "laravel-precognition": "^2.0.0" + }, + "peerDependencies": { + "axios": "^1.15.2" + }, + "peerDependenciesMeta": { + "axios": { + "optional": true + } + } + }, + "node_modules/@inertiajs/react": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@inertiajs/react/-/react-3.7.0.tgz", + "integrity": "sha512-rc/TsVT7ihDk+cMeCuU3BjdUfTq6HJwXqGy7oPaysLQCeyfhIaP2QgExo5R1QSCFIwl9un0MeZnzTOG+i38jLw==", + "license": "MIT", + "dependencies": { + "@inertiajs/core": "3.7.0", + "es-toolkit": "^1.33.0", + "laravel-precognition": "^2.0.0" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + } + }, + "node_modules/@inertiajs/vite": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@inertiajs/vite/-/vite-3.7.0.tgz", + "integrity": "sha512-eoOqvIEgmsktC/b5NuZjsj3VvCJ7GsbvHFN2IgT/7DXjLVdXGygWeyYHmS57AGSbb6yOyebeBR6cYkk6YyHOmg==", + "license": "MIT", + "dependencies": { + "@inertiajs/core": "3.7.0", + "tinyglobby": "^0.2.15" + }, + "peerDependencies": { + "vite": "^7.0.0 || ^8.0.0" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.149.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.149.0.tgz", + "integrity": "sha512-Efcc+iF0j3Bf67YjEqIqWXbX5XddXoK/Mw4K1/JuXwRCZ8N16VR7iT23nlCc9XrveFVh/E5Rqs2StT0V8v9LdA==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/oxc-project" + } + }, + "node_modules/@rails/actioncable": { + "version": "7.2.302", + "resolved": "https://registry.npmjs.org/@rails/actioncable/-/actioncable-7.2.302.tgz", + "integrity": "sha512-9JOPzUb7RCqIEWeoE78mPFd71fzyJ25LjeMzD45zQ75f41ca7BsgQVqiyrIuxDZ1yyZ4PdyxCMZF0KJlJ9qX0g==", + "license": "MIT" + }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.8.tgz", + "integrity": "sha512-tN5aztYkKCte4i5SIrrz5yK/HMjEuCqCSCJa418jOV8tZ1cBY3YF2otxB1ktPxzsLA1BeTqwapK0bfjxNvHJVw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.8.tgz", + "integrity": "sha512-dIYTWl9XprMUiQFoc55KUyk/oS8SKYH3zFl0LTR7RT0Xj4hgSVyuJcroH8JUu8RcpF8fTB6E0aOwCkZoYPcDSQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.8.tgz", + "integrity": "sha512-PCSDQGXD2IyTEFrcgPyBM8jJuGmrbCMuoIOXdbEGVemruKACXoLQJrb+A45Z0L5t1RQkdfJprAYPkikbh7dzdA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.8.tgz", + "integrity": "sha512-Uk7lRsGhPFHVX/sAUC6D5H9Ol30dFHd6iquokll2th3LpdJ3F5CzQB+7DHn0Ri2mG+U7k2zXiPHDrwZenXhwSA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.8.tgz", + "integrity": "sha512-DjszaTEVogPqA5bYzsEeqDCQxbcp2fexQwKcRspYji2yzR68fCf+e4fx6kBSRDwX5/brZaHw/hWS9+A/+/w9sQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.8.tgz", + "integrity": "sha512-zmwa7FTmdzB6aaEEuuls18H6Ap5JmJPSoPTuXixeJZV6tG40SyLkApQtz1g8ptZtiEKqj9OM0oNLPh1AgvE31Q==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.8.tgz", + "integrity": "sha512-KdYQDPHwJVnbFwdTGMgxsI9SqblBlz6STGM+w1We/d5B8OWWidYH0MwkU/uA1wM5fIpO2MkOVxXrNzzuZhw9ew==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.8.tgz", + "integrity": "sha512-jFJTifHnNPY+yzOoNZQfSIysrVyXzEQPhPnOUjmD1bcQGHH6s7c8cViKWar8YplQImE5N9JRqMCLrM2CdxOrZA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.8.tgz", + "integrity": "sha512-FhiOziBDWPBjbcmRzfLyIJnaP7AVMFXT7YCXPjXxj7wKU3vx24RjrCNN/zjvVa+N2vVoHJwCoUBvsrN/DG3zIA==", + "cpu": [ + "ppc64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.8.tgz", + "integrity": "sha512-WnHfADMzOV2Y55wlx1hzzQnar/wDt/VdvWSD99r18Mz9ylNieIGOkRx3UV21h7m/eJvjySYJkO26VvGNFkwsIQ==", + "cpu": [ + "s390x" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.8.tgz", + "integrity": "sha512-H9tRr5ibfXFVLxbPOseVewewFpl28zcEdjRDt2FTUZU7odxP0gEv1ki4/kGmcGOh78oRwZuuQllGLZ9zTJp84g==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.8.tgz", + "integrity": "sha512-UefiqfM3D6IVNlZ8tSGs9+Ejjud2T+oxO0IHADU45Y+lyEjD2dVFyZHbkfX0LUb5Zugo/oIv1eCO/KVYhgYJYA==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.8.tgz", + "integrity": "sha512-637Ke4kWSy6rp9cxQ9gMOXlxPgIw/c1beASV4M//3+9I4uwBVOOl74G+e3zyU3u19U7RkRl/HuewixZ/Z6+Rjg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.8.tgz", + "integrity": "sha512-xWBkPOF1Q9k/Gv1nQXnVdLxKu74jXppuOM4Z3mnypVUJJJwLsMl7hNJGRAUJoG8A5MgOI1ACKM+wBFxSJzKy4A==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.8.tgz", + "integrity": "sha512-uz2ZvfgXbxqNwijjjbxrnvALwpyODDcgc1T1N8N3rf/DXKQmaFwmB4LX4yyjggpwN2obdQLb2rgirX5ffCWYng==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "license": "MIT" + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.1.1", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.1.tgz", + "integrity": "sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==", + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.1" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "oxc-transform-react": "^0.145.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "oxc-transform-react": { + "optional": true + } + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/es-toolkit": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.52.0.tgz", + "integrity": "sha512-XTNEJQh1tY1ZJVcf6ayP/2n4ZPyaHlW2FWs7xvw5ddPuhUVjLD3olQVQS7kf58JbAB48iL0uL/jerTrjtV3lDA==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/laravel-precognition": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/laravel-precognition/-/laravel-precognition-2.0.0.tgz", + "integrity": "sha512-dmA4HGc9m+TsVNsJs9/XQBI8u6j7coilN+qKkBuhuXQzH3HypwS/c5dFQ4UqUGjBbcxIM7zdk91kM/SRZwIvWQ==", + "license": "MIT", + "dependencies": { + "es-toolkit": "^1.32.0" + }, + "peerDependencies": { + "axios": "^1.4.0" + }, + "peerDependenciesMeta": { + "axios": { + "optional": true + } + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/nanoid": { + "version": "3.3.18", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz", + "integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/obug": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz", + "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==", + "dev": true, + "funding": [ + "https://github.com/sponsors/sxzz", + "https://opencollective.com/debug" + ], + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.28", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz", + "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.18", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz", + "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz", + "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.28.0" + }, + "peerDependencies": { + "react": "^19.3.0" + } + }, + "node_modules/rolldown": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.8.tgz", + "integrity": "sha512-Z67nTmhZe7anqnM/EjI392w5i/ANUinjip7QYsOyN37oayduxt3ksdX0hf5OOamkAd53BiIHfbfSzfUmzKFQqQ==", + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.149.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm-eabi": "1.2.8", + "@rolldown/binding-android-arm64": "1.2.8", + "@rolldown/binding-darwin-arm64": "1.2.8", + "@rolldown/binding-darwin-x64": "1.2.8", + "@rolldown/binding-freebsd-x64": "1.2.8", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.8", + "@rolldown/binding-linux-arm64-gnu": "1.2.8", + "@rolldown/binding-linux-arm64-musl": "1.2.8", + "@rolldown/binding-linux-ppc64-gnu": "1.2.8", + "@rolldown/binding-linux-s390x-gnu": "1.2.8", + "@rolldown/binding-linux-x64-gnu": "1.2.8", + "@rolldown/binding-linux-x64-musl": "1.2.8", + "@rolldown/binding-openharmony-arm64": "1.2.8", + "@rolldown/binding-win32-arm64-msvc": "1.2.8", + "@rolldown/binding-win32-x64-msvc": "1.2.8" + } + }, + "node_modules/scheduler": { + "version": "0.28.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz", + "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==", + "license": "MIT" + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/vite": { + "version": "8.2.2", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.2.2.tgz", + "integrity": "sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==", + "license": "MIT", + "dependencies": { + "lightningcss": "^1.33.0", + "picomatch": "^4.0.5", + "postcss": "^8.5.26", + "rolldown": "~1.2.4", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.4.0 || ^0.5.0", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/vite-plugin-ruby": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/vite-plugin-ruby/-/vite-plugin-ruby-5.2.3.tgz", + "integrity": "sha512-WwUa91eE1A5veI2UiU2WVtTKmmvha8zoCccSi3rT978W43QT+SXzAHYuJ8cirPq58E1ct4okmOCWpsyEbUl6Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "obug": "^2.0", + "tinyglobby": "^0.2.12" + }, + "peerDependencies": { + "vite": ">=5.0.0" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 000000000..0ab1d07f3 --- /dev/null +++ b/package.json @@ -0,0 +1,16 @@ +{ + "private": true, + "type": "module", + "devDependencies": { + "vite": "^8.2.2", + "vite-plugin-ruby": "^5.2.3" + }, + "dependencies": { + "@inertiajs/react": "^3.7.0", + "@inertiajs/vite": "^3.7.0", + "@rails/actioncable": "^7.2.302", + "@vitejs/plugin-react": "^6.1.1", + "react": "^19.3.0", + "react-dom": "^19.3.0" + } +} diff --git a/public/400.html b/public/400.html new file mode 100644 index 000000000..640de0339 --- /dev/null +++ b/public/400.html @@ -0,0 +1,135 @@ + + + + + + + The server cannot process the request due to a client error (400 Bad Request) + + + + + + + + + + + + + +
+
+ +
+
+

The server cannot process the request due to a client error. Please check the request and try again. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/404.html b/public/404.html new file mode 100644 index 000000000..d7f0f1422 --- /dev/null +++ b/public/404.html @@ -0,0 +1,135 @@ + + + + + + + The page you were looking for doesn't exist (404 Not found) + + + + + + + + + + + + + +
+
+ +
+
+

The page you were looking for doesn't exist. You may have mistyped the address or the page may have moved. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/406-unsupported-browser.html b/public/406-unsupported-browser.html new file mode 100644 index 000000000..43d2811e8 --- /dev/null +++ b/public/406-unsupported-browser.html @@ -0,0 +1,135 @@ + + + + + + + Your browser is not supported (406 Not Acceptable) + + + + + + + + + + + + + +
+
+ +
+
+

Your browser is not supported.
Please upgrade your browser to continue.

+
+
+ + + + diff --git a/public/422.html b/public/422.html new file mode 100644 index 000000000..f12fb4aa1 --- /dev/null +++ b/public/422.html @@ -0,0 +1,135 @@ + + + + + + + The change you wanted was rejected (422 Unprocessable Entity) + + + + + + + + + + + + + +
+
+ +
+
+

The change you wanted was rejected. Maybe you tried to change something you didn't have access to. If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/500.html b/public/500.html new file mode 100644 index 000000000..e4eb18a75 --- /dev/null +++ b/public/500.html @@ -0,0 +1,135 @@ + + + + + + + We're sorry, but something went wrong (500 Internal Server Error) + + + + + + + + + + + + + +
+
+ +
+
+

We're sorry, but something went wrong.
If you're the application owner check the logs for more information.

+
+
+ + + + diff --git a/public/icon.png b/public/icon.png new file mode 100644 index 000000000..c4c9dbfbb Binary files /dev/null and b/public/icon.png differ diff --git a/public/icon.svg b/public/icon.svg new file mode 100644 index 000000000..04b34bf83 --- /dev/null +++ b/public/icon.svg @@ -0,0 +1,3 @@ + + + diff --git a/public/robots.txt b/public/robots.txt new file mode 100644 index 000000000..c19f78ab6 --- /dev/null +++ b/public/robots.txt @@ -0,0 +1 @@ +# See https://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file diff --git a/script/.keep b/script/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/storage/.keep b/storage/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/application_system_test_case.rb b/test/application_system_test_case.rb new file mode 100644 index 000000000..2c3b69f4b --- /dev/null +++ b/test/application_system_test_case.rb @@ -0,0 +1,8 @@ +require "test_helper" + +class ApplicationSystemTestCase < ActionDispatch::SystemTestCase + driven_by :selenium, using: :headless_chrome, screen_size: [ 1400, 900 ] do |options| + options.add_argument("no-sandbox") + options.add_argument("disable-dev-shm-usage") + end +end diff --git a/test/channels/application_cable/connection_test.rb b/test/channels/application_cable/connection_test.rb new file mode 100644 index 000000000..0aeacee08 --- /dev/null +++ b/test/channels/application_cable/connection_test.rb @@ -0,0 +1,26 @@ +require "test_helper" + +class ApplicationCable::ConnectionTest < ActionCable::Connection::TestCase + setup do + @user = User.create!(full_name: "Cable User", email: "cable-conn@example.com", password: "Password123", password_confirmation: "Password123") + end + + test "connects with valid session cookie" do + session = @user.sessions.create! + cookies.signed[:session_id] = session.id + + connect + + assert_equal @user.id, connection.current_user.id + end + + test "rejects connection without session cookie" do + assert_reject_connection { connect } + end + + test "rejects connection with unknown session id" do + cookies.signed[:session_id] = 0 + + assert_reject_connection { connect } + end +end diff --git a/test/channels/dashboard_channel_test.rb b/test/channels/dashboard_channel_test.rb new file mode 100644 index 000000000..83670d476 --- /dev/null +++ b/test/channels/dashboard_channel_test.rb @@ -0,0 +1,30 @@ +require "test_helper" + +class DashboardChannelTest < ActionCable::Channel::TestCase + setup do + @admin = User.create!(full_name: "Dash Admin", email: "dash-chan@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Dash User", email: "dash-user@example.com", password: "Password123", password_confirmation: "Password123") + end + + test "subscribes for admin" do + stub_connection current_user: @admin + subscribe + + assert subscription.confirmed? + assert_has_stream "dashboard" + end + + test "rejects subscription for non-admin" do + stub_connection current_user: @user + subscribe + + assert subscription.rejected? + end + + test "rejects subscription without user" do + stub_connection current_user: nil + subscribe + + assert subscription.rejected? + end +end diff --git a/test/channels/user_import_channel_test.rb b/test/channels/user_import_channel_test.rb new file mode 100644 index 000000000..8d674bd9c --- /dev/null +++ b/test/channels/user_import_channel_test.rb @@ -0,0 +1,33 @@ +require "test_helper" + +class UserImportChannelTest < ActionCable::Channel::TestCase + setup do + @admin = User.create!(full_name: "Import Admin", email: "imp-chan-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Import User", email: "imp-chan-user@example.com", password: "Password123", password_confirmation: "Password123") + @import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + @import.file.attach(io: StringIO.new("full_name,email,password\nA,a@x.co,Password123\n"), filename: "users.csv", content_type: "text/csv") + @import.save! + end + + test "subscribes for admin" do + stub_connection current_user: @admin + subscribe(id: @import.id) + + assert subscription.confirmed? + assert_has_stream_for @import + end + + test "rejects subscription for non-admin" do + stub_connection current_user: @user + subscribe(id: @import.id) + + assert subscription.rejected? + end + + test "rejects subscription for an unknown import" do + stub_connection current_user: @admin + subscribe(id: 0) + + assert subscription.rejected? + end +end diff --git a/test/controllers/.keep b/test/controllers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/controllers/concerns/authentication_test.rb b/test/controllers/concerns/authentication_test.rb new file mode 100644 index 000000000..2a8ad66cd --- /dev/null +++ b/test/controllers/concerns/authentication_test.rb @@ -0,0 +1,31 @@ +require "test_helper" + +class AuthenticationConcernTest < ActiveSupport::TestCase + class DummyController < ActionController::Base + include Authentication + + def root_url + "http://test.host/" + end + end + + test "falls back to root_url without return location" do + controller = DummyController.new + controller.define_singleton_method(:session) { {} } + + assert_equal "http://test.host/", controller.send(:after_authentication_url) + end + + test "returns stored return location when present" do + controller = DummyController.new + controller.define_singleton_method(:session) do + { return_to_after_authenticating: "http://test.host/profile" } + end + + assert_equal "http://test.host/profile", controller.send(:after_authentication_url) + end + + test "inertia controller inherits application controller" do + assert_equal ApplicationController, InertiaController.superclass + end +end diff --git a/test/controllers/health_controller_test.rb b/test/controllers/health_controller_test.rb new file mode 100644 index 000000000..6121b1df7 --- /dev/null +++ b/test/controllers/health_controller_test.rb @@ -0,0 +1,24 @@ +require "test_helper" + +class HealthControllerTest < ActionDispatch::IntegrationTest + test "show returns ok when the database is reachable" do + get rails_health_check_path + + assert_response :success + assert_equal({ "status" => "ok" }, response.parsed_body) + end + + test "show reports unavailable when the database is down" do + connection = ActiveRecord::Base.connection + connection.define_singleton_method(:execute) { |*| raise ActiveRecord::ConnectionNotEstablished } + + begin + get rails_health_check_path + ensure + connection.singleton_class.send(:remove_method, :execute) + end + + assert_response :service_unavailable + assert_equal({ "status" => "unavailable" }, response.parsed_body) + end +end diff --git a/test/controllers/inertia_controller_coverage_test.rb b/test/controllers/inertia_controller_coverage_test.rb new file mode 100644 index 000000000..4f2e73fea --- /dev/null +++ b/test/controllers/inertia_controller_coverage_test.rb @@ -0,0 +1,7 @@ +require "test_helper" +class InertiaControllerCoverageTest < ActionDispatch::IntegrationTest + test "index" do + get root_path + assert [ 200, 302 ].include?(response.status) + end +end diff --git a/test/controllers/inertia_controller_test.rb b/test/controllers/inertia_controller_test.rb new file mode 100644 index 000000000..5af216ebe --- /dev/null +++ b/test/controllers/inertia_controller_test.rb @@ -0,0 +1,8 @@ +require "test_helper" + +class ControllerCoverageTest < ActionDispatch::IntegrationTest + test "inertia controller responds" do + get root_path + assert [ 200, 302 ].include?(response.status) + end +end diff --git a/test/controllers/passwords_controller_test.rb b/test/controllers/passwords_controller_test.rb new file mode 100644 index 000000000..982151a6f --- /dev/null +++ b/test/controllers/passwords_controller_test.rb @@ -0,0 +1,67 @@ +require "test_helper" + +class PasswordsControllerTest < ActionDispatch::IntegrationTest + setup { @user = User.take } + + test "new" do + get new_password_path + assert_response :success + end + + test "create" do + post passwords_path, params: { email: @user.email } + assert_enqueued_jobs 1, only: ActionMailer::MailDeliveryJob + assert_redirected_to new_session_path + + follow_redirect! + assert_notice "reset instructions sent" + end + + test "create for an unknown user redirects but sends no mail" do + post passwords_path, params: { email: "missing-user@example.com" } + assert_enqueued_emails 0 + assert_redirected_to new_session_path + + follow_redirect! + assert_notice "reset instructions sent" + end + + test "edit" do + get edit_password_path(@user.password_reset_token) + assert_response :success + end + + test "edit with invalid password reset token" do + get edit_password_path("invalid token") + assert_redirected_to new_password_path + + follow_redirect! + assert_notice "reset link is invalid" + end + + test "update" do + assert_changes -> { @user.reload.password_digest } do + put password_path(@user.password_reset_token), params: { password: "NewPass123", password_confirmation: "NewPass123" } + assert_redirected_to new_session_path + end + + follow_redirect! + assert_notice "Password has been reset" + end + + test "update with non matching passwords" do + token = @user.password_reset_token + assert_no_changes -> { @user.reload.password_digest } do + put password_path(token), params: { password: "NoMatch1", password_confirmation: "Mismatch1" } + assert_redirected_to edit_password_path(token) + end + + follow_redirect! + assert_notice "Passwords did not match" + end + + private + def assert_notice(text) + assert_match text, response.body + end +end diff --git a/test/controllers/sessions_controller_test.rb b/test/controllers/sessions_controller_test.rb new file mode 100644 index 000000000..dadbaada1 --- /dev/null +++ b/test/controllers/sessions_controller_test.rb @@ -0,0 +1,33 @@ +require "test_helper" + +class SessionsControllerTest < ActionDispatch::IntegrationTest + setup { @user = User.take } + + test "new" do + get new_session_path + assert_response :success + end + + test "create with valid credentials redirects by role" do + post session_path, params: { email: @user.email, password: "Password1" } + + assert_redirected_to(@user.admin? ? admin_root_path : profile_path) + assert cookies[:session_id] + end + + test "create with invalid credentials" do + post session_path, params: { email: @user.email, password: "wrong" } + + assert_redirected_to new_session_path + assert_nil cookies[:session_id] + end + + test "destroy" do + sign_in_as(User.take) + + delete session_path + + assert_redirected_to new_session_path + assert_empty cookies[:session_id] + end +end diff --git a/test/fixtures/files/.keep b/test/fixtures/files/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/fixtures/files/sample_users.csv b/test/fixtures/files/sample_users.csv new file mode 100644 index 000000000..2c0bfd3e3 --- /dev/null +++ b/test/fixtures/files/sample_users.csv @@ -0,0 +1,26 @@ +full_name,email,password +Ana Garcia,ana.garcia@example.com,Pass1234! +Marcus Johnson,marcus.j@example.com,Secure99 +Yuki Tanaka,yuki.t@example.com,Moonlight88 +Fatima Al-Rashid,fatima@example.com,Desert77 +Liam O'Brien,liam.ob@example.com,Celtic66 +Sofia Petrova,sofia.p@example.com,Frost55 +Chen Wei,chen.wei@example.com,Dragon44 +Isabella Rodriguez,isabella@example.com,Sunshine33 +Kwame Asante,kwame@example.com,Akwaaba22 +Nina Müller,nina.m@example.com,Berlin11 +Hassan El-Sayed,hassan@example.com,Nile000 +Léa Dubois,lea.d@example.com,Paris999 +Ravi Sharma,ravi.s@example.com,Lotus888 +Camila Santos,camila@example.com,Rio7777 +Dimitri Ivanov,dimitri@example.com,Moscow66 +Aisha Patel,aisha@example.com,Lotus555 +Tomás Silva,tomas@example.com,Amazon44 +Ingrid Nilsen,ingrid@example.com,Fjord333 +Carlos Mendez,carlos@example.com,Sierra22 +Amara Okafor,amara@example.com,Lagos111 +Ivan Petrov,ivan@example.com,Volga000 +Mei-Ling Chen,meiling@example.com,Pearl999 +Aarav Patel,aarav@example.com,Lotus888 +Zara Khan,zara@example.com,Silk777 +Diego Lopez,diego@example.com,Amigo666 diff --git a/test/fixtures/files/sample_users.xlsx b/test/fixtures/files/sample_users.xlsx new file mode 100644 index 000000000..07c2ec03e Binary files /dev/null and b/test/fixtures/files/sample_users.xlsx differ diff --git a/test/fixtures/user_imports.yml b/test/fixtures/user_imports.yml new file mode 100644 index 000000000..a90503903 --- /dev/null +++ b/test/fixtures/user_imports.yml @@ -0,0 +1 @@ +# Read about fixtures at https://api.rubyonrails.org/classes/ActiveRecord/FixtureSet.html diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml new file mode 100644 index 000000000..82282b511 --- /dev/null +++ b/test/fixtures/users.yml @@ -0,0 +1,11 @@ +<% password_digest = BCrypt::Password.create("Password1") %> + +one: + full_name: One + email: one@example.com + password_digest: <%= password_digest %> + +two: + full_name: Two + email: two@example.com + password_digest: <%= password_digest %> diff --git a/test/helpers/.keep b/test/helpers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/integration/.keep b/test/integration/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/integration/admin_dashboard_live_test.rb b/test/integration/admin_dashboard_live_test.rb new file mode 100644 index 000000000..763970d33 --- /dev/null +++ b/test/integration/admin_dashboard_live_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class AdminDashboardLiveTest < ActionDispatch::IntegrationTest + include ActionCable::TestHelper + + setup do + @admin = User.create!(full_name: "Admin", email: "live-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(@admin) + end + + test "dashboard renders live component with counts" do + get admin_root_path + assert_response :success + assert_match "Admin/Dashboard/Show", response.body + assert_match "total_users", response.body + end + + test "creating user broadcasts dashboard update over cable" do + assert_broadcasts("dashboard", 1) do + User.create!(full_name: "Live", email: "live@example.com", password: "Password123", password_confirmation: "Password123") + end + end +end diff --git a/test/integration/admin_dashboard_test.rb b/test/integration/admin_dashboard_test.rb new file mode 100644 index 000000000..b1e132951 --- /dev/null +++ b/test/integration/admin_dashboard_test.rb @@ -0,0 +1,25 @@ +require "test_helper" + +class AdminDashboardTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Admin", email: "admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Regular", email: "user@example.com", password: "Password123", password_confirmation: "Password123", role: :user) + end + + test "admin dashboard shows total and by role" do + sign_in_as(@admin) + get admin_root_path + assert_response :success + assert_match "Admin/Dashboard/Show", response.body + assert_match "total_users", response.body + assert_match "users_by_role", response.body + assert_match "admin", response.body + assert_match "user", response.body + end + + test "non-admin redirected" do + sign_in_as(@user) + get admin_root_path + assert_redirected_to root_path + end +end diff --git a/test/integration/admin_import_test.rb b/test/integration/admin_import_test.rb new file mode 100644 index 000000000..18e89d8db --- /dev/null +++ b/test/integration/admin_import_test.rb @@ -0,0 +1,55 @@ +require "test_helper" + +class AdminImportTest < ActionDispatch::IntegrationTest + include ActiveJob::TestHelper + + setup do + @admin = User.create!(full_name: "Admin", email: "import-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(@admin) + end + + test "upload csv enqueues job and creates users with progress" do + csv = "full_name,email,password\nImported One,imp1@example.com,Password123\nImported Two,imp2@example.com,Password123\n" + file = Tempfile.new([ "users", ".csv" ]) + file.write(csv) + file.rewind + + assert_difference("User.count", 2) do + perform_enqueued_jobs do + post admin_user_imports_path, params: { user_import: { file: Rack::Test::UploadedFile.new(file.path, "text/csv") } } + end + end + + import = UserImport.last + assert_equal "completed", import.status + assert_equal 2, import.total_rows + assert_equal 2, import.processed_rows + get admin_user_import_path(import) + assert_response :success + assert_match "completed", response.body + end + + test "upload xlsx creates users" do + require "rubyXL" + wb = RubyXL::Workbook.new + ws = wb[0] + ws.add_cell(0, 0, "full_name"); ws.add_cell(0, 1, "email"); ws.add_cell(0, 2, "password") + ws.add_cell(1, 0, "X One"); ws.add_cell(1, 1, "x1@example.com"); ws.add_cell(1, 2, "Password123") + file = Tempfile.new([ "users", ".xlsx" ]) + wb.write(file.path) + + assert_difference("User.count", 1) do + perform_enqueued_jobs do + post admin_user_imports_path, params: { user_import: { file: Rack::Test::UploadedFile.new(file.path, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") } } + end + end + assert_equal "completed", UserImport.last.status + end + + test "non-admin cannot import" do + user = User.create!(full_name: "U", email: "nimp@example.com", password: "Password123", password_confirmation: "Password123") + sign_in_as(user) + get admin_user_imports_path + assert_redirected_to root_path + end +end diff --git a/test/integration/admin_imports_extra_test.rb b/test/integration/admin_imports_extra_test.rb new file mode 100644 index 000000000..eaa10db0c --- /dev/null +++ b/test/integration/admin_imports_extra_test.rb @@ -0,0 +1,24 @@ +require "test_helper" + +class AdminImportsExtraTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Imports Admin", email: "imports-extra-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(@admin) + end + + test "lists imports with file names" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach(io: StringIO.new("full_name,email,password\n"), filename: "XXX_USERS_.csv", content_type: "text/csv") + import.save! + + get admin_user_imports_path + assert_response :success + assert_match "XXX_USERS_.csv", response.body + end + + test "create without file rerenders form" do + post admin_user_imports_path, params: { user_import: { file: nil } } + assert_response :unprocessable_entity + assert_match "Admin/Imports/New", response.body + end +end diff --git a/test/integration/admin_quick_coverage_test.rb b/test/integration/admin_quick_coverage_test.rb new file mode 100644 index 000000000..0e7073264 --- /dev/null +++ b/test/integration/admin_quick_coverage_test.rb @@ -0,0 +1,25 @@ +require "test_helper" + +class AdminQuickCoverageTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Cover Admin", email: "cover-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + end + + test "admin base controller requires admin" do + sign_in_as(@admin) + get admin_root_path + assert_response :success + end + + test "admin users index" do + sign_in_as(@admin) + get admin_users_path + assert_response :success + end + + test "admin user imports index" do + sign_in_as(@admin) + get admin_user_imports_path + assert_response :success + end +end diff --git a/test/integration/admin_users_extra_test.rb b/test/integration/admin_users_extra_test.rb new file mode 100644 index 000000000..2b55d3d77 --- /dev/null +++ b/test/integration/admin_users_extra_test.rb @@ -0,0 +1,50 @@ +require "test_helper" + +class AdminUsersExtraTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Extra Admin", email: "extra-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Extra User", email: "extra-user@example.com", password: "Password123", password_confirmation: "Password123") + sign_in_as(@admin) + end + + test "shows user profile" do + get admin_user_path(@user) + assert_response :success + assert_match "Admin/Users/Show", response.body + end + + test "renders new user form" do + get new_admin_user_path + assert_response :success + assert_match "Admin/Users/New", response.body + end + + test "renders edit user form" do + get edit_admin_user_path(@user) + assert_response :success + assert_match "Admin/Users/Edit", response.body + end + + test "update with invalid params rerenders edit" do + patch admin_user_path(@user), params: { user: { full_name: "", email: "bad" } } + assert_response :unprocessable_entity + assert_match "Admin/Users/Edit", response.body + end + + test "replaces url when uploading file" do + @user.update!(avatar_url: "https://example.com/old.png") + file = Rack::Test::UploadedFile.new(StringIO.new("img"), "image/png", original_filename: "new.png") + + patch admin_user_path(@user), params: { user: { avatar_image: file } } + assert_redirected_to admin_users_path + assert_nil @user.reload.avatar_url + end + + test "purges attachment when setting url" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "old.png", content_type: "image/png") + + patch admin_user_path(@user), params: { user: { avatar_url: "https://example.com/new.png" } } + assert_redirected_to admin_users_path + assert_not @user.reload.avatar_image.attached? + end +end diff --git a/test/integration/admin_users_test.rb b/test/integration/admin_users_test.rb new file mode 100644 index 000000000..6666cab27 --- /dev/null +++ b/test/integration/admin_users_test.rb @@ -0,0 +1,50 @@ +require "test_helper" + +class AdminUsersTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Admin", email: "admin3@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Bob", email: "bob@example.com", password: "Password123", password_confirmation: "Password123") + sign_in_as(@admin) + end + + test "list users" do + get admin_users_path + assert_response :success + assert_match "Bob", response.body + end + + test "create user" do + assert_difference("User.count", 1) do + post admin_users_path, params: { user: { full_name: "New", email: "new@example.com", password: "Password123", password_confirmation: "Password123", role: "user" } } + end + assert_redirected_to admin_users_path + end + + test "update user" do + patch admin_user_path(@user), params: { user: { full_name: "Bob Updated" } } + assert_redirected_to admin_users_path + assert_equal "Bob Updated", @user.reload.full_name + end + + test "toggle role" do + assert @user.user? + patch toggle_role_admin_user_path(@user) + assert_redirected_to admin_users_path + assert @user.reload.admin? + patch toggle_role_admin_user_path(@user) + assert @user.reload.user? + end + + test "delete user" do + assert_difference("User.count", -1) do + delete admin_user_path(@user) + end + assert_redirected_to admin_users_path + end + + test "non-admin cannot access" do + sign_in_as(@user) + get admin_users_path + assert_redirected_to root_path + end +end diff --git a/test/integration/avatar_management_test.rb b/test/integration/avatar_management_test.rb new file mode 100644 index 000000000..39f42bf6f --- /dev/null +++ b/test/integration/avatar_management_test.rb @@ -0,0 +1,64 @@ +require "test_helper" + +class AvatarManagementTest < ActionDispatch::IntegrationTest + setup do + @user = User.create!(full_name: "Avatar User", email: "avatar-mgmt@example.com", password: "Password123", password_confirmation: "Password123") + @admin = User.create!(full_name: "Avatar Admin", email: "avatar-mgmt-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + end + + test "user removes own avatar" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "a.png", content_type: "image/png") + @user.update!(avatar_url: "https://example.com/a.png") + sign_in_as(@user) + + delete remove_avatar_profile_path + assert_redirected_to profile_path + + assert_not @user.reload.avatar_image.attached? + assert_nil @user.reload.avatar_url + end + + test "uploading file clears existing url" do + @user.update!(avatar_url: "https://example.com/old.png") + sign_in_as(@user) + + file = Rack::Test::UploadedFile.new(StringIO.new("img"), "image/png", original_filename: "new.png") + patch profile_path, params: { user: { avatar_image: file } } + assert_redirected_to profile_path + + assert_nil @user.reload.avatar_url + end + + test "setting url purges existing attachment" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "old.png", content_type: "image/png") + sign_in_as(@user) + + patch profile_path, params: { user: { avatar_url: "https://example.com/new.png" } } + assert_redirected_to profile_path + + assert_not @user.reload.avatar_image.attached? + assert_equal "https://example.com/new.png", @user.reload.avatar_url + end + + test "admin removes user avatar" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "a.png", content_type: "image/png") + @user.update!(avatar_url: "https://example.com/a.png") + sign_in_as(@admin) + + delete remove_avatar_admin_user_path(@user) + assert_redirected_to admin_users_path + + assert_not @user.reload.avatar_image.attached? + assert_nil @user.reload.avatar_url + end + + test "failed update keeps the existing attachment" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "keep.png", content_type: "image/png") + sign_in_as(@user) + + patch profile_path, params: { user: { email: "not-an-email", avatar_url: "https://example.com/new.png" } } + + assert_response :unprocessable_entity + assert @user.reload.avatar_image.attached? + end +end diff --git a/test/integration/avatar_upload_test.rb b/test/integration/avatar_upload_test.rb new file mode 100644 index 000000000..973df376b --- /dev/null +++ b/test/integration/avatar_upload_test.rb @@ -0,0 +1,28 @@ +require "test_helper" + +class AvatarUploadTest < ActionDispatch::IntegrationTest + setup do + @user = User.create!(full_name: "Pic", email: "picup@example.com", password: "Password123", password_confirmation: "Password123") + @admin = User.create!(full_name: "Admin", email: "picadmin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + end + + test "profile avatar file upload attaches" do + sign_in_as(@user) + file = Rack::Test::UploadedFile.new(StringIO.new("img"), "image/png", original_filename: "a.png") + patch profile_path, params: { user: { avatar_image: file } } + assert_redirected_to profile_path + assert @user.reload.avatar_image.attached? + get profile_path + assert_match "avatar_image_url", response.body + assert_match "/rails/active_storage/", response.body + end + + test "admin creates user with avatar file" do + sign_in_as(@admin) + file = Rack::Test::UploadedFile.new(StringIO.new("img"), "image/png", original_filename: "b.png") + assert_difference("User.count", 1) do + post admin_users_path, params: { user: { full_name: "Av", email: "av@example.com", password: "Password123", password_confirmation: "Password123", avatar_image: file } } + end + assert User.find_by(email: "av@example.com").avatar_image.attached? + end +end diff --git a/test/integration/channel_coverage_test.rb b/test/integration/channel_coverage_test.rb new file mode 100644 index 000000000..89ee2e485 --- /dev/null +++ b/test/integration/channel_coverage_test.rb @@ -0,0 +1,11 @@ +require "test_helper" + +class ChannelCoverageTest < ActionDispatch::IntegrationTest + test "dashboard channel exists" do + assert defined?(DashboardChannel) + end + + test "user import channel exists" do + assert defined?(UserImportChannel) + end +end diff --git a/test/integration/connection_coverage_test.rb b/test/integration/connection_coverage_test.rb new file mode 100644 index 000000000..17110a55a --- /dev/null +++ b/test/integration/connection_coverage_test.rb @@ -0,0 +1,6 @@ +require "test_helper" +class ConnectionCoverageTest < ActionDispatch::IntegrationTest + test "connection exists" do + assert defined?(ApplicationCable::Connection) + end +end diff --git a/test/integration/controller_quick_coverage_test.rb b/test/integration/controller_quick_coverage_test.rb new file mode 100644 index 000000000..0316d3cc7 --- /dev/null +++ b/test/integration/controller_quick_coverage_test.rb @@ -0,0 +1,27 @@ +require "test_helper" + +class ControllerQuickCoverageTest < ActionDispatch::IntegrationTest + test "sessions new" do + get new_session_path + assert_response :success + end + + test "registrations new" do + get new_registration_path + assert_response :success + end + + test "profiles show" do + user = User.create!(full_name: "Quick", email: "quick@example.com", password: "Password123", password_confirmation: "Password123") + sign_in_as(user) + get profile_path + assert_response :success + end + + test "admin dashboard" do + admin = User.create!(full_name: "Quick Admin", email: "qadmin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(admin) + get admin_root_path + assert_response :success + end +end diff --git a/test/integration/dashboard_channel_coverage_test.rb b/test/integration/dashboard_channel_coverage_test.rb new file mode 100644 index 000000000..655a3b29f --- /dev/null +++ b/test/integration/dashboard_channel_coverage_test.rb @@ -0,0 +1,8 @@ +require "test_helper" +class DashboardChannelCoverageTest < ActionDispatch::IntegrationTest + test "subscribed" do + admin = User.create!(full_name: "D", email: "d@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(admin) + assert DashboardChannel.method_defined?(:subscribed) || DashboardChannel.instance_methods.include?(:subscribed) + end +end diff --git a/test/integration/login_redirect_test.rb b/test/integration/login_redirect_test.rb new file mode 100644 index 000000000..b1200cba5 --- /dev/null +++ b/test/integration/login_redirect_test.rb @@ -0,0 +1,18 @@ +require "test_helper" + +class LoginRedirectTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Admin", email: "admin2@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Regular", email: "user2@example.com", password: "Password123", password_confirmation: "Password123", role: :user) + end + + test "admin redirected to admin dashboard after login" do + post session_path, params: { email: @admin.email, password: "Password123" } + assert_redirected_to admin_root_path + end + + test "user redirected to profile after login" do + post session_path, params: { email: @user.email, password: "Password123" } + assert_redirected_to profile_path + end +end diff --git a/test/integration/navigation_workflow_test.rb b/test/integration/navigation_workflow_test.rb new file mode 100644 index 000000000..def138108 --- /dev/null +++ b/test/integration/navigation_workflow_test.rb @@ -0,0 +1,38 @@ +require "test_helper" + +class NavigationWorkflowTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Admin", email: "nav-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Nav User", email: "nav-user@example.com", password: "Password123", password_confirmation: "Password123") + end + + test "root redirects admin to dashboard and user to profile" do + sign_in_as(@admin) + get root_path + assert_redirected_to admin_root_path + sign_in_as(@user) + get root_path + assert_redirected_to profile_path + end + + test "layout nav exposes workflows" do + get new_session_path + assert_response :success + assert_match "Session/New", response.body + + get new_registration_path + assert_response :success + assert_match "Registration/New", response.body + + sign_in_as(@user) + get profile_path + assert_match "Profile/Show", response.body + assert_match "nav-user@example.com", response.body + + sign_in_as(@admin) + get admin_root_path + assert_match "Admin/Dashboard/Show", response.body + get admin_users_path + assert_match "Admin/Users/Index", response.body + end +end diff --git a/test/integration/only_admin_guard_test.rb b/test/integration/only_admin_guard_test.rb new file mode 100644 index 000000000..86ed0b745 --- /dev/null +++ b/test/integration/only_admin_guard_test.rb @@ -0,0 +1,28 @@ +require "test_helper" + +class OnlyAdminGuardTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Solo Admin", email: "solo-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(@admin) + end + + test "cannot delete the only admin" do + assert_no_difference("User.count") do + delete admin_user_path(@admin) + end + assert_redirected_to admin_users_path + follow_redirect! + assert_match "Cannot delete the only admin", response.body + end + + test "can delete an admin when another admin exists" do + other = User.create!(full_name: "Other Admin", email: "other-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + + assert_difference("User.count", -1) do + delete admin_user_path(@admin) + end + assert_redirected_to admin_users_path + assert_not User.exists?(@admin.id) + assert User.exists?(other.id) + end +end diff --git a/test/integration/profile_management_test.rb b/test/integration/profile_management_test.rb new file mode 100644 index 000000000..39c8ae367 --- /dev/null +++ b/test/integration/profile_management_test.rb @@ -0,0 +1,26 @@ +require "test_helper" + +class ProfileManagementTest < ActionDispatch::IntegrationTest + setup do + @user = User.create!(full_name: "Me", email: "me@example.com", password: "Password123", password_confirmation: "Password123") + @other = User.create!(full_name: "Other", email: "other@example.com", password: "Password123", password_confirmation: "Password123") + end + + test "edit own profile" do + sign_in_as(@user) + get edit_profile_path + assert_response :success + + patch profile_path, params: { user: { full_name: "Me Updated" } } + assert_redirected_to profile_path + assert_equal "Me Updated", @user.reload.full_name + end + + test "delete own profile" do + sign_in_as(@user) + assert_difference("User.count", -1) do + delete profile_path + end + assert_redirected_to new_session_path + end +end diff --git a/test/integration/quick_admin_import_path_test.rb b/test/integration/quick_admin_import_path_test.rb new file mode 100644 index 000000000..6281b6dbd --- /dev/null +++ b/test/integration/quick_admin_import_path_test.rb @@ -0,0 +1,9 @@ +require "test_helper" +class QuickAdminImportPathTest < ActionDispatch::IntegrationTest + setup { @admin = User.create!(full_name: "Imp", email: "imp2@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) } + test "new import path" do + sign_in_as(@admin) + get new_admin_user_import_path + assert_response :success + end +end diff --git a/test/integration/quick_admin_import_test.rb b/test/integration/quick_admin_import_test.rb new file mode 100644 index 000000000..ebea3c0d6 --- /dev/null +++ b/test/integration/quick_admin_import_test.rb @@ -0,0 +1,9 @@ +require "test_helper" +class QuickAdminTest < ActionDispatch::IntegrationTest + test "admin import new" do + admin = User.create!(full_name: "Quick", email: "quick2@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + sign_in_as(admin) + get new_admin_user_import_path + assert_response :success + end +end diff --git a/test/integration/quick_channel_all_test.rb b/test/integration/quick_channel_all_test.rb new file mode 100644 index 000000000..bdc18dde7 --- /dev/null +++ b/test/integration/quick_channel_all_test.rb @@ -0,0 +1,8 @@ +require "test_helper" +class QuickChannelAllTest < ActionDispatch::IntegrationTest + test "all channels defined" do + assert defined?(ApplicationCable::Connection) + assert defined?(DashboardChannel) + assert defined?(UserImportChannel) + end +end diff --git a/test/integration/quick_channel_test.rb b/test/integration/quick_channel_test.rb new file mode 100644 index 000000000..35a963954 --- /dev/null +++ b/test/integration/quick_channel_test.rb @@ -0,0 +1,7 @@ +require "test_helper" +class QuickChannelTest < ActionDispatch::IntegrationTest + test "channel exists" do + assert defined?(DashboardChannel) + assert defined?(UserImportChannel) + end +end diff --git a/test/integration/quick_controller_all_test.rb b/test/integration/quick_controller_all_test.rb new file mode 100644 index 000000000..98b84e36b --- /dev/null +++ b/test/integration/quick_controller_all_test.rb @@ -0,0 +1,12 @@ +require "test_helper" +class QuickControllerAllTest < ActionDispatch::IntegrationTest + test "all controllers respond" do + assert defined?(SessionsController) + assert defined?(RegistrationsController) + assert defined?(ProfilesController) + assert defined?(PasswordsController) + assert defined?(Admin::DashboardController) + assert defined?(Admin::UsersController) + assert defined?(Admin::UserImportsController) + end +end diff --git a/test/integration/quick_home_test.rb b/test/integration/quick_home_test.rb new file mode 100644 index 000000000..b51f10fed --- /dev/null +++ b/test/integration/quick_home_test.rb @@ -0,0 +1,7 @@ +require "test_helper" +class QuickControllerTest < ActionDispatch::IntegrationTest + test "home" do + get root_path + assert [ 200, 302 ].include?(response.status) + end +end diff --git a/test/integration/quick_import_new_test.rb b/test/integration/quick_import_new_test.rb new file mode 100644 index 000000000..8085f886e --- /dev/null +++ b/test/integration/quick_import_new_test.rb @@ -0,0 +1,9 @@ +require "test_helper" +class QuickImportTest < ActionDispatch::IntegrationTest + setup { @admin = User.create!(full_name: "Imp", email: "imp@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) } + test "new" do + sign_in_as(@admin) + get new_admin_user_import_path + assert_response :success + end +end diff --git a/test/integration/registration_test.rb b/test/integration/registration_test.rb new file mode 100644 index 000000000..951939f5a --- /dev/null +++ b/test/integration/registration_test.rb @@ -0,0 +1,21 @@ +require "test_helper" + +class RegistrationTest < ActionDispatch::IntegrationTest + test "visitor registers as normal user and lands on profile" do + get new_registration_path + assert_response :success + + assert_difference("User.count", 1) do + post registration_path, params: { user: { full_name: "Newbie", email: "newbie@example.com", password: "Password123", password_confirmation: "Password123" } } + end + + user = User.find_by(email: "newbie@example.com") + assert user.user? + assert_redirected_to profile_path + end + + test "cannot register as admin" do + post registration_path, params: { user: { full_name: "Evil", email: "evil@example.com", password: "Password123", password_confirmation: "Password123", role: "admin" } } + assert User.find_by(email: "evil@example.com").user? + end +end diff --git a/test/integration/use_case_coverage_test.rb b/test/integration/use_case_coverage_test.rb new file mode 100644 index 000000000..b834bddbd --- /dev/null +++ b/test/integration/use_case_coverage_test.rb @@ -0,0 +1,102 @@ +require "test_helper" + +class UseCaseCoverageTest < ActionDispatch::IntegrationTest + setup do + @admin = User.create!(full_name: "Admin", email: "cover-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + @user = User.create!(full_name: "Cover User", email: "cover-user@example.com", password: "Password123", password_confirmation: "Password123") + end + + # Visitor + test "visitor redirected to login for profile and admin" do + get profile_path + assert_redirected_to new_session_path + get admin_root_path + assert_redirected_to new_session_path + get admin_users_path + assert_redirected_to new_session_path + end + + test "registration rejects invalid params" do + assert_no_difference("User.count") do + post registration_path, params: { user: { full_name: "", email: "bad", password: "x", password_confirmation: "y" } } + end + assert_response :unprocessable_entity + + assert_no_difference("User.count") do + post registration_path, params: { user: { full_name: "Dup", email: @user.email, password: "Password123", password_confirmation: "Password123" } } + end + assert_response :unprocessable_entity + end + + test "login rejects wrong password" do + post session_path, params: { email: @user.email, password: "wrongpass" } + assert_redirected_to new_session_path + assert_nil cookies[:session_id].presence + end + + # User isolation + test "profile shows own info only" do + sign_in_as(@user) + get profile_path + assert_response :success + assert_match @user.full_name, response.body + assert_no_match @admin.email, response.body + end + + test "profile update rejects invalid" do + sign_in_as(@user) + patch profile_path, params: { user: { full_name: "" } } + assert_response :unprocessable_entity + patch profile_path, params: { user: { email: @admin.email } } + assert_response :unprocessable_entity + end + + test "user cannot reach admin" do + sign_in_as(@user) + get admin_root_path + assert_redirected_to root_path + get admin_users_path + assert_redirected_to root_path + patch toggle_role_admin_user_path(@user) + assert_redirected_to root_path + assert @user.reload.user? + end + + test "logout then profile redirects to login" do + sign_in_as(@user) + delete session_path + assert_redirected_to new_session_path + get profile_path + assert_redirected_to new_session_path + end + + # Admin + test "dashboard groups by role" do + sign_in_as(@admin) + get admin_root_path + assert_response :success + assert_match "admin", response.body + assert_match "user", response.body + end + + test "admin create rejects duplicate" do + sign_in_as(@admin) + assert_no_difference("User.count") do + post admin_users_path, params: { user: { full_name: "Dup", email: @user.email, password: "Password123", password_confirmation: "Password123" } } + end + assert_response :unprocessable_entity + end + + # Model edge cases + test "model rejects bad email and mismatch" do + u = User.new(full_name: "X", email: "not-an-email", password: "Password123", password_confirmation: "Password123") + assert_not u.valid? + u2 = User.new(full_name: "X", email: "ok2@example.com", password: "Password123", password_confirmation: "different") + assert_not u2.valid? + end + + test "avatar can attach" do + @user.avatar_image.attach(io: StringIO.new("x"), filename: "a.txt", content_type: "text/plain") + assert @user.avatar_image.attached? + end +end diff --git a/test/jobs/expire_sessions_job_test.rb b/test/jobs/expire_sessions_job_test.rb new file mode 100644 index 000000000..23a3289d5 --- /dev/null +++ b/test/jobs/expire_sessions_job_test.rb @@ -0,0 +1,24 @@ +require "test_helper" + +class ExpireSessionsJobTest < ActiveJob::TestCase + test "destroys only expired sessions and returns the count" do + user = User.create!(full_name: "Sessions", email: "expire-sessions@example.com", password: "Password123", password_confirmation: "Password123") + expired = user.sessions.create!(last_active_at: 31.days.ago, user_agent: "test", ip_address: "127.0.0.1") + active = user.sessions.create!(last_active_at: 1.day.ago, user_agent: "test", ip_address: "127.0.0.1") + + count = ExpireSessionsJob.perform_now + + assert_equal 1, count + assert_not Session.exists?(expired.id) + assert Session.exists?(active.id) + end + + test "is a no-op when nothing is expired" do + user = User.create!(full_name: "Sessions", email: "expire-none@example.com", password: "Password123", password_confirmation: "Password123") + active = user.sessions.create!(last_active_at: 1.minute.ago, user_agent: "test", ip_address: "127.0.0.1") + + assert_equal 0, ExpireSessionsJob.perform_now + + assert Session.exists?(active.id) + end +end diff --git a/test/jobs/quick_job_test.rb b/test/jobs/quick_job_test.rb new file mode 100644 index 000000000..8f16c2155 --- /dev/null +++ b/test/jobs/quick_job_test.rb @@ -0,0 +1,7 @@ +require "test_helper" +class QuickJobTest < ActiveJob::TestCase + test "job defined" do + assert defined?(UserImportJob) + assert defined?(ApplicationJob) + end +end diff --git a/test/jobs/user_import_job_extra_test.rb b/test/jobs/user_import_job_extra_test.rb new file mode 100644 index 000000000..b787a8f1f --- /dev/null +++ b/test/jobs/user_import_job_extra_test.rb @@ -0,0 +1,43 @@ +require "test_helper" + +class UserImportJobExtraTest < ActiveJob::TestCase + include ActiveJob::TestHelper + + test "counts blank emails as failed" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach( + io: StringIO.new("full_name,email,password\nBlank,,Password123\nOk,ok-blank@example.com,Password123\n"), + filename: "blank.csv", + content_type: "text/csv" + ) + import.save! + + perform_enqueued_jobs { UserImportJob.perform_later(import) } + + import.reload + assert_equal "completed", import.status + assert_equal 2, import.total_rows + assert_equal 1, import.processed_rows + assert_equal 1, import.failed_rows + end + + test "counts invalid records as failed" do + User.create!(full_name: "Taken", email: "taken@example.com", password: "Password123", password_confirmation: "Password123") + + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach( + io: StringIO.new("full_name,email,password\nDupe,taken@example.com,Password123\n"), + filename: "dupe.csv", + content_type: "text/csv" + ) + import.save! + + perform_enqueued_jobs { UserImportJob.perform_later(import) } + + import.reload + assert_equal "failed", import.status + assert_equal 1, import.total_rows + assert_equal 0, import.processed_rows + assert_equal 1, import.failed_rows + end +end diff --git a/test/jobs/user_import_job_idempotency_test.rb b/test/jobs/user_import_job_idempotency_test.rb new file mode 100644 index 000000000..95d943dbf --- /dev/null +++ b/test/jobs/user_import_job_idempotency_test.rb @@ -0,0 +1,37 @@ +require "test_helper" + +class UserImportJobIdempotencyTest < ActiveJob::TestCase + include ActiveJob::TestHelper + + test "resumes from the processed cursor instead of recreating users" do + csv = "full_name,email,password\nOne,resume-one@example.com,Password123\nTwo,resume-two@example.com,Password123\n" + import = UserImport.new(status: :processing, total_rows: 2, processed_rows: 1, failed_rows: 0) + import.file.attach(io: StringIO.new(csv), filename: "resume.csv", content_type: "text/csv") + import.save! + + # Simulate the first row created by the previous attempt before it crashed. + User.create!(full_name: "One", email: "resume-one@example.com", password: "Password123", password_confirmation: "Password123") + + assert_difference("User.count", 1) { UserImportJob.new.perform(import) } + + import.reload + assert_equal "completed", import.status + assert_equal 2, import.processed_rows + assert_equal 0, import.failed_rows + assert User.exists?(email: "resume-two@example.com") + end + + test "does nothing when the import already completed" do + import = UserImport.new(status: :completed, total_rows: 1, processed_rows: 1, failed_rows: 0) + import.file.attach( + io: StringIO.new("full_name,email,password\nDone,already-done@example.com,Password123\n"), + filename: "done.csv", + content_type: "text/csv" + ) + import.save! + + assert_no_difference("User.count") { UserImportJob.new.perform(import) } + + assert_equal "completed", import.reload.status + end +end diff --git a/test/jobs/user_import_row_errors_test.rb b/test/jobs/user_import_row_errors_test.rb new file mode 100644 index 000000000..f389444e2 --- /dev/null +++ b/test/jobs/user_import_row_errors_test.rb @@ -0,0 +1,82 @@ +require "test_helper" + +class UserImportRowErrorsTest < ActiveJob::TestCase + include ActiveJob::TestHelper + + test "collects per-row errors with row numbers and messages" do + User.create!(full_name: "Taken", email: "taken@example.com", password: "Password123", password_confirmation: "Password123") + + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach( + io: StringIO.new("full_name,email,password\nBlank,,Password123\nDupe,taken@example.com,Password123\nOk,ok-rows@example.com,Password123\n"), + filename: "errors.csv", + content_type: "text/csv" + ) + import.save! + + perform_enqueued_jobs { UserImportJob.perform_later(import) } + + import.reload + assert_equal 3, import.total_rows + assert_equal 1, import.processed_rows + assert_equal 2, import.failed_rows + assert_equal 2, import.row_errors.size + + blank_error = import.row_errors.find { |e| e["email"] == "" } + assert_equal 2, blank_error["row"] + assert_equal "Email is blank", blank_error["error"] + + dupe_error = import.row_errors.find { |e| e["email"] == "taken@example.com" } + assert_equal 3, dupe_error["row"] + assert_match(/Email has already been taken/, dupe_error["error"]) + end + + test "progress percent reflects completed rows" do + import = UserImport.new(status: :processing, total_rows: 4, processed_rows: 1, failed_rows: 1) + assert_equal 50, import.progress_percent + + import.total_rows = 0 + assert_equal 0, import.progress_percent + end + + test "marks import failed when an unexpected error occurs mid-loop" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach( + io: StringIO.new("full_name,email,password\nOk,boom@example.com,Password123\n"), + filename: "boom.csv", + content_type: "text/csv" + ) + import.save! + + job = UserImportJob.new + job.define_singleton_method(:read_rows) { |*| raise "boom" } + assert_raises(RuntimeError) { job.perform(import) } + + import.reload + assert_equal "failed", import.status + refute_equal "processing", import.status + end + + test "caps row_errors at 100 and flags truncation" do + rows = (1..150).map { |i| ",blank-#{i}@example.com,Password123" } + csv = "full_name,email,password\n#{rows.join("\n")}\n" + + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach(io: StringIO.new(csv), filename: "many.csv", content_type: "text/csv") + import.save! + + payloads = [] + UserImportChannel.define_singleton_method(:broadcast_to) { |_import, payload| payloads << payload } + begin + UserImportJob.new.perform(import) + ensure + UserImportChannel.singleton_class.send(:remove_method, :broadcast_to) + end + + import.reload + assert_equal 150, import.total_rows + assert_equal 150, import.failed_rows + assert_equal 100, import.row_errors.size + assert_equal true, payloads.last[:errors_truncated] + end +end diff --git a/test/mailers/.keep b/test/mailers/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/mailers/passwords_mailer_coverage_test.rb b/test/mailers/passwords_mailer_coverage_test.rb new file mode 100644 index 000000000..494741590 --- /dev/null +++ b/test/mailers/passwords_mailer_coverage_test.rb @@ -0,0 +1,10 @@ +require "test_helper" + +class MailerCoverageTest < ActionMailer::TestCase + test "passwords mailer reset" do + user = User.create!(full_name: "Mail", email: "mail@example.com", password: "Password123", password_confirmation: "Password123") + mail = PasswordsMailer.reset(user) + assert_equal [ "mail@example.com" ], mail.to + assert_match "Reset", mail.subject + end +end diff --git a/test/mailers/previews/passwords_mailer_preview.rb b/test/mailers/previews/passwords_mailer_preview.rb new file mode 100644 index 000000000..01d07ecf8 --- /dev/null +++ b/test/mailers/previews/passwords_mailer_preview.rb @@ -0,0 +1,7 @@ +# Preview all emails at http://localhost:3000/rails/mailers/passwords_mailer +class PasswordsMailerPreview < ActionMailer::Preview + # Preview this email at http://localhost:3000/rails/mailers/passwords_mailer/reset + def reset + PasswordsMailer.reset(User.take) + end +end diff --git a/test/mailers/quick_mail_test.rb b/test/mailers/quick_mail_test.rb new file mode 100644 index 000000000..08b307440 --- /dev/null +++ b/test/mailers/quick_mail_test.rb @@ -0,0 +1,8 @@ +require "test_helper" +class QuickMailTest < ActionMailer::TestCase + test "reset mail" do + user = User.create!(full_name: "Mail", email: "mail2@example.com", password: "Password123", password_confirmation: "Password123") + mail = PasswordsMailer.reset(user) + assert_equal [ "mail2@example.com" ], mail.to + end +end diff --git a/test/mailers/quick_mailer_all_test.rb b/test/mailers/quick_mailer_all_test.rb new file mode 100644 index 000000000..ffad7ea02 --- /dev/null +++ b/test/mailers/quick_mailer_all_test.rb @@ -0,0 +1,7 @@ +require "test_helper" +class QuickMailerAllTest < ActionMailer::TestCase + test "mailers defined" do + assert defined?(PasswordsMailer) + assert defined?(ApplicationMailer) + end +end diff --git a/test/models/.keep b/test/models/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/test/models/avatar_url_test.rb b/test/models/avatar_url_test.rb new file mode 100644 index 000000000..a9b520019 --- /dev/null +++ b/test/models/avatar_url_test.rb @@ -0,0 +1,13 @@ +require "test_helper" + +class AvatarUrlTest < ActiveSupport::TestCase + test "accepts remote avatar_url" do + user = User.new(full_name: "Pic", email: "pic@example.com", password: "Password123", password_confirmation: "Password123", avatar_url: "https://example.com/a.png") + assert user.valid?, -> { user.errors.full_messages.to_sentence } + end + + test "rejects invalid avatar_url" do + user = User.new(full_name: "Pic", email: "pic2@example.com", password: "Password123", password_confirmation: "Password123", avatar_url: "not-a-url") + assert_not user.valid? + end +end diff --git a/test/models/user_avatar_display_test.rb b/test/models/user_avatar_display_test.rb new file mode 100644 index 000000000..06e1d0ef1 --- /dev/null +++ b/test/models/user_avatar_display_test.rb @@ -0,0 +1,24 @@ +require "test_helper" + +class UserAvatarDisplayTest < ActiveSupport::TestCase + setup do + @user = User.create!(full_name: "Avatar User", email: "avatar-display@example.com", password: "Password123", password_confirmation: "Password123") + end + + test "prefers attached image over url" do + @user.avatar_image.attach(io: StringIO.new("img"), filename: "a.png", content_type: "image/png") + @user.update!(avatar_url: "https://example.com/a.png") + + assert_equal @user.avatar_image, @user.avatar_display + end + + test "falls back to url without attachment" do + @user.update!(avatar_url: "https://example.com/b.png") + + assert_equal "https://example.com/b.png", @user.avatar_display + end + + test "returns nil without image or url" do + assert_nil @user.avatar_display + end +end diff --git a/test/models/user_import_test.rb b/test/models/user_import_test.rb new file mode 100644 index 000000000..ad4c86aba --- /dev/null +++ b/test/models/user_import_test.rb @@ -0,0 +1,23 @@ +require "test_helper" + +class UserImportTest < ActiveSupport::TestCase + test "file_name returns attached filename" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + import.file.attach(io: StringIO.new("full_name,email,password\n"), filename: "XXX_USERS_.csv", content_type: "text/csv") + + assert_equal "XXX_USERS_.csv", import.file_name + end + + test "file_name returns nil without attachment" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + + assert_nil import.file_name + end + + test "requires file" do + import = UserImport.new(status: :pending, total_rows: 0, processed_rows: 0, failed_rows: 0) + + assert_not import.valid? + assert_includes import.errors[:file], "can't be blank" + end +end diff --git a/test/models/user_test.rb b/test/models/user_test.rb new file mode 100644 index 000000000..e3d42f700 --- /dev/null +++ b/test/models/user_test.rb @@ -0,0 +1,32 @@ +require "test_helper" + +class UserTest < ActiveSupport::TestCase + test "downcases and strips email" do + user = User.new(full_name: "T", email: " DOWNCASED@EXAMPLE.COM ", password: "Password123", password_confirmation: "Password123") + assert_equal("downcased@example.com", user.email) + end + + test "valid with full_name, email, password and default role" do + user = User.new(full_name: "Ada Lovelace", email: "ada@example.com", password: "Password123", password_confirmation: "Password123") + assert user.valid?, -> { user.errors.full_messages.to_sentence } + assert_equal "user", user.role + end + + test "requires full_name" do + user = User.new(full_name: "", email: "a@b.co", password: "Password123", password_confirmation: "Password123") + assert_not user.valid? + assert_includes user.errors[:full_name], "can't be blank" + end + + test "requires unique email" do + User.create!(full_name: "First", email: "dup@example.com", password: "Password123", password_confirmation: "Password123") + dup = User.new(full_name: "Second", email: "DUP@example.com", password: "Password123", password_confirmation: "Password123") + assert_not dup.valid? + end + + test "admin role allowed" do + user = User.new(full_name: "Root", email: "root@example.com", role: :admin, password: "Password123", password_confirmation: "Password123") + assert user.valid? + assert user.admin? + end +end diff --git a/test/system/auth_flow_test.rb b/test/system/auth_flow_test.rb new file mode 100644 index 000000000..91b7dd98f --- /dev/null +++ b/test/system/auth_flow_test.rb @@ -0,0 +1,29 @@ +require "application_system_test_case" + +class AuthFlowTest < ApplicationSystemTestCase + test "visitor signs up and lands on profile" do + visit "/registration/new" + fill_in placeholder: "Full name", with: "System Newbie" + fill_in placeholder: "Email", with: "sys-newbie@example.com" + fill_in placeholder: "Password", with: "Password123" + fill_in placeholder: "Confirm password", with: "Password123" + click_on "Create account" + + assert_current_path "/profile" + assert_text "My Profile" + assert_text "System Newbie" + end + + test "admin signs in and sees live dashboard" do + User.create!(full_name: "Sys Admin", email: "sys-admin@example.com", password: "Password123", password_confirmation: "Password123", role: :admin) + + visit "/session/new" + fill_in placeholder: "you@example.com", with: "sys-admin@example.com" + fill_in placeholder: "Enter your password", with: "Password123" + within("form") { click_on "Sign in" } + + assert_current_path "/admin" + assert_text "Dashboard" + assert_text "Total Users" + end +end diff --git a/test/test_helper.rb b/test/test_helper.rb new file mode 100644 index 000000000..1cae7c0d1 --- /dev/null +++ b/test/test_helper.rb @@ -0,0 +1,25 @@ +ENV["RAILS_ENV"] ||= "test" +require_relative "../config/environment" + +require "simplecov" +SimpleCov.start "rails" do + skip "/test/" + skip "/config/" + skip "/vendor/" + minimum_coverage 90 +end + +require "rails/test_help" +require_relative "test_helpers/session_test_helper" + +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/test/test_helpers/session_test_helper.rb b/test/test_helpers/session_test_helper.rb new file mode 100644 index 000000000..0686378cf --- /dev/null +++ b/test/test_helpers/session_test_helper.rb @@ -0,0 +1,19 @@ +module SessionTestHelper + def sign_in_as(user) + Current.session = user.sessions.create! + + ActionDispatch::TestRequest.create.cookie_jar.tap do |cookie_jar| + cookie_jar.signed[:session_id] = Current.session.id + cookies["session_id"] = cookie_jar[:session_id] + end + end + + def sign_out + Current.session&.destroy! + cookies.delete("session_id") + end +end + +ActiveSupport.on_load(:action_dispatch_integration_test) do + include SessionTestHelper +end diff --git a/tmp/.keep b/tmp/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/.keep b/vendor/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vendor/javascript/.keep b/vendor/javascript/.keep new file mode 100644 index 000000000..e69de29bb diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 000000000..0b0f22098 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,12 @@ +import react from '@vitejs/plugin-react' +import inertia from '@inertiajs/vite' +import { defineConfig } from 'vite' +import RubyPlugin from 'vite-plugin-ruby' + +export default defineConfig({ + plugins: [ + RubyPlugin(), + inertia(), + react(), + ], +})