{
  "clusterId": "03_CORE_CourseService",
  "featureFocus": "Core Course Management, Enrollments, and Structure Microservice",
  "documentationReport": "{\n  \"documentation_report\": \"Xikolo Unified Course Management and Learning Evaluation System\\n\\nThis document synthesizes the capabilities of a merged software cluster, presenting a comprehensive system for managing educational course content, enrollments, and now, robust learning evaluation and statistics. The system integrates the foundational `Xikolo::CourseService` with specialized components for performance analytics, offering an end-to-end solution for educational platforms.\\n\\n1. Core Course Management (Xikolo::CourseService)\\n\\nThe `Xikolo::CourseService` microservice forms the backbone of this system, primarily responsible for the lifecycle management of course content, student enrollments, and the structural organization of learning materials.\\n\\n*   **Public API:** The service exposes a public API (v2) specifically for managing courses and enrollments, facilitating external integrations and client-side interactions.\\n*   **Course Entities:**\\n    *   **Courses:** Central entities managed by the `CoursesController`. Courses possess key attributes such as `title`, `status`, `description`, `course_code`, `start_date`, and `end_date`.\\n    *   **Course States:** Courses can transition through various states: `preparation`, `announced`, `preview`, `active`, `self-paced`, or `external`, reflecting their current availability and operational status. The `Course` model includes logic for status transitions, including auto-archiving.\\n    *   **Search & Indexing:** Course search functionality is supported by a `search_data` column, which is updated asynchronously by the `UpdateCourseSearchIndexWorker` to ensure efficient and up-to-date search results.\\n    *   **Event Publishing:** The `Course` model publishes events via `Msgr` (RabbitMQ) upon creation, update, and deletion, enabling other services to react to changes in course data.\\n*   **Course Structure:**\\n    *   **Sections:** Courses are organized into `Sections`, providing a logical grouping for learning materials.\\n    *   **Items:** Each `Section` contains `Items`, which represent individual learning activities or content units.\\n    *   **Ordering & Availability:** Both `Section` and `Item` models support ordering (`acts_as_list`) and include logic for publishing status and date-based availability, allowing for controlled release of content.\\n\\n2. Learning Evaluation and Statistics\\n\\nAugmenting the core course management, this merged cluster now incorporates a dedicated functional domain for learning evaluation and statistics. This capability provides deep insights into student performance and engagement with course materials.\\n\\n*   **Key Components & Capabilities:**\\n    *   **ItemGradeController:** Manages and exposes grading information for individual learning `Item`s within courses.\\n    *   **ItemResultsController:** Provides functionality to track and retrieve student results for various course `Item`s, offering a detailed view of performance.\\n    *   **ItemStatisticsController:** Delivers statistical insights related to course `Item`s, potentially including completion rates, average scores, and common difficulties.\\n    *   **LastVisitsController:** Tracks and reports on the last visit times of users to course components, aiding in monitoring student engagement and progress.\\n    *   **LearningEvaluation::RecalculationsController:** Handles the recalculation of learning evaluation metrics, ensuring that aggregated data and performance indicators are always current and accurate.\\n\\n3. Technical Architecture\\n\\nThe system is built on a robust and modern technology stack, designed for scalability and maintainability.\\n\\n*   **Framework:** Ruby on Rails 7.2.0\\n*   **Programming Language:** Ruby 3.4.0\\n*   **Data Persistence:** PostgreSQL, serving as the primary relational database for all course and evaluation data.\\n*   **Inter-service Communication:** RabbitMQ, utilized via the `msgr` gem, facilitates asynchronous messaging and event-driven communication between services, particularly for publishing course-related events.\\n*   **Background Processing:** Sidekiq is employed for managing and executing background jobs, such as updating course search indexes (`UpdateCourseSearchIndexWorker`), ensuring that resource-intensive tasks do not impact real-time user experience.\\n\\n4. Unified Functional Domain\\n\\nThis merged cluster establishes a unified functional domain that spans from the creation and structured delivery of educational content to the comprehensive analysis of learning outcomes. By combining the `Xikolo::CourseService`'s robust content and enrollment management with advanced learning evaluation and statistics, the system provides a holistic platform for educators and learners, enabling better course design, personalized learning paths, and data-driven pedagogical improvements.\\n\\n5. Key Components Overview\\n\\n*   **Controllers:**\\n    *   `CoursesController`\\n    *   `ItemGradeController`\\n    *   `ItemResultsController`\\n    *   `ItemStatisticsController`\\n    *   `LastVisitsController`\\n    *   `LearningEvaluation::RecalculationsController`\\n*   **Models:**\\n    *   `Course`\\n    *   `Section`\\n    *   `Item`\\n*   **Workers:**\\n    *   `UpdateCourseSearchIndexWorker`\"\n}",
  "componentMapPatch": {
    "components": {
      "CourseConsumer": {
        "type": "Consumer",
        "description": "A RabbitMQ consumer responsible for handling course-related messages, specifically for cloning courses. It acknowledges messages to prevent multiple nodes from processing the same job. [Source: services/course/app/consumers/course_consumer.rb]",
        "interactions": {
          "interaction_0": "Processes `clone` messages from RabbitMQ. [Source: services/course/app/consumers/course_consumer.rb]",
          "interaction_1": "Delegates course cloning logic to `Course::Clone`. [Source: services/course/app/consumers/course_consumer.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/consumers/course_consumer.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 16,
              "code": "class CourseConsumer < Msgr::Consumer\n  def clone\n    return unless payload \\\n      && payload[:old_course_id] \\\n      && payload[:new_course_code]\n\n    # were the node that will take care, avoid multiple nodes taking care\n    message.ack\n    # lets do the job\n    Course::Clone.call(\n      payload[:old_course_id],\n      payload[:new_course_code]\n    )\n  end\nend",
              "source": "services/course/app/consumers/course_consumer.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/consumers/course_consumer.rb",
              "relevance": 19
            }
          ]
        }
      },
      "AchievementsController": {
        "type": "Controller",
        "description": "Handles API requests related to user achievements within a course. It uses `Responders` for API formatting, decoration, and HTTP caching. [Source: services/course/app/controllers/achievements_controller.rb]",
        "interactions": {
          "interaction_0": "Responds to `GET /achievements` to list achievements for a given course and user. [Source: services/course/app/controllers/achievements_controller.rb]",
          "interaction_1": "Sets locale based on `http_accept_language`. [Source: services/course/app/controllers/achievements_controller.rb]",
          "interaction_2": "Interacts with `Achievements` (model not provided in chunk) to retrieve data. [Source: services/course/app/controllers/achievements_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/achievements_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 23,
              "code": "# frozen_string_literal: true\n\nclass AchievementsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder\n\n  respond_to :json\n  before_action :set_locale\n\n  def index\n    respond_with Achievements.new(params[:course_id], params[:user_id])\n  end\n\n  private\n\n  def set_locale\n    I18n.locale = http_accept_language\n      .preferred_language_from(Xikolo.config.locales['available'])\n    response.headers['Content-Language'] = I18n.locale.to_s\n  end\nend",
              "source": "services/course/app/controllers/achievements_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/achievements_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ChannelsController": {
        "type": "Controller",
        "description": "Manages `Channel` resources, providing API endpoints for listing, viewing, creating, updating, and destroying channels. It supports filtering channels by public status, highlight status, and code. [Source: services/course/app/controllers/channels_controller.rb]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Channel` models. [Source: services/course/app/controllers/channels_controller.rb]",
          "interaction_1": "Uses `UUID4` for generating new channel IDs. [Source: services/course/app/controllers/channels_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/channels_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 45,
              "code": "# frozen_string_literal: true\n\nclass ChannelsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def index\n    channels = Channel.where(affiliated: false)\n\n    channels = channels.where(public: true) if params[:public] == 'true'\n    channels = channels.where(highlight: true) if params[:highlight] == 'true'\n    channels = channels.where(code: params[:code]) unless params[:code].nil?\n\n    respond_with channels\n  end\n\n  def show\n    respond_with channel\n  end\n\n  def create\n    @channel = Channel.create! channel_params.merge(id: UUID4.new)\n\n    respond_with @channel\n  rescue ActiveRecord::RecordInvalid => e\n    respond_with e.record\n  end\n\n  def update\n    channel.update(channel_params)\n    respond_with channel\n  end\n\n  def destroy\n    respond_with channel.destroy\n  end\n\n  def max_per_page\n    250\n  end\n\n  private\n\n  def channel\n    @channel ...",
              "source": "services/course/app/controllers/channels_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/channels_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ClassifiersController": {
        "type": "Controller",
        "description": "Handles API requests for `Classifier` resources, allowing listing and viewing of individual classifiers. It supports filtering by cluster ID and a search query. [Source: services/course/app/controllers/classifiers_controller.rb]",
        "interactions": {
          "interaction_0": "Retrieves `Classifier` records based on various filters. [Source: services/course/app/controllers/classifiers_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/classifiers_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 30,
              "code": "# frozen_string_literal: true\n\nmodule Admin\n  module Ajax\n    class ClassifiersController < Abstract::AjaxController\n      before_action :ensure_logged_in\n      require_permission 'course.course.edit'\n      respond_to? :json\n\n      def index\n        classifiers = ::Course::Classifier.all\n\n        if params[:cluster].present?\n          classifiers = classifiers.where(cluster_id: params[:cluster])\n        end\n\n        if params[:q].present?\n          classifiers = classifiers.query(params[:q])\n        end\n\n        render json: serialize_classifiers(classifiers)\n      end\n\n      private\n\n      def serialize_classifiers(classifiers)\n        classifiers.map do |classifier|\n          {\n            id: classifier.id,\n            title: classifier.title,\n            cluster_id: classifier.cluster_id,\n            translations: classifier.translations,\n          }.compact\n        end\n      end\n    end\n  end\nend",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 29,
              "code": "# frozen_string_literal: true\n\nclass ClassifiersController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def index\n    classifiers = Classifier.all\n\n    if params['cluster'].present?\n      classifiers.where! cluster_id: params['cluster'].split(',')\n    end\n\n    unless params['q'].nil?\n      classifiers.where! 'title LIKE ?', \"%#{params['q']}%\"\n    end\n\n    respond_with classifiers.offset(params['offset'].to_i)\n  end\n\n  def show\n    respond_with Classifier.find params[:id]\n  end\n\n  def max_per_page\n    500\n  end\nend",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 17,
              "code": "# frozen_string_literal: true\n\nmodule Abstract\n  ##\n  # A base class for all controllers handling AJAX requests\n  class AjaxController < ::ApplicationController\n    rescue_from Status::Unauthorized do\n      render status: :forbidden, json: {errors: 'forbidden'}\n    end\n\n    private\n\n    def ensure_logged_in\n      return true if current_user.logged_in?\n\n      head :forbidden\n    end",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/admin/ajax/classifiers_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/course/app/controllers/classifiers_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "CoursesController": {
        "type": "Controller",
        "description": "The primary controller for managing `Course` resources. It provides extensive filtering capabilities for listing courses, as well as endpoints for showing, creating, updating, and destroying courses. [Source: services/course/app/controllers/courses_controller.rb] It integrates with `Enrollment` for user-specific course listings and `Classifier` for categorization. [Source: services/course/app/controllers/courses_controller.rb, docs/app/features/courses/classifiers.md]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Course` models. [Source: services/course/app/controllers/courses_controller.rb]",
          "interaction_1": "Filters courses by `cat_id` (classifier), `user_id` (enrollment status), `status`, `lang`, `course_code`, `channel_id`, `document_id`, `upcoming`, `current`, `finished`, `public`, `hidden`, `only_hidden`, `exclude_external`, `latest_first`, `alphabetic`, `promoted_for`, `not_enrolled`, `autocomplete`, `active_after`, and `sort` parameters. [Source: services/course/app/controllers/courses_controller.rb]",
          "interaction_2": "Delegates course creation to `Course::Create.call` and updates to `Course::Update.call`. [Source: services/course/app/controllers/courses_controller.rb]",
          "interaction_3": "Delegates course destruction to `Course::Destroy.call`. [Source: services/course/app/controllers/courses_controller.rb]",
          "interaction_4": "Interacts with `Enrollment` to filter courses based on user enrollment status. [Source: services/course/app/controllers/courses_controller.rb]",
          "interaction_5": "Interacts with `Cluster` to validate classifier parameters. [Source: services/course/app/controllers/courses_controller.rb]"
        },
        "techDebt": [
          "The `index` method contains a very large number of conditional filters, which could be refactored into a more modular query object pattern for better readability and maintainability. [Source: services/course/app/controllers/courses_controller.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/courses_controller.rb",
            "docs/app/features/courses/classifiers.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 10,
              "endLine": 18,
              "code": "      def index\n        authorize_any! 'course.course.index', 'course.document.manage'\n\n        courses = course_api.rel(:courses).get({\n          autocomplete: params[:q],\n          offset: params[:offset],\n          limit: 50,\n        }).value!\n\n        render json: courses.map {|c| {id: c['id'], text: \"#{c['title']} (#{c['course_code']})\"} }\n      end",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            },
            {
              "startLine": 8,
              "endLine": 19,
              "code": "      def index\n        courses = []\n        Xikolo.paginate(\n          course_api.rel(:courses).get({hidden: false})\n        ) do |course|\n          next if course['invite_only']\n\n          courses << serialize(course)\n        end\n\n        render json: courses\n      end",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            },
            {
              "startLine": 22,
              "endLine": 38,
              "code": "      def serialize(course)\n        {\n          id: course['id'],\n          title: course['title'],\n          course_code: course['course_code'],\n          start_date: course['start_date'],\n          language: course['lang'],\n          self_paced: course['status'] == 'archive',\n          certificates: {\n            roa: {\n              enabled: course['roa_enabled'],\n              requirement: course['roa_threshold_percentage'],\n            },\n            cop: {\n              enabled: course['cop_enabled'],\n              requirement: course['cop_threshold...\n",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            },
            {
              "startLine": 10,
              "endLine": 14,
              "code": "      def index\n        response.link(bridges_transpipe_courses_url(page: page + 1), rel: 'next') if courses.rel?(:next)\n        response.link(bridges_transpipe_courses_url(page: page - 1), rel: 'prev') if courses.rel?(:prev)\n\n        render json: courses.map {|course| serialize_course_for_index(course) }\n      end",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            },
            {
              "startLine": 16,
              "endLine": 20,
              "code": "      def show\n        return head(:not_found, content_type: 'text/plain') if external_course?\n\n        render json: serialize_course_for_show(course)\n      rescue Restify::NotFound\n        head(:not_found, content_type: 'text/plain')\n      end",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            },
            {
              "startLine": 23,
              "endLine": 27,
              "code": "      def courses\n        @courses ||= course_api.rel(:courses)\n          .get({exclude_external: true, latest_first: true, page:})\n          .value!\n      end",
              "source": "app/controllers/admin/ajax/courses_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/admin/ajax/courses_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/bridges/chatbot/courses_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/bridges/transpipe/courses_controller.rb",
              "relevance": 24
            }
          ]
        }
      },
      "EnrollmentsController": {
        "type": "Controller",
        "description": "Manages `Enrollment` resources, providing API endpoints for listing, viewing, creating, updating, and destroying enrollments. It supports filtering enrollments by course, user, and completion status. [Source: services/course/app/controllers/enrollments_controller.rb]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Enrollment` models. [Source: services/course/app/controllers/enrollments_controller.rb]",
          "interaction_1": "Filters enrollments by `course_id`, `user_id`, `learning_evaluation`, `deleted`, `current_course`, and `proctored`. [Source: services/course/app/controllers/enrollments_controller.rb]",
          "interaction_2": "Delegates enrollment creation to `Enrollment::Create.call`, updates to `Enrollment::Update.call`, and deletion to `Enrollment::Delete.call`. [Source: services/course/app/controllers/enrollments_controller.rb]",
          "interaction_3": "Interacts with `Course` to find the relevant course for an enrollment. [Source: services/course/app/controllers/enrollments_controller.rb]",
          "interaction_4": "Uses `LearningEvaluation.by_params` for filtering. [Source: services/course/app/controllers/enrollments_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/enrollments_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 35,
              "code": "# frozen_string_literal: true\n\nmodule PortalAPI\n  class EnrollmentsController < BaseController\n    before_action :require_authorization_header!\n    before_action :require_shared_secret!\n    before_action do\n      allow_content_types! ALLOWED_CONTENT_TYPES[action_name.to_sym]\n    end\n\n    ALLOWED_CONTENT_TYPES = {\n      index: %w[application/vnd.openhpi.enrollments+json;v=1.0],\n      create: %w[application/vnd.openhpi.enrollment+json;v=1.0],\n    }.freeze\n\n    def index\n      if params[:user_id].blank?\n        return problem_details(\n          'parameter_missing',\n          'The user_id cannot be blank.',\n          status: :unprocessable_entity\n        )\n      end\n\n      response.headers['Content-Type'] = 'application/vnd.openhpi.enrollments+json;v=1.0'\n\n      render json: enrollments.map {|enrollment| serialize_enrollment(enrollment) }\n    rescue CourseNotFound, UserNotFound\n      problem_details(\n        'course_or_user_not_found',\n        'Course or user not found.',\n        status: :...",
              "source": "app/controllers/portal_api/enrollments_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 37,
              "code": "# frozen_string_literal: true\n\nclass EnrollmentsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  # List allowed filter parameters for #index here.\n  rfc6570_params index: %i[\n    course_id\n    user_id\n    learning_evaluation\n    deleted\n    current_course\n    per_page\n    proctored\n  ]\n  def index\n    enrollments = Enrollment.all\n\n    # eliminate enrollments from deleted courses\n    enrollments = enrollments.left_joins(:course).where({courses: {deleted: false}})\n\n    enrollments = enrollments.active unless params[:deleted] == 'true'\n\n    if params[:course_id].present?\n      enrollments.where! course_id: course.id\n    end\n\n    enrollments.where! user_id: params[:user_id] if params[:user_id].present?\n\n    if params[:proctored].present?\n      enrollments.where! proctored: params[:proctored]\n    end\n\n    if params[:completed].present?\n    ...",
              "source": "app/controllers/portal_api/enrollments_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/portal_api/enrollments_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/course/app/controllers/enrollments_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ItemsController": {
        "type": "Controller",
        "description": "Manages `Item` resources, which represent individual learning content units within sections. It provides extensive filtering for listing items and handles CRUD operations. It also includes logic for 'open mode' and user-specific item access. [Source: services/course/app/controllers/items_controller.rb, docs/app/features/courses/open_mode.md]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Item` models. [Source: services/course/app/controllers/items_controller.rb]",
          "interaction_1": "Filters items by `content_type`, `exercise_type`, `section_id`, `content_id`, `id`, `available`, `all_available`, `was_available`, `published`, `course_id`, `featured`, `open_mode`, `required_items`, `state_for`, `proctored`, `user_id`, and `new_for`. [Source: services/course/app/controllers/items_controller.rb]",
          "interaction_2": "Interacts with `Section`, `Course`, `Visit`, and `Structure::UserItemsSelector` for complex filtering and access control. [Source: services/course/app/controllers/items_controller.rb]",
          "interaction_3": "Handles versioning of items using `paper_trail`. [Source: services/course/app/controllers/items_controller.rb]",
          "interaction_4": "Determines 'current' item for a user based on last visit or first available item. [Source: services/course/app/controllers/items_controller.rb]"
        },
        "techDebt": [
          "The `index` method has a complex conditional logic for filtering, especially regarding `exercise_type` and `available` scopes, which could be simplified. [Source: services/course/app/controllers/items_controller.rb]",
          "The `TODO` comment regarding dropping items where requirements are not fulfilled suggests a known limitation due to the microservice architecture. [Source: services/course/app/controllers/items_controller.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/items_controller.rb",
            "docs/app/features/courses/open_mode.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 35,
              "code": "class ItemsController < Abstract::FrontendController\n  include CourseContextHelper\n  include ItemContextHelper\n\n  before_action :set_no_cache_headers\n\n  include Interruptible\n\n  before_action :ensure_content_editor, except: :show\n  before_action :load_user_preferences, only: :show, if: proc {|_| current_user.authenticated? }\n\n  inside_course\n  inside_item only: :show\n  before_action :load_section_nav, except: :destroy\n\n  respond_to :json, :xml\n\n  def request_section\n    if params[:action] == 'show'\n      course_api.rel(:section).get({id: UUID(item['section_id'])})\n    else\n      super\n    end\n  end\n\n  def request_item\n    return nil unless params[:id]\n    raise Status::NotFound if (uuid = UUID4.try_convert(params[:id])).nil?\n\n    get_params = {id: uuid.to_s}.tap do |p|\n      # Authorized users (e.g., course admins) can always access items, but\n      # for regular learners the user-specific access is verified.\n      p[:user_id] = current_user.id unless cur...",
              "source": "app/controllers/items_controller.rb"
            },
            {
              "startLine": 4,
              "endLine": 33,
              "code": "class ItemsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n  include PointsProcessor\n\n  respond_to :json\n\n  def index\n    items = Item.all\n    items.where! content_type: params[:content_type] if params[:content_type]\n    if params[:exercise_type]\n      case params[:exercise_type]\n        when ::ActionController::Parameters\n          items.where! exercise_type: params[:exercise_type].values\n        when String\n          items.where! exercise_type: params[:exercise_type].split(',')\n        else\n          items.where! exercise_type: params[:exercise_type]\n      end\n    end\n    items.where! section_id: params[:section_id] unless params[:section_id].nil?\n    items.where! content_id: params[:content_id] unless params[:content_id].nil?\n    items.where! id: params[:id] unless params[:id].nil?\n    # NOTE: This will also return availabl...",
              "source": "app/controllers/items_controller.rb"
            },
            {
              "startLine": 4,
              "endLine": 18,
              "code": "class ItemsController < RESTController\n  respond_to :json\n\n  has_scope :section_id do |_controller, scope, value|\n    scope.for_section value.to_s\n  end\n\n  has_scope :course_id do |_controller, scope, value|\n    scope.for_course value.to_s\n  end\n\n  rfc6570_params index: %i[section_id course_id]\n\n  def index\n    respond_with collection\n  end",
              "source": "app/controllers/items_controller.rb"
            },
            {
              "startLine": 27,
              "endLine": 41,
              "code": "  def overwrite_time_effort\n    if params[:time_effort].blank?\n      return render status: :unprocessable_content, json: {errors: 'time_effort_required'}\n    end\n\n    item = Item.find(params.require(:item_id))\n    overwrite_for!(item, params[:time_effort])\n\n    head :no_content\n  rescue Errors::OverwriteTimeEffortError => e\n    render status: :unprocessable_content, json: {errors: e.reason}\n  rescue Restify::ClientError => e\n    render status: :unprocessable_content, json: {errors: e.errors}\n  end",
              "source": "app/controllers/items_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/items_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/course/app/controllers/items_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/timeeffort/app/controllers/items_controller.rb",
              "relevance": 24
            }
          ]
        }
      },
      "NextDatesController": {
        "type": "Controller",
        "description": "Manages `NextDate` resources, providing an API endpoint to list upcoming dates relevant to a user or course. It supports filtering by resource type and date type. [Source: services/course/app/controllers/next_dates_controller.rb]",
        "interactions": {
          "interaction_0": "Retrieves `NextDate` records, filtering by `user_id`, `course_id`, `resource_type`, and `type`. [Source: services/course/app/controllers/next_dates_controller.rb]",
          "interaction_1": "Interacts with `Enrollment` and `Course` to determine the course filter for a user. [Source: services/course/app/controllers/next_dates_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/next_dates_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 27,
              "code": "class NextDatesController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder\n  respond_to :json\n  def index\n    dates = NextDate\n      .active\n      .for_user(params[:user_id])\n      .where(course_id: course_filter)\n      .order_by_date\n      .includes(:course)\n    if params[:resource_type].present?\n      dates.where! resource_type: params[:resource_type]\n    end\n    dates.where! type: params[:type].split(',') if params[:type].present?\n    respond_with dates\n  end\n\n  def course_filter\n    return params[:course_id] if params[:course_id]\n\n    if params[:user_id]\n      Enrollment.unscoped.where(user_id: params[:user_id]).active\n        .select(:course_id)\n    else\n      Course.unrestricted.where(hidden: false).select(:id)\n    end\n  end\nend",
              "source": "services/course/app/controllers/next_dates_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/next_dates_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "PrerequisiteStatusController": {
        "type": "Controller",
        "description": "Provides an API endpoint to check the fulfillment status of course prerequisites for a given user. If prerequisites are met, it triggers a background job to create group memberships. [Source: services/course/app/controllers/prerequisite_status_controller.rb, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Responds to `GET /prerequisite_status` with the fulfillment status. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
          "interaction_1": "Interacts with `Course` to retrieve prerequisites. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
          "interaction_2": "Uses `Prerequisites` to determine the status for a user. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
          "interaction_3": "Triggers `EnrollmentGroupWorker.perform_async` if prerequisites are fulfilled. [Source: services/course/app/controllers/prerequisite_status_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/prerequisite_status_controller.rb",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 34,
              "code": "class PrerequisiteStatusController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder\n\n  respond_to :json\n\n  # List allowed parameters for #index here.\n  rfc6570_params index: %i[user_id]\n  def index\n    if prerequisites.any? && status.fulfilled?\n      EnrollmentGroupWorker.perform_async course.id, user_id\n    end\n\n    respond_with status\n  end\n\n  private\n\n  def status\n    @status ||= prerequisites.status_for(user_id)\n  end\n\n  def prerequisites\n    course.prerequisites\n  end\n\n  def course\n    Course.by_identifier(params[:id]).take!\n  end\n\n  def user_id\n    params.require :user_id\n  end\nend",
              "source": "services/course/app/controllers/prerequisite_status_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/prerequisite_status_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ProgressesController": {
        "type": "Controller",
        "description": "Calculates and returns the progress of a user within a course, including section-level and overall course progress. It aggregates data from items, results, and visits. [Source: services/course/app/controllers/progresses_controller.rb]",
        "interactions": {
          "interaction_0": "Responds to `GET /progresses` with detailed progress information. [Source: services/course/app/controllers/progresses_controller.rb]",
          "interaction_1": "Interacts with `Course`, `Section`, `Item`, `Result`, and `SectionChoice` models. [Source: services/course/app/controllers/progresses_controller.rb]",
          "interaction_2": "Uses `Structure::UserItemsSelector` for courses with content trees. [Source: services/course/app/controllers/progresses_controller.rb]",
          "interaction_3": "Constructs `Progress` objects for decoration. [Source: services/course/app/controllers/progresses_controller.rb]"
        },
        "techDebt": [
          "The `index` method contains complex SQL queries and Ruby logic for aggregating progress, which could be challenging to maintain and optimize. [Source: services/course/app/controllers/progresses_controller.rb]",
          "The `alternatives_rating` method is marked with `rubocop:enable all` and `rubocop:disable all`, indicating a known area of complex or potentially non-standard code. [Source: services/course/app/controllers/progresses_controller.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/progresses_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 12,
              "code": "class ProgressesController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  MAIN_BONUS_POINTS = %w[main bonus].freeze\n  MAIN_POINTS = %w[main].freeze\n\n  respond_to :json",
              "source": "services/course/app/controllers/progresses_controller.rb"
            },
            {
              "startLine": 13,
              "endLine": 29,
              "code": "  def index\n    # 0. verify params\n    unless params[:course_id].present? && params[:user_id].present?\n      return head(:not_found, content_type: 'text/plain')\n    end\n\n    user = params[:user_id]\n    # 1. select base resources\n    course = Course.find(params[:course_id])\n    if course.legacy?\n      sections = with_section_choices(course.sections.published.not_alternative)\n      relevant_items = Item.course_order.all_available.joins(:section)\n        .where(section_id: sections.map(&:id), sections: {course:})\n    else\n      relevant_items = Structure::UserItemsSelector.new(course.node, params[:user_id])\n        .items(scope: Item.all_available).joins(:section)\n      s...",
              "source": "services/course/app/controllers/progresses_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/progresses_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ReactivationsController": {
        "type": "Controller",
        "description": "Handles the creation of course reactivations for enrollments. It prevents reactivation if an enrollment is already active, unless explicitly extending. [Source: services/course/app/controllers/reactivations_controller.rb, docs/app/features/reactivation.md]",
        "interactions": {
          "interaction_0": "Responds to `POST /reactivations` to reactivate an enrollment. [Source: services/course/app/controllers/reactivations_controller.rb]",
          "interaction_1": "Interacts with `Enrollment` to find the target enrollment. [Source: services/course/app/controllers/reactivations_controller.rb]",
          "interaction_2": "Delegates reactivation logic to `Enrollment::Reactivate.call`. [Source: services/course/app/controllers/reactivations_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/reactivations_controller.rb",
            "docs/app/features/reactivation.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.98,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 32,
              "code": "# frozen_string_literal: true\n\nclass ReactivationsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder\n\n  respond_to :json\n\n  def create\n    if forbid_because_running?\n      error! errors: {submission_date: 'running'}\n      return\n    end\n\n    respond_with Enrollment::Reactivate.call(enrollment, submission_date)\n  end\n\n  private\n\n  def forbid_because_running?\n    # Unless we explicitly want to extend the reactivation, we only complain if\n    # there is already an active reactivation\n    enrollment.reactivated? && !params.key?(:extend)\n  end\n\n  def submission_date\n    Time.iso8601 params.fetch :submission_date\n  rescue ArgumentError\n    error! errors: {submission_date: 'invalid'}\n  end\n\n  def enrollment\n    @enrollment ||= Enrollment.find params.fetch :enrollment_id\n  end\nend",
              "source": "services/course/app/controllers/reactivations_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/reactivations_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "RepetitionSuggestionsController": {
        "type": "Controller",
        "description": "Provides API endpoints for suggesting items for repetition based on user results and performance. It filters items where the user's score is below a certain percentage. [Source: services/course/app/controllers/repetition_suggestions_controller.rb]",
        "interactions": {
          "interaction_0": "Responds to `GET /repetition_suggestions` with a list of suggested items. [Source: services/course/app/controllers/repetition_suggestions_controller.rb]",
          "interaction_1": "Queries `Result` and `Item` models to identify repetition candidates. [Source: services/course/app/controllers/repetition_suggestions_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/repetition_suggestions_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.98,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 34,
              "code": "class RepetitionSuggestionsController < ApplicationController   responders Responders::ApiResponder,     Responders::DecorateResponder,     Responders::HttpCacheResponder   respond_to :json   def index     # what results and corresponding items are possible repetition candidates:     candidates = Result       .joins(item: :section)       .where(item: {sections: {course_id:}})       .where(user_id:)       .select(         'dpoints as user_dpoints,         item_id,         ROW_NUMBER() OVER(           PARTITION BY item_id ORDER BY dpoints DESC         ) row_num'       )     candidates = candidates.where item: {content_type: content} if content.present?     candidates = candidates.where item: {exercise_type: exercise} if exercise.present?      # select items for each candidate:     items = Item.from(       Result.from(candidates, :results).where(row_num: 1)         .joins(:item)         .select('items.*,           COALESCE((user_dpoints::float/max_dpoints::f...",
              "source": "services/course/app/controllers/repetition_suggestions_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/repetition_suggestions_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "SectionChoicesController": {
        "type": "Controller",
        "description": "Manages `SectionChoice` resources, allowing users to select alternative sections within a course. [Source: services/course/app/controllers/section_choices_controller.rb]",
        "interactions": {
          "interaction_0": "Responds to `GET /section_choices` to list choices for a user/section. [Source: services/course/app/controllers/section_choices_controller.rb]",
          "interaction_1": "Responds to `POST /section_choices` to create or update a user's section choice. [Source: services/course/app/controllers/section_choices_controller.rb]",
          "interaction_2": "Interacts with `SectionChoice` model. [Source: services/course/app/controllers/section_choices_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/section_choices_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 27,
              "code": "class SectionChoicesController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def index\n    choices = SectionChoice.all\n    choices.where! user_id: params[:user_id] if params[:user_id]\n    choices.where! section_id: params[:section_id] if params[:section_id]\n    respond_with choices\n  end\n\n  def create\n    sc = SectionChoice.find_or_initialize_by(user_id: params[:user_id],\n      section_id: params[:section_id])\n    choice_id = params[:chosen_section_id]\n    unless sc.choice_ids.include?(choice_id)\n      sc.choice_ids << choice_id\n      sc.save!\n    end\n    respond_with({}, {location: ''})\n  end\nend",
              "source": "services/course/app/controllers/section_choices_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/section_choices_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "SectionsController": {
        "type": "Controller",
        "description": "Manages `Section` resources, which organize `Item`s within a `Course`. It provides API endpoints for listing, viewing, creating, updating, and destroying sections. It also handles alternative sections. [Source: services/course/app/controllers/sections_controller.rb]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Section` models. [Source: services/course/app/controllers/sections_controller.rb]",
          "interaction_1": "Filters sections by `course_id`, `published`, `available`, `id`, `position`, `parent_id`, and `include_alternatives`. [Source: services/course/app/controllers/sections_controller.rb]",
          "interaction_2": "Delegates section destruction to `Section::Destroy.call`. [Source: services/course/app/controllers/sections_controller.rb]",
          "interaction_3": "Updates `alternative_state` of a parent section when a child section is created. [Source: services/course/app/controllers/sections_controller.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/sections_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 37,
              "code": "# frozen_string_literal: true\n\nclass SectionsController < Abstract::FrontendController\n  include CourseContextHelper\n\n  before_action :ensure_content_editor, only: %i[index create destroy move update]\n  before_action :load_section_nav, only: [:show]\n  before_action :set_no_cache_headers\n  inside_course\n  respond_to :json\n\n  before_action(only: :create) do\n    next if section_params[:alternative_state] != 'child'\n    next if current_user.feature?('alternative_sections.create')\n\n    raise AbstractController::ActionNotFound\n  end\n\n  def index\n    @course_presenter = CoursePresenter.create(the_course, current_user)\n\n    course = Course::Course.find(the_course.id)\n\n    if course.legacy?\n      @legacy = true\n      @sections = load_raw_sections(the_course)\n    else\n      course.node.preload_tree!\n      @sections = course.node.children\n    end\n\n    Acfs.run\n    @new_section = Xikolo::Course::Section.new\n  end\n\n  # redirects to the first item in the section or to decision page for alternative s...",
              "source": "app/controllers/sections_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 31,
              "code": "# frozen_string_literal: true\n\nclass SectionsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n  def index\n    sections = Section.all\n    sections.where! course_id: params[:course_id] unless params[:course_id].nil?\n    sections.where! published: params[:published] unless params[:published].nil?\n    sections = sections.available unless params[:available].nil?\n    sections.where! id: params[:id] if params[:id]\n    sections.where! position: params[:position] if params[:position]\n    if params[:parent_id]\n      sections.where! parent_id: params[:parent_id]\n    elsif !params[:include_alternatives]\n      sections = sections.not_alternative\n    end\n    sections.includes! :course\n\n    respond_with sections\n  end\n\n  def show\n    respond_with Section.find params[:id]\n  end\n\n  def create\n    section = Section.create section_params\n    if params[:pare...",
              "source": "app/controllers/sections_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/sections_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/course/app/controllers/sections_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "TeachersController": {
        "type": "Controller",
        "description": "Manages `Teacher` resources, providing API endpoints for listing, viewing, creating, and updating teacher profiles. It supports associating teachers with courses and handling picture uploads. [Source: services/course/app/controllers/teachers_controller.rb]",
        "interactions": {
          "interaction_0": "Manages CRUD operations for `Teacher` models. [Source: services/course/app/controllers/teachers_controller.rb]",
          "interaction_1": "Filters teachers by `course`, `user_id`, and `query`. [Source: services/course/app/controllers/teachers_controller.rb]",
          "interaction_2": "Handles picture uploads via URI or ID, interacting with `Xikolo::S3` and `FileDeletionWorker`. [Source: services/course/app/controllers/teachers_controller.rb]"
        },
        "techDebt": [
          "The `upload_via_uri` and `upload_via_id` methods contain significant logic for S3 interactions and error handling, which could potentially be extracted into a dedicated service object for cleaner controller code. [Source: services/course/app/controllers/teachers_controller.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/teachers_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 29,
              "code": "# frozen_string_literal: true\n\nclass TeachersController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n  respond_to :json\n\n  # List allowed filter parameters for #index here.\n  rfc6570_params index: %i[course query]\n  def index\n    teachers = Teacher.all\n    teachers = teachers.for_course(params[:course]) if params[:course]\n    teachers = teachers.where(user_id: params[:user_id]) if params[:user_id]\n    teachers = teachers.filter_by_query(params[:query]) if params[:query]\n    teachers = teachers.order('lower(name) asc') if params[:sort] == 'name'\n    respond_with teachers\n  end\n\n  def create\n    teacher = Teacher.new create_teacher_params\n    if teacher.valid?\n      if params[:picture_uri].present?\n        teacher.upload_via_uri(params[:picture_uri])\n      else\n        teacher.upload_via_id(params[:picture_upload_id])\n      end\n      teacher.save if teacher.errors.em...",
              "source": "services/course/app/controllers/teachers_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/teachers_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "AlternativeSectionProgress": {
        "type": "Model/Service",
        "description": "Calculates and sets the 'best alternative' section for a user within a parent section that offers multiple alternative child sections. This is used for course progress calculation. [Source: services/course/app/models/alternative_section_progress.rb]",
        "interactions": {
          "interaction_0": "Interacts with `SectionProgress` to find and update progress records. [Source: services/course/app/models/alternative_section_progress.rb]",
          "interaction_1": "Interacts with `Section` to get children and their goals. [Source: services/course/app/models/alternative_section_progress.rb]"
        },
        "techDebt": [
          "The `best_alternative` method's ranking logic is calculated in memory, which is noted as 'fine for the limited number of alternative sections' but could become a performance concern with many alternatives. [Source: services/course/app/models/alternative_section_progress.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/alternative_section_progress.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 3,
              "code": "class AlternativeSectionProgress",
              "source": "services/course/app/models/alternative_section_progress.rb"
            },
            {
              "startLine": 4,
              "endLine": 6,
              "code": "  def initialize(parent:, user:)\n    @parent = parent\n    @user_id = user\n  end",
              "source": "services/course/app/models/alternative_section_progress.rb"
            },
            {
              "startLine": 10,
              "endLine": 20,
              "code": "  def set_best_alternative!\n    ActiveRecord::Base.transaction do\n      relevant_progresses.lock.each do |progress|\n        if progress.section_id == best_alternative.section_id\n          progress.update!(alternative_progress_for: @parent.id)\n        else\n          progress.update!(alternative_progress_for: nil)\n        end\n      end\n    end\n  end",
              "source": "services/course/app/models/alternative_section_progress.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/alternative_section_progress.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Branch": {
        "type": "Model",
        "description": "Represents a specific branch within a content test, linking to a `Duplicated::Group` and a `Fork`. It automatically attaches a `Structure::Branch` node on creation. [Source: services/course/app/models/branch.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Duplicated::Group` and `Fork`. [Source: services/course/app/models/branch.rb]",
          "interaction_1": "Has one `Structure::Branch` node, which is destroyed on deletion. [Source: services/course/app/models/branch.rb]",
          "interaction_2": "Creates a `Structure::Branch` node after creation. [Source: services/course/app/models/branch.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/branch.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  class Branch < ::ApplicationRecord\n    belongs_to :group, class_name: 'Account::Group'\n    has_one :node, class_name: '::Course::Structure::Branch', dependent: :destroy\n\n    belongs_to :fork\n  end\nend",
              "source": "app/models/course/branch.rb"
            },
            {
              "startLine": 1,
              "endLine": 14,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  module Structure\n    class Branch < Node\n      belongs_to :branch, class_name: '::Course::Branch'\n\n      class << self\n        def preload_content!(nodes)\n          ActiveRecord::Associations::Preloader.new(records: nodes, associations: :branch).call\n        end\n      end\n    end\n  end\nend",
              "source": "app/models/course/branch.rb"
            },
            {
              "startLine": 1,
              "endLine": 15,
              "code": "# frozen_string_literal: true\n\nclass Branch < ApplicationRecord\n  belongs_to :group, class_name: '::Duplicated::Group'\n  belongs_to :fork\n\n  has_one :node, class_name: '::Structure::Branch', dependent: :destroy\n\n  after_create :attach_node\n\n  private\n\n  def attach_node\n    create_node!(course: fork.section.course, parent: fork.node)\n  end\nend",
              "source": "app/models/course/branch.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/models/course/branch.rb",
              "relevance": 30
            },
            {
              "path": "app/models/course/structure/branch.rb",
              "relevance": 30
            },
            {
              "path": "services/course/app/models/branch.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Channel": {
        "type": "Model",
        "description": "Represents a categorization or 'channel' for courses. It includes file references for logos and visuals, and handles their deletion from S3. [Source: services/course/app/models/channel.rb]",
        "interactions": {
          "interaction_0": "Has many `Course`s. [Source: services/course/app/models/channel.rb]",
          "interaction_1": "Uses `FileReference` concern for S3 integration. [Source: services/course/app/models/channel.rb]",
          "interaction_2": "Interacts with `Xikolo::S3` to manage associated files. [Source: services/course/app/models/channel.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/channel.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 35,
              "code": "# frozen_string_literal: true\n\nmodule Xikolo\n  module V2::Courses\n    class Channels < Xikolo::Endpoint::CollectionEndpoint\n      entity do\n        type 'channels'\n\n        id {|channel| channel['code'] }\n\n        attribute('title') {\n          description 'The public title of this channel'\n          alias_for 'name'\n          type :string\n        }\n\n        # @deprecated\n        attribute('color') {\n          version max: 4\n          description 'Hexadecimal RGB color values as known from CSS, e.g. FF0000 for red'\n          type :string\n          reading { Xikolo.config.ui_primary_color }\n        }\n\n        attribute('position') {\n          description 'Relative position in the channel list'\n          type :integer\n        }\n\n        attribute('description') {\n          description 'A localized long-form text describing the channel contents in greater detail. Picks an available language based on the Accept-Language header.'\n          type :string\n        }\n\n        attribute('mobile_i...",
              "source": "api/xikolo/v2/courses/channels.rb"
            },
            {
              "startLine": 1,
              "endLine": 18,
              "code": "# frozen_string_literal: true\n\nmodule ChannelHelper\n  def stage_min_width\n    1920\n  end\n\n  def stage_min_height\n    500\n  end\n\n  def mobile_min_width\n    1280\n  end\n\n  def mobile_min_height\n    720\n  end\nend",
              "source": "api/xikolo/v2/courses/channels.rb"
            },
            {
              "startLine": 1,
              "endLine": 44,
              "code": "# frozen_string_literal: true\n\nmodule Catalog\n  module Category\n    ##\n    # An automatic course category that loads courses in a given channel.\n    # All publicly visible courses, regardless of start date and duration,\n    # may show up, oldest (by start date) first.\n    #\n    # A maximum of 4 courses will be loaded.\n    #\n    class Channel\n      ##\n      # Get a list of categories, one for each publicly visible channel.\n      #\n      def self.all_public\n        ::Course::Channel.public.ordered.map do |channel|\n          new(channel)\n        end\n      end\n\n      def initialize(channel)\n        @channel = channel\n      end\n\n      def title\n        @channel.name\n      end\n\n      def url\n        \"/channels/#{@channel.code}\"\n      end\n\n      def courses\n        @courses ||= ::Catalog::Course.released\n          .for_channel_list(@channel)\n          .for_guests\n          .order_chronologically\n          .take(4)\n      end\n    end\n  end\nend",
              "source": "api/xikolo/v2/courses/channels.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/courses/channels.rb",
              "relevance": 30
            },
            {
              "path": "app/helpers/channel_helper.rb",
              "relevance": 30
            },
            {
              "path": "app/models/catalog/category/channel.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Classifier": {
        "type": "Model",
        "description": "Used to annotate courses for organization and discoverability, grouped into `Cluster`s. It has a title, belongs to a cluster, and can be translated. [Source: services/course/app/models/classifier.rb, docs/app/features/courses/classifiers.md]",
        "interactions": {
          "interaction_0": "Has and belongs to many `Course`s. [Source: services/course/app/models/classifier.rb]",
          "interaction_1": "Belongs to `Cluster`. [Source: services/course/app/models/classifier.rb]",
          "interaction_2": "Triggers `UpdateCourseSearchIndexWorker` on update or destroy to keep course search data current. [Source: services/course/app/models/classifier.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/classifier.rb",
            "docs/app/features/courses/classifiers.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 10,
              "endLine": 29,
              "code": "      def index\n        classifiers = ::Course::Classifier.all\n\n        if params[:cluster].present?\n          classifiers = classifiers.where(cluster_id: params[:cluster])\n        end\n\n        if params[:q].present?\n          classifiers = classifiers.query(params[:q])\n        end\n\n        render json: serialize_classifiers(classifiers)\n      end\n\n      private\n\n      def serialize_classifiers(classifiers)\n        classifiers.map do |classifier|\n          {\n            id: classifier.id,\n            title: classifier.title,\n            cluster_id: classifier.cluster_id,\n            translations: classifier.translations,\n          }.compact\n        end\n      end",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            },
            {
              "startLine": 13,
              "endLine": 37,
              "code": "    class Classifier\n      def initialize(cluster_id, classifier_title, max: 4)\n        @cluster_id = cluster_id\n        @classifier_title = classifier_title\n        @max = max\n      end\n\n      def title\n        classifier.title\n      end\n\n      def url\n        nil\n      end\n\n      def courses\n        @courses ||= ::Catalog::Course.released\n          .by_classifier(@cluster_id, @classifier_title)\n          .for_guests\n          .order_chronologically\n          .take(@max)\n      end\n\n      private\n\n      def classifier\n        @classifier ||= ::Course::Classifier\n          .where(cluster_id: @cluste...",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            },
            {
              "startLine": 3,
              "endLine": 27,
              "code": "  class Classifier < ::ApplicationRecord\n    has_many :classifier_assignments, class_name: '::Course::ClassifierAssignment', dependent: :delete_all\n    has_many :courses, lambda {\n                         not_deleted.order('classifiers_courses.position')\n                       }, through: :classifier_assignments\n    belongs_to :cluster, class_name: '::Course::Cluster'\n    acts_as_list scope: :cluster\n\n    validates :title,\n      presence: true,\n      format: {with: /\\A[\\w\\-\\ ]+\\z/, message: :invalid_format},\n      uniqueness: {scope: :cluster_id, case_sensitive: false, message: :not_unique}\n    validate do\n      if translations[Xikolo.config.locales['default']].blank?\n        errors.add :translations, :missing\n      end\n    end\n\n    scope :query, ->(query) { where('title ILIKE ?', \"%#{sanitize_sql_like(query)}%\") }\n\n    class << self\n      def order_for(cluster)\n        scope = merge(where(cluster_id: cluster.id))\n        if cluster.sort_mod...",
              "source": "app/controllers/admin/ajax/classifiers_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/controllers/admin/ajax/classifiers_controller.rb",
              "relevance": 30
            },
            {
              "path": "app/models/catalog/category/classifier.rb",
              "relevance": 30
            },
            {
              "path": "app/models/course/classifier.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Cluster": {
        "type": "Model",
        "description": "Groups `Classifier`s, allowing courses to be tagged along multiple dimensions (e.g., 'level of difficulty', 'topic'). Clusters can be visible or hidden. [Source: services/course/app/models/cluster.rb, docs/app/features/courses/classifiers.md]",
        "interactions": {
          "interaction_0": "Has many `Classifier`s. [Source: services/course/app/models/cluster.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/cluster.rb",
            "docs/app/features/courses/classifiers.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 34,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  class Cluster < ::ApplicationRecord\n    has_many :classifiers, ->(cluster) { order_for(cluster) },\n      inverse_of: :cluster,\n      dependent: :delete_all\n\n    validates :id,\n      presence: true,\n      format: {with: /\\A[\\w-]+\\z/, message: :invalid_format},\n      uniqueness: {case_sensitive: false, message: :not_unique}\n    validates :sort_mode,\n      presence: true,\n      inclusion: %w[automatic manual]\n    validate do\n      if translations[Xikolo.config.locales['default']].blank?\n        errors.add :translations, :missing\n      end\n    end\n\n    class << self\n      def visible\n        where(visible: true)\n      end\n    end\n\n    ## ROUTE HELPERS\n    ## Ensure that Rails routing helpers can be used directly with Cluster instances.\n\n    def self.model_name\n      ActiveModel::Name.new(self, nil, 'Cluster')\n    end\n\n    def to_param\n      id\n    end\n\n    CLASSIFIER_LIMIT = 5\n    def classifiers_preview\n      titles = classifiers.limit(CLASSI...",
              "source": "app/models/course/cluster.rb"
            },
            {
              "startLine": 20,
              "endLine": 22,
              "code": "        cluster = Course::Cluster\n          .create_with(translations: {en: 'Course List', de: 'Kursliste'}, visible: false)\n          .find_or_create_by!(id: 'course-list')\n        Course::Classifier.create! cluster:, title: 'Featured'",
              "source": "app/models/course/cluster.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/models/course/cluster.rb",
              "relevance": 30
            },
            {
              "path": "services/course/app/models/cluster.rb",
              "relevance": 30
            },
            {
              "path": "db/migrate/20221102150705_add_featured_courses_classifier.rb",
              "relevance": 19
            }
          ]
        }
      },
      "ContentTest": {
        "type": "Model",
        "description": "Manages A/B tests for course content. It defines groups for users and assigns them in a round-robin fashion to ensure even distribution. [Source: services/course/app/models/content_test.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Course`. [Source: services/course/app/models/content_test.rb]",
          "interaction_1": "Has many `Fork`s. [Source: services/course/app/models/content_test.rb]",
          "interaction_2": "Interacts with `Duplicated::Group` and `Duplicated::Membership` to manage user groups and assignments. [Source: services/course/app/models/content_test.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/content_test.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 36,
              "code": "# frozen_string_literal: true\n\nclass ContentTest < ApplicationRecord\n  IDENTIFIER_REGEXP = /\\A[[:alnum:]]+(-[[:alnum:]]+)*\\z/\n\n  belongs_to :course\n  has_many :forks, dependent: :restrict_with_exception\n\n  validates :identifier,\n    presence: true,\n    uniqueness: {scope: :course, message: 'Identifier has already been used for this course'},\n    format: IDENTIFIER_REGEXP\n  validates :groups, length: {minimum: 2, message: 'Test should include at least two groups'}\n  validate :alphanumeric_group_names, :groups_are_unique\n\n  after_create :create_groups\n\n  def group_for_user(user_id)\n    assigned_group(user_id) || assign(user_id)\n  end\n\n  ##\n  # Iterate over the user groups belonging to this content test.\n  #\n  # Yields the internal group identifier as well as the group model.\n  #\n  def with_groups\n    hash = Duplicated::Group.where(name: group_names).index_by(&:name)\n\n    groups.each do |identifier|\n      yield identifier, hash[build_group_name(identifier)]\n    end\n  end\n\n  private\n\n  def...",
              "source": "app/models/course/content_test.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/models/course/content_test.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/content_test.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Course": {
        "type": "Model",
        "description": "The central model for courses, encompassing attributes like title, status, dates, descriptions, and associations with sections, items, channels, and classifiers. It includes extensive logic for course states, access control, search indexing, and certificate conditions (CoP, RoA). [Source: services/course/app/models/course.rb, services/course/README.md, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Has one `Structure::Root` node (for content tree). [Source: services/course/app/models/course.rb]",
          "interaction_1": "Has many `Section`s and `Item`s (through sections). [Source: services/course/app/models/course.rb]",
          "interaction_2": "Belongs to `Channel`. [Source: services/course/app/models/course.rb]",
          "interaction_3": "Has and belongs to many `Classifier`s and `Document`s. [Source: services/course/app/models/course.rb]",
          "interaction_4": "Has many `Enrollment`s. [Source: services/course/app/models/course.rb]",
          "interaction_5": "Has many `ContentTest`s and `Duplicated::Offer`s. [Source: services/course/app/models/course.rb]",
          "interaction_6": "Interacts with `CourseSet`, `CourseSetEntry`, `CourseSetRelation` for course tracks and prerequisites. [Source: services/course/app/models/course.rb, docs/app/features/courses/relations.md]",
          "interaction_7": "Publishes `xikolo.course.course.create`, `xikolo.course.course.update`, `xikolo.course.course.destroy` events via `Msgr`. [Source: services/course/app/models/course.rb]",
          "interaction_8": "Triggers `NextDate::CourseStartSyncWorker`, `UpdateCourseSearchIndexWorker`, `NextDate::SectionStartSyncWorker`, `NextDate::ItemSubmissionDeadlineSyncWorker`, `NextDate::ItemSubmissionPublishingSyncWorker`, and `EnrollmentCompletionWorker` on various lifecycle events. [Source: services/course/app/models/course.rb]",
          "interaction_9": "Uses `ForGroups` and `CourseProviderSync` concerns. [Source: services/course/app/models/course.rb]"
        },
        "techDebt": [
          "The `mark_for_recalculation!` and `needs_recalculation?` methods contain `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation, which can be a source of data inconsistency if not carefully managed. [Source: services/course/app/models/course.rb]",
          "The `legacy?` method is marked as `@deprecated`, indicating that the course content tree (`Structure::Root`) is the preferred approach, and legacy courses represent technical debt. [Source: services/course/app/models/course.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/course.rb",
            "services/course/README.md",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 27,
              "code": "module Xikolo   module Entities     class CourseDate < Grape::Entity       include Rails.application.routes.url_helpers        expose def id         id = \"#{object.course_id}|#{object.type}|#{object.resource_id}\"         Digest::MD5.hexdigest id       end        expose :title       expose :date       expose :type        expose def url         case type           when 'course_start'             course_path object.course_code           when 'item_submission_deadline'             course_item_path object.course_code, UUID(object.resource_id).to_param         end       end        expose def course         object.course_id       end     end   end end",
              "source": "api/xikolo/entities/course_date.rb"
            },
            {
              "startLine": 4,
              "endLine": 22,
              "code": "module Xikolo   module Model     class CourseRepository       def courses_for(user, course_id)         courses = course_api.rel(:courses).get({           per_page: 100,           user_id: user.id,         }).value!         if course_id.present?           courses.select {|c| c['id'] == course_id }         else           courses         end       end        private        def course_api         @course_api ||= Xikolo.api(:course).value!       end     end   end end",
              "source": "api/xikolo/entities/course_date.rb"
            },
            {
              "startLine": 4,
              "endLine": 19,
              "code": "module Xikolo   module V2     class CourseAPI < Grape::API::Instance       namespace 'courses' do         route_param :course_id, type: String, desc: 'The course UUID' do           namespace 'time_effort' do             mount Endpoint::GetCourseTimeEffort           end         end       end        namespace 'next_dates' do         mount Endpoint::ListNextDates       end     end   end end",
              "source": "api/xikolo/entities/course_date.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/entities/course_date.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/model/course_repository.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/v2/course_api.rb",
              "relevance": 30
            }
          ]
        }
      },
      "CourseGoals": {
        "type": "Model/Service",
        "description": "Calculates the maximum achievable visits and points for a given course, considering only published and mandatory items within non-alternative sections. [Source: services/course/app/models/course_goals.rb]",
        "interactions": {
          "interaction_0": "Interacts with `Course`, `Section`, and `Item` models to aggregate data. [Source: services/course/app/models/course_goals.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/course_goals.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 30,
              "code": "# frozen_string_literal: true\n\n##\n# What goals can be achieved in this course based on its items?\n#\n# This takes into account content that will become *available* at a later time,\n# but ignores the content that is not *published*.\n#\nclass CourseGoals\n  def initialize(course)\n    @course = course\n  end\n\n  ##\n  # The maximum number of visits of all non-optional items that belong to the\n  # non-optional sections of a course. Alternative sections are ignored.\n  #\n  # This can be used, for example, to determine how many visits count towards\n  # a Confirmation of Participation.\n  #\n  def max_visits\n    @max_visits ||= begin\n      relevant_sections = Section.published.mandatory.where(alternative_state: 'none')\n\n      @course.items.published.mandatory\n        .joins(:section).merge(relevant_sections)\n        .count\n    end\n  end",
              "source": "services/course/app/models/course_goals.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/course_goals.rb",
              "relevance": 19
            }
          ]
        }
      },
      "CourseProgress": {
        "type": "Model",
        "description": "Stores and calculates a user's overall progress within a course, including visits, points, and percentages. Handles aggregation from SectionProgress records, considering regular and alternative sections.",
        "interactions": {
          "interaction_0": "Belongs to Course.",
          "interaction_1": "Has one FixedLearningEvaluation.",
          "interaction_2": "Aggregates data from SectionProgress records."
        },
        "techDebt": [
          "Fixed-point arithmetic (_fpoints) adds complexity to calculations and requires careful handling."
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/course_progress.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 22,
              "code": "# frozen_string_literal: true\n\nmodule Xikolo\n  module V2::Courses\n    class CourseProgresses < Xikolo::Endpoint::CollectionEndpoint\n      entity do\n        type 'course-progresses'\n\n        id {|progress|\n          progress['resource_id']\n        }\n\n        attribute('main_exercises') {\n          description 'The course\\'s main exercise statistics for user'\n          type :hash, of: Xikolo::V2::ProgressStats.exercise_schema\n          reading {|progress|\n            Xikolo::V2::ProgressStats.exercise_data progress['main_exercises']\n          }\n        }\n\n        attribute('selftest_exercises') {\n          description 'The course\\'s selftest exercise statistics for user'\n          type :hash, of: Xikolo::V2::ProgressStats.exercise_schema\n          reading {|progress|\n            Xikolo::V2::ProgressStats.exercise_data progress['selftest_exercises']\n          }\n        }\n\n        attribute('bonus_exercises') {\n          description 'The course\\'s bonus exercise statistics for user'\n      ...",
              "source": "api/xikolo/v2/courses/course_progresses.rb"
            },
            {
              "startLine": 1,
              "endLine": 24,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  module LearnerDashboard\n    class CourseProgress < ApplicationComponent\n      include ProgressHelper\n      include ActiveSupport::NumberHelper\n\n      EMPTY_STATE = '—'\n\n      def initialize(progresses, course)\n        @course_progress = progresses.pop\n        @section_progresses = progresses\n        @course = course\n      end\n\n      def graded_score\n        return if @course_progress['main_exercises'].blank? &&\n                  @course_progress['bonus_exercises'].blank?\n\n        achieved_points = [\n          @course_progress.dig('main_exercises', 'submitted_points').presence,\n          @course_progress.dig('bonus_exercises', 'submitted_points').presence,\n        ].compact.sum\n        available_points = @course_progress.dig('main_exercises', 'max_points')\n\n        return unless available_points&.positive?\n\n        achieved = number_to_rounded(achieved_points, strip_insignificant_zeros: true)\n        available = number_to_rounded(available_...",
              "source": "api/xikolo/v2/courses/course_progresses.rb"
            },
            {
              "startLine": 1,
              "endLine": 32,
              "code": "# frozen_string_literal: true\n\nclass CourseProgress < ApplicationRecord\n  self.primary_key = %i[course_id user_id]\n\n  # `0_00..100_00` are the fixed point representation of 0.00% - 100.00%\n  validates_inclusion_of :points_percentage_fpoints, in: 0_00..100_00\n  validates_inclusion_of :visits_percentage_fpoints, in: 0_00..100_00\n\n  belongs_to :course\n\n  has_one :fixed_learning_evaluation,\n    foreign_key: %i[user_id course_id],\n    primary_key: %i[user_id course_id]\n\n  def calculate!\n    # The `.or` is a logical union.\n    progresses = regular_section_progresses.or best_alternative_section_progresses\n\n    aggregated = progresses.select(\n      'COALESCE(SUM(visits), 0) AS visits,' \\\n      'COALESCE(SUM(main_dpoints), 0) AS main_dpoints,' \\\n      'COALESCE(SUM(main_exercises), 0) AS main_exercises,' \\\n      'COALESCE(SUM(bonus_dpoints), 0) AS bonus_dpoints,' \\\n      'COALESCE(SUM(bonus_exercises), 0) AS bonus_exercises,' \\\n      'COALESCE(SUM(selftest_dpoints), 0) AS selftest_dpoints,' \\\n ...",
              "source": "api/xikolo/v2/courses/course_progresses.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/courses/course_progresses.rb",
              "relevance": 19
            },
            {
              "path": "app/components/course/learner_dashboard/course_progress.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/course_progress.rb",
              "relevance": 19
            }
          ]
        }
      },
      "CourseProvider": {
        "type": "Model",
        "description": "Manages external course providers, including their configuration and synchronization status. It triggers background jobs to sync courses with enabled providers. [Source: services/course/app/models/course_provider.rb]",
        "interactions": {
          "interaction_0": "Triggers `CourseProviderWorker` to perform synchronization for enabled providers. [Source: services/course/app/models/course_provider.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/course_provider.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 12,
              "code": "module CourseProviderSync   extend ActiveSupport::Concern    included do     after_commit :sync_providers, on: %i[create update]   end    def sync_providers     CourseProvider.sync(id) if CourseProvider.sync?(self)   end end",
              "source": "services/course/app/models/concerns/course_provider_sync.rb"
            },
            {
              "startLine": 4,
              "endLine": 35,
              "code": "class CourseProvider < ApplicationRecord   validates :name, presence: true, uniqueness: true   validates :provider_type, presence: true   validates :config, presence: true    def self.sync(course_id)     CourseProvider       .where(enabled: true)       .find_each do |provider|         CourseProviderWorker           .perform_async(             provider.name,             provider.provider_type,             provider.config,             course_id           )       end   end    def self.sync?(course)     (course.status != 'preparation' || changed_to_preparation?(course)) &&       !course.invite_only &&       course.external_course_url.blank? &&       course.groups.blank?   end    def self.changed_to_preparation?(course)     course.status_previously_changed?(from: 'active', to: 'preparation') ||       course.status_previously_changed?(from: 'archive', to: 'preparation')   end end",
              "source": "services/course/app/models/concerns/course_provider_sync.rb"
            },
            {
              "startLine": 4,
              "endLine": 11,
              "code": "class CourseProviderWorker   include Sidekiq::Job    def perform(name, type, config, course_id)     course = Course.find_by(id: course_id)     return unless course      \"#{type}::Adapter\".constantize.new(name, course, config).sync   end end",
              "source": "services/course/app/models/concerns/course_provider_sync.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/concerns/course_provider_sync.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/course_provider.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/workers/course_provider_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "CourseSet": {
        "type": "Model",
        "description": "A simple data structure to group courses, identified by a name. Used in conjunction with `CourseSetRelation` to define course tracks and prerequisites. [Source: services/course/app/models/course_set.rb, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Has many `CourseSetEntry`s and `Course`s (through entries). [Source: services/course/app/models/course_set.rb]",
          "interaction_1": "Has many `CourseSetRelation`s (as source sets) and `linked_sets` (as target sets). [Source: services/course/app/models/course_set.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/course_set.rb",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 18,
              "code": "# frozen_string_literal: true\n\nclass CourseSet < ApplicationRecord\n  has_many :course_set_entries, dependent: :delete_all\n\n  has_many :courses,\n    through: :course_set_entries\n\n  has_many :course_set_relations,\n    foreign_key: :source_set_id,\n    inverse_of: :source_set,\n    dependent: :delete_all\n\n  has_many :linked_sets,\n    through: :course_set_relations,\n    class_name: 'CourseSet',\n    source: :target_set\nend",
              "source": "services/course/app/models/course_set.rb"
            },
            {
              "startLine": 1,
              "endLine": 9,
              "code": "# frozen_string_literal: true\n\nclass CourseSetEntry < ApplicationRecord\n  self.primary_key = %i[course_set_id course_id]\n\n  belongs_to :course\n  belongs_to :course_set\nend",
              "source": "services/course/app/models/course_set.rb"
            },
            {
              "startLine": 1,
              "endLine": 13,
              "code": "# frozen_string_literal: true\n\nclass CourseSetRelation < ApplicationRecord\n  belongs_to :source_set,\n    class_name: 'CourseSet',\n    inverse_of: :course_set_relations\n\n  belongs_to :target_set,\n    class_name: 'CourseSet',\n    inverse_of: false\n\n  has_many :target_courses,\n    through: :target_set,\n    source: :courses\nend",
              "source": "services/course/app/models/course_set.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/course_set.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/course_set_entry.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/course_set_relation.rb",
              "relevance": 19
            }
          ]
        }
      },
      "CourseSetEntry": {
        "type": "Model",
        "description": "A join table that links `CourseSet`s to `Course`s, forming the entries within a course set. [Source: services/course/app/models/course_set_entry.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Course` and `CourseSet`. [Source: services/course/app/models/course_set_entry.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/course_set_entry.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 8,
              "code": "# frozen_string_literal: true\n\nclass CourseSetEntry < ApplicationRecord\n  self.primary_key = %i[course_set_id course_id]\n\n  belongs_to :course\n  belongs_to :course_set\nend",
              "source": "services/course/app/models/course_set_entry.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/course_set_entry.rb",
              "relevance": 19
            }
          ]
        }
      },
      "CourseSetRelation": {
        "type": "Model",
        "description": "Defines directed connections between `CourseSet`s, specifying a source set, a target set, and a 'kind' (e.g., `requires_roa`, `requires_cop`). [Source: services/course/app/models/course_set_relation.rb, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Belongs to `source_set` and `target_set` (both `CourseSet`s). [Source: services/course/app/models/course_set_relation.rb]",
          "interaction_1": "Has many `target_courses` through the target set. [Source: services/course/app/models/course_set_relation.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/course_set_relation.rb",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 15,
              "code": "# frozen_string_literal: true\n\nclass CourseSetRelation < ApplicationRecord\n  belongs_to :source_set,\n    class_name: 'CourseSet',\n    inverse_of: :course_set_relations\n\n  belongs_to :target_set,\n    class_name: 'CourseSet',\n    inverse_of: false\n\n  has_many :target_courses,\n    through: :target_set,\n    source: :courses\nend",
              "source": "services/course/app/models/course_set_relation.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/course_set_relation.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Enrollment": {
        "type": "Model",
        "description": "Represents a user's enrollment in a course, managing its state, completion, and associated learning evaluation. Provides scopes for filtering and methods for calculating completion status, effective quantile, and last visit.",
        "interactions": {
          "interaction_0": "Belongs to Course.",
          "interaction_1": "Has one FixedLearningEvaluation and CourseProgress.",
          "interaction_2": "Publishes Msgr events on update.",
          "interaction_3": "Triggers LearningEvaluation::UpdateCourseProgressWorker and NextDate::OnDemandExpiresSyncWorker.",
          "interaction_4": "Interacts with Item, Result, Visit for evaluation calculations.",
          "interaction_5": "Calls Xikolo.api(:account) to create memberships."
        },
        "techDebt": [
          "The self.with_learning_evaluation method contains highly complex SQL queries for dynamic learning evaluation, which could be difficult to maintain and optimize.",
          "The completed? logic is intricate and depends on multiple attributes and course associations."
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/enrollment.rb",
            "services/course/README.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 27,
              "code": "module Xikolo\n  module Entities\n    class Enrollment < Grape::Entity\n      expose :id\n\n      expose def user\n        object.user_id\n      end\n\n      expose def course\n        object.course_id\n      end\n\n      expose def reactivated\n        object.forced_submission_date.present? && Time.zone.parse(object.forced_submission_date).future?\n      end\n\n      expose :points\n      expose :certificates\n      expose :completed\n      expose :quantile\n      expose :proctored\n    end\n  end\nend",
              "source": "api/xikolo/entities/enrollment.rb"
            },
            {
              "startLine": 4,
              "endLine": 11,
              "code": "class SmowlConfirmation\n  def self.passed?(enrollment)\n    course = Course::Course.where(deleted: false).find(enrollment['course_id'])\n    Proctoring::SmowlAdapter.new(course).passed?(\n      Struct.new(:id).new(enrollment['user_id'])\n    )\n  end\nend",
              "source": "api/xikolo/entities/enrollment.rb"
            },
            {
              "startLine": 13,
              "endLine": 31,
              "code": "module Xikolo\n  module V2::Courses\n    class Enrollments < Xikolo::Endpoint::CollectionEndpoint\n      CERTIFICATE_TYPE_URL_MAPPING = {\n        'confirmation_of_participation' => ::Certificate::Record::COP,\n        'record_of_achievement' => ::Certificate::Record::ROA,\n        'qualified_certificate' => ::Certificate::Record::CERT,\n      }.freeze\n\n      entity do\n        type 'enrollments'\n\n        attribute('certificates') {\n          description 'A hash with information about the achieved certificates (confirmation_of_participation, record_of_achievement, qualified_certificate): Every value is either a URL pointing to the certificate file, or null'\n          type :hash, of: {\n            confirmation_of_part...\n",
              "source": "api/xikolo/entities/enrollment.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/entities/enrollment.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/v2/courses/enrollments.rb",
              "relevance": 30
            },
            {
              "path": "app/components/course/enrollment_policy_form.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Fork": {
        "type": "Model",
        "description": "Represents a content fork within a `ContentTest`, linking a `Section` to a specific test. It automatically creates `Branch`es for each group defined in the content test. [Source: services/course/app/models/fork.rb]",
        "interactions": {
          "interaction_0": "Belongs to `ContentTest` and `Section`. [Source: services/course/app/models/fork.rb]",
          "interaction_1": "Has many `Branch`es. [Source: services/course/app/models/fork.rb]",
          "interaction_2": "Has one `Structure::Fork` node. [Source: services/course/app/models/fork.rb]",
          "interaction_3": "Creates a `Structure::Fork` node and `Branch`es after creation. [Source: services/course/app/models/fork.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/fork.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  class Fork < ::ApplicationRecord\n    has_one :node, class_name: '::Course::Structure::Fork', dependent: :destroy\n\n    belongs_to :content_test\n    belongs_to :section\n    has_many :branches, dependent: :destroy\n  end\nend",
              "source": "app/models/course/fork.rb"
            },
            {
              "startLine": 1,
              "endLine": 15,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  module Structure\n    class Fork < Node\n      belongs_to :fork, class_name: '::Course::Fork'\n\n      has_one :content_test, through: :fork\n\n      class << self\n        def preload_content!(nodes)\n          ActiveRecord::Associations::Preloader.new(records: nodes, associations: :content_test).call\n        end\n      end\n    end\n  end\nend",
              "source": "app/models/course/fork.rb"
            },
            {
              "startLine": 1,
              "endLine": 19,
              "code": "# frozen_string_literal: true\n\nclass Fork < ApplicationRecord\n  belongs_to :content_test\n  belongs_to :section\n  has_many :branches, dependent: :destroy\n\n  has_one :node, class_name: '::Structure::Fork', dependent: :destroy\n\n  # Run in same transaction as creation\n  after_create :attach_node\n  after_create :create_branches\n\n  private\n\n  def attach_node\n    create_node!(course: section.course, parent: section.node)\n  end\n\n  def create_branches\n    content_test.with_groups do |identifier, group|\n      branches.create!(group:, title: \"#{title} - #{identifier}\")\n    end\n  end\nend",
              "source": "app/models/course/fork.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/models/course/fork.rb",
              "relevance": 30
            },
            {
              "path": "app/models/course/structure/fork.rb",
              "relevance": 30
            },
            {
              "path": "services/course/app/models/fork.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Item": {
        "type": "Model",
        "description": "Represents an individual learning content unit within a `Section`. It includes attributes for title, content type, dates, publication status, and exercise-specific details. It supports 'open mode' for video content. [Source: services/course/app/models/item.rb, docs/app/features/courses/open_mode.md]",
        "interactions": {
          "interaction_0": "Belongs to `Section`. [Source: services/course/app/models/item.rb]",
          "interaction_1": "Has one `Structure::Item` node. [Source: services/course/app/models/item.rb]",
          "interaction_2": "Has many `Result`s (user_results) and `Visit`s (user_visits). [Source: services/course/app/models/item.rb]",
          "interaction_3": "Has many `Document`s (through `documents_items`). [Source: services/course/app/models/item.rb]",
          "interaction_4": "Uses `paper_trail` for versioning. [Source: services/course/app/models/item.rb]",
          "interaction_5": "Publishes `xikolo.course.item.create`, `xikolo.course.item.update`, `xikolo.course.item.destroy` events via `Msgr`. [Source: services/course/app/models/item.rb]",
          "interaction_6": "Triggers `NextDate::ItemSubmissionDeadlineSyncWorker` and `NextDate::ItemSubmissionPublishingSyncWorker` on commit. [Source: services/course/app/models/item.rb]",
          "interaction_7": "Marks its `Section` and `Course` for recalculation on relevant changes. [Source: services/course/app/models/item.rb]"
        },
        "techDebt": [
          "The `mark_for_recalculation!` method contains `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation. [Source: services/course/app/models/item.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/item.rb",
            "docs/app/features/courses/open_mode.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 5,
              "endLine": 34,
              "code": "      entity do\n        type 'course-items'\n\n        attribute('title') {\n          description 'The item\\'s title'\n          type :string\n        }\n\n        attribute('position') {\n          description 'The item\\'s position within its section'\n          type :integer\n        }\n\n        attribute('deadline') {\n          description 'The date at which the item must have been finished by the user'\n          type :datetime\n          alias_for 'submission_deadline'\n        }\n\n        attribute('content_type') {\n          description 'The type of item: one of quiz, video, rich_text, lti_exercise'\n          type :string\n        }\n\n        attribute('icon') {\n          version max: 4\n          description 'The icon for this item (reflecting the icon in the xikolo-font)'\n          type :string\n          reading {|item|\n            case item['content_type']",
              "source": "api/xikolo/v2/courses/items.rb"
            },
            {
              "startLine": 5,
              "endLine": 38,
              "code": "      class Item < ApplicationComponent\n        include UUIDHelper\n        include ProgressHelper\n\n        def initialize(item, course)\n          @item = item\n          @course = course\n        end\n\n        def title\n          @item['title']\n        end\n\n        def css_classes\n          [].tap do |cls|\n            cls << \"section-progress__material-item--#{state}\" if state.present?\n            cls << 'section-progress__material-item--optional' if optional?\n          end\n        end\n\n        def percentage_variable\n          {\n            completed: '--percentage: 100%',\n            critical: '--percentage: 15%',\n            warning: \"--percentage: #{percentage}%\",\n          }.fetch(state, nil)\n        end\n\n        def path\n          Rails.application.routes.url_helpers.course_item_path(@course.course_code, short_uuid(@item['id']))\n        end\n\n        def icon\n          ::Course::Item::Ic...",
              "source": "api/xikolo/v2/courses/items.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/courses/items.rb",
              "relevance": 30
            },
            {
              "path": "app/components/course/item_navigation.rb",
              "relevance": 30
            },
            {
              "path": "app/components/course/learner_dashboard/section_progress/item.rb",
              "relevance": 30
            }
          ]
        }
      },
      "NextDate": {
        "type": "Model",
        "description": "Manages scheduled dates related to courses, sections, and items. It supports general and user-specific dates, and provides logic for filtering active and relevant dates. [Source: services/course/app/models/next_date.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Course`. [Source: services/course/app/models/next_date.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/next_date.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 19,
              "code": "module Xikolo::Course   class NextDate < Acfs::Resource     service Xikolo::Course::Client, path: 'next_dates'      # resource info itself (course, section, item)     attribute :resource_id, :uuid     attribute :resource_type, :string     # course info     attribute :course_id, :uuid     attribute :course_code, :string     attribute :course_title, :string      # event data itself     attribute :date, :date_time     attribute :kind, :string     attribute :title, :string   end end",
              "source": "clients/xikolo-course/lib/xikolo/course/next_date.rb"
            },
            {
              "startLine": 3,
              "endLine": 29,
              "code": "class NextDatesController < ApplicationController   responders Responders::ApiResponder,     Responders::DecorateResponder,     Responders::HttpCacheResponder   respond_to :json   def index     dates = NextDate       .active       .for_user(params[:user_id])       .where(course_id: course_filter)       .order_by_date       .includes(:course)     if params[:resource_type].present?       dates.where! resource_type: params[:resource_type]     end     dates.where! type: params[:type].split(',') if params[:type].present?     respond_with dates   end    def course_filter     return params[:course_id] if params[:course_id]      if params[:user_id]       Enrollment.unscoped.where(user_id: params[:user_id]).active         .select(:course_id)     else       Course.unrestricted.where(hidden: false).select(:id)     end   end end",
              "source": "clients/xikolo-course/lib/xikolo/course/next_date.rb"
            },
            {
              "startLine": 3,
              "endLine": 17,
              "code": "class NextDateDecorator < ApplicationDecorator   delegate :errors    def as_api_v1(_opts)     {       course_id: model.course_id,       course_code: model.course.course_code,       course_title: model.course.title,       resource_type: model.resource_type,       resource_id: model.resource_id,       type: model.type,       title: model.title,       date: model.date.iso8601(3),     }   end end",
              "source": "clients/xikolo-course/lib/xikolo/course/next_date.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "clients/xikolo-course/lib/xikolo/course/next_date.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/controllers/next_dates_controller.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/decorators/next_date_decorator.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Prerequisites": {
        "type": "Model/Service",
        "description": "Encapsulates the logic for determining if a user has fulfilled the prerequisites for a course. It evaluates `CourseSetRelation`s of kind `requires_roa` or `requires_cop`. [Source: services/course/app/models/prerequisites.rb, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Interacts with `CourseSetRelation` to retrieve prerequisite relations. [Source: services/course/app/models/prerequisites.rb]",
          "interaction_1": "Uses nested `UserStatus`, `CopStatus`, and `RoaStatus` classes to evaluate fulfillment. [Source: services/course/app/models/prerequisites.rb]",
          "interaction_2": "Interacts with `Enrollment` and `LearningEvaluation` to check user's progress in target courses. [Source: services/course/app/models/prerequisites.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/prerequisites.rb",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 20,
              "code": "class Prerequisites   def initialize(course)     @course = course   end    delegate :any?, to: :relations    def status_for(uid)     UserStatus.new(@course, relations, uid)   end    private    def relations     @relations ||= @course.relations.includes(:target_courses)       .where(kind: %w[requires_roa requires_cop])   end",
              "source": "services/course/app/models/prerequisites.rb"
            },
            {
              "startLine": 22,
              "endLine": 47,
              "code": "  class UserStatus     def initialize(course, relations, uid)       @course = course       @relations = relations       @uid = uid     end      def fulfilled?       sets.all?(&:fulfilled?)     end      def sets       @sets ||= @relations.map do |relation|         {           'requires_roa' => Prerequisites::RoaStatus,           'requires_cop' => Prerequisites::CopStatus,         }.fetch(relation.kind).new(relation.target_courses, self)       end     end      def decorate(*)       PrerequisiteStatusDecorator.new(self, *)     end      def enrollments       @enrollments ||= LearningEvaluation.by_params({learning_evaluation: 'true'}).call     end   end",
              "source": "services/course/app/models/prerequisites.rb"
            },
            {
              "startLine": 3,
              "endLine": 32,
              "code": "class Course::PrerequisitesPresenter   def initialize(course, status)     @course = course     @status = status   end    def any?     @status && @status['prerequisites'].any?   end    def each(&)     all.each(&)   end    def status     all.all?(&:fulfilled?) ? 'complete' : 'incomplete'   end    def status_text     I18n.t(:'courses.prerequisites.status_text', count: all.count(&:missing?))   end    def status_icon_name     status == 'complete' ? 'check' : 'times'   end    def all     @all ||= @status['prerequisites'].map {|req| Item.new(@course, req) }   end",
              "source": "services/course/app/models/prerequisites.rb"
            },
            {
              "startLine": 34,
              "endLine": 45,
              "code": "  class Item     def initialize(course, prerequisite)       @course = course       @prerequisite = prerequisite     end      def render(ctx)       ctx.render(         'course/courses/prerequisite',         prerequisite: self,         course: prerequisite_course,         course_url: ctx.course_url(prerequisite_course['course_code']),         free_reactivation_url: ctx.course_free_reactivations_url(@cour...     end   end",
              "source": "services/course/app/models/prerequisites.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/prerequisites.rb",
              "relevance": 30
            },
            {
              "path": "app/assets/course/prerequisites.ts",
              "relevance": 11
            },
            {
              "path": "app/presenters/course/prerequisites_presenter.rb",
              "relevance": 11
            }
          ]
        }
      },
      "Progress": {
        "type": "Transient Object",
        "description": "A transient object used to represent and decorate the progress for a `Section` or `Course`. It aggregates visited items and results. [Source: services/course/app/models/progress.rb]",
        "interactions": {
          "interaction_0": "Initialized with a resource (Course or Section), items, and results. [Source: services/course/app/models/progress.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/progress.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 37,
              "code": "# frozen_string_literal: true\n\nmodule Xikolo\n  module V2\n    class ProgressStats\n      class << self\n        def exercise_schema\n          {\n            exercises_available: :integer,\n            exercises_taken: :integer,\n            points_possible: :float,\n            points_scored: :float,\n          }\n        end\n\n        def visit_schema\n          {\n            items_available: :integer,\n            items_visited: :integer,\n            visits_percentage: :integer,\n          }\n        end\n\n        def item_schema\n          {\n            id: :string,\n            user_state: :string,\n            max_points: :float,\n            user_points: :float,\n            time_effort: :integer,\n            completed: :boolean,\n          }\n        end\n\n        def exercise_data(exercises)\n          if exercises\n            {\n              exercises_available: exercises['total_exercises'],\n              exercises_taken: exercises['submitted_exercises'],\n              points_possible: exercises['max...",
              "source": "api/xikolo/v2/progress_stats.rb"
            },
            {
              "startLine": 1,
              "endLine": 11,
              "code": "# frozen_string_literal: true\n\nmodule ProgressHelper\n  def calc_progress(user_points, total_points)\n    return 0 if user_points.blank? || total_points.blank?\n\n    if total_points.zero?\n      0\n    else\n      [user_points.fdiv(total_points) * 100, 100].min.floor\n    end\n  end\nend",
              "source": "api/xikolo/v2/progress_stats.rb"
            },
            {
              "startLine": 1,
              "endLine": 22,
              "code": "# frozen_string_literal: true\n\nmodule Xikolo::Course\n  class Progress < Acfs::Resource\n    service Xikolo::Course::Client, path: '/progresses'\n\n    attribute :resource_id, :uuid\n    attribute :kind, :string\n    attribute :visits, :dict\n    attribute :items, :list\n    attribute :title, :string\n    attribute :description, :string\n    attribute :available, :boolean\n    attribute :optional, :boolean\n    attribute :parent, :boolean\n    attribute :alternative_state, :string\n    attribute :discarded, :boolean\n    attribute :selftest_exercises, :dict\n    attribute :main_exercises, :dict\n    attribute :bonus_exercises, :dict\n    attribute :required_section_ids, :list\n  end\nend",
              "source": "api/xikolo/v2/progress_stats.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/progress_stats.rb",
              "relevance": 30
            },
            {
              "path": "app/helpers/progress_helper.rb",
              "relevance": 30
            },
            {
              "path": "clients/xikolo-course/lib/xikolo/course/progress.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Relation": {
        "type": "Model",
        "description": "An alias for `CourseSetRelation`, used to define connections between course sets for prerequisite tracking. [Source: services/course/app/models/relation.rb, docs/app/features/courses/relations.md]",
        "interactions": {
          "interaction_0": "Inherits from `CourseSetRelation`. [Source: services/course/app/models/relation.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/relation.rb",
            "docs/app/features/courses/relations.md"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 5,
              "endLine": 27,
              "code": "      class HasManyRelationship < Relationship\n        class Factory\n          def initialize(name, klass)\n            @name = name\n            @klass = klass\n            @opts = {\n              filters: {},\n            }\n          end\n\n          def build(&specification)\n            instance_exec(&specification) if specification\n\n            HasManyRelationship.new @name, @klass, @opts\n          end\n\n          # Define which of the resource's attributes should be used for filtering\n          #\n          # The first parameter must map to an existing filter on the related endpoint.\n          # The optional second parameter provides the name of this resource's attribute\n          # which identifies the resource (for use with the filter).\n          def foreign_key(filter_name, identifier_key = 'id')\n            @opts[:foreign_key_filter] = filter_name\n            @opts[:foreign_key_attr] = identifier_k...\n",
              "source": "api/xikolo/endpoint/relationships/has_many_relationship.rb"
            },
            {
              "startLine": 5,
              "endLine": 36,
              "code": "      class HasOneRelationship < Relationship\n        class Factory\n          def initialize(name, klass)\n            @name = name\n            @klass = klass\n            @opts = {}\n          end\n\n          def build(&specification)\n            instance_exec(&specification) if specification\n\n            HasOneRelationship.new @name, @klass, @opts\n          end\n\n          def foreign_key(key)\n            @opts[:foreign_key] = key\n          end\n\n          # Define how to extract the related resource from the input data\n          #\n          # The block will receive the resource hash and should extract and return a hash that can be\n          # used as input to serialize the related resource.\n          def embedded(&block)\n            @opts[:loader] = block\n          end\n        end\n\n        def initialize(name, klass, opts = {})\n          super(name)\n\n          @klass = klass\n          @opts = opts\n    ...\n",
              "source": "api/xikolo/endpoint/relationships/has_many_relationship.rb"
            },
            {
              "startLine": 5,
              "endLine": 44,
              "code": "      class MorphOneRelationship < Relationship\n        class Factory\n          def initialize(name)\n            @name = name\n            @types = {}\n            @opts = {}\n          end\n\n          def build(&specification)\n            instance_exec(&specification) if specification\n\n            MorphOneRelationship.new @name, @types, @opts\n          end\n\n          def foreign_type(type)\n            @opts[:foreign_type] = type\n          end\n\n          def foreign_key(key)\n            @opts[:foreign_key] = key\n          end\n\n          def morph(name, klass)\n            @types[name] = klass\n          end\n        end\n\n        def initialize(name, types = {}, opts = {})\n          super(name)\n\n          @types = types\n          @opts = opts\n        end\n\n        def foreign_type\n          @opts[:foreign_type]\n        end\n\n        def foreign_key\n          @opts[:foreign_key]\n        end\n\n        def instan...\n",
              "source": "api/xikolo/endpoint/relationships/has_many_relationship.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/endpoint/relationships/has_many_relationship.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/endpoint/relationships/has_one_relationship.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/endpoint/relationships/morph_one_relationship.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Section": {
        "type": "Model",
        "description": "Organizes `Item`s within a `Course`. Sections can be published, available, optional, mandatory, and can be part of an alternative section structure (parent/child). [Source: services/course/app/models/section.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Course`. [Source: services/course/app/models/section.rb]",
          "interaction_1": "Has one `Structure::Section` node. [Source: services/course/app/models/section.rb]",
          "interaction_2": "Has many `Item`s and `Fork`s. [Source: services/course/app/models/section.rb]",
          "interaction_3": "Has many `SectionProgress`es. [Source: services/course/app/models/section.rb]",
          "interaction_4": "Can have `parent` and `children` sections for alternative content. [Source: services/course/app/models/section.rb]",
          "interaction_5": "Triggers `NextDate::SectionStartSyncWorker`, `NextDate::ItemSubmissionDeadlineSyncWorker`, and `NextDate::ItemSubmissionPublishingSyncWorker` on commit. [Source: services/course/app/models/section.rb]",
          "interaction_6": "Marks itself and its `Course` for recalculation on relevant changes. [Source: services/course/app/models/section.rb]"
        },
        "techDebt": [
          "The `mark_for_recalculation!` method contains `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation. [Source: services/course/app/models/section.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/section.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 23,
              "code": "module Xikolo\n  module Entities\n    class Section < Grape::Entity\n      expose :id\n      expose :position\n\n      expose def shortUuid\n        object['shortUuid'] || UUID(object['id']).to_param\n      end\n\n      expose :title\n      expose :start_date\n      expose :end_date\n      expose :optional_section\n      expose :effective_start_date\n      expose :effective_end_date\n      expose :pinboard_closed\n    end\n  end\nend",
              "source": "api/xikolo/entities/section.rb"
            },
            {
              "startLine": 6,
              "endLine": 39,
              "code": "      entity do\n        type 'section-progresses'\n\n        id {|progress|\n          progress['resource_id']\n        }\n\n        attribute('title') {\n          description 'The section\\'s title'\n          type :string\n        }\n\n        attribute('description') {\n          description 'A text describing the section\\'s content'\n          type :string\n        }\n\n        attribute('position') {\n          description 'The sections\\'s position within its course'\n          type :integer\n        }\n\n        attribute('available') {\n          description 'Whether the section was unlocked yet'\n          type :boolean\n        }\n\n        attribute('parent') {\n          description 'Whether the section is a parent section'\n          type :boolean\n        }\n\n        attribute('main_exercises') {\n          description 'The sections\\'s main exercise statistics for user'",
              "source": "api/xikolo/entities/section.rb"
            },
            {
              "startLine": 6,
              "endLine": 39,
              "code": "      entity do\n        type 'course-sections'\n\n        attribute('title') {\n          description 'The section\\'s title'\n          type :string\n        }\n\n        attribute('description') {\n          description 'A text describing the section\\'s content'\n          type :string\n        }\n\n        attribute('position') {\n          description 'The sections\\'s position within its course'\n          type :integer\n        }\n\n        attribute('start_at') {\n          description 'The date when this section becomes available'\n          type :datetime\n          alias_for 'effective_start_date'\n        }\n\n        attribute('end_at') {\n          description 'The date when access to this section is closed'\n          type :datetime\n          alias_for 'effective_end_date'\n        }\n\n        attribute('accessible') {\n          description 'Whether the section\\'s content can be...",
              "source": "api/xikolo/entities/section.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/entities/section.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/v2/courses/section_progresses.rb",
              "relevance": 30
            },
            {
              "path": "api/xikolo/v2/courses/sections.rb",
              "relevance": 30
            }
          ]
        }
      },
      "SectionChoice": {
        "type": "Model",
        "description": "Records a user's selection of alternative sections within a course. It stores an array of chosen section IDs. [Source: services/course/app/models/section_choice.rb]",
        "interactions": {
          "interaction_0": "Belongs to `Section`. [Source: services/course/app/models/section_choice.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/section_choice.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\nmodule Xikolo::Course\n  class SectionChoice < Acfs::Resource\n    service Xikolo::Course::Client, path: '/section_choices'\n\n    attribute :section_id, :uuid\n    attribute :user_id, :uuid\n    attribute :choice_ids, :list\n  end\nend",
              "source": "clients/xikolo-course/lib/xikolo/course/section_choice.rb"
            },
            {
              "startLine": 1,
              "endLine": 31,
              "code": "# frozen_string_literal: true\n\nclass SectionChoicesController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def index\n    choices = SectionChoice.all\n    choices.where! user_id: params[:user_id] if params[:user_id]\n    choices.where! section_id: params[:section_id] if params[:section_id]\n    respond_with choices\n  end\n\n  def create\n    sc = SectionChoice.find_or_initialize_by(user_id: params[:user_id],\n      section_id: params[:section_id])\n    choice_id = params[:chosen_section_id]\n    unless sc.choice_ids.include?(choice_id)\n      sc.choice_ids << choice_id\n      sc.save!\n    end\n    respond_with({}, {location: ''})\n  end\nend",
              "source": "clients/xikolo-course/lib/xikolo/course/section_choice.rb"
            },
            {
              "startLine": 1,
              "endLine": 12,
              "code": "# frozen_string_literal: true\n\nclass SectionChoiceDecorator < ApplicationDecorator\n  delegate_all\n\n  def as_api_v1(_opts)\n    {\n      user_id:,\n      section_id:,\n      choice_ids:,\n    }\n  end\nend",
              "source": "clients/xikolo-course/lib/xikolo/course/section_choice.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "clients/xikolo-course/lib/xikolo/course/section_choice.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/controllers/section_choices_controller.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/decorators/section_choice_decorator.rb",
              "relevance": 19
            }
          ]
        }
      },
      "SectionGoals": {
        "type": "Model/Service",
        "description": "Calculates the maximum achievable visits and points for a given section, considering only published and mandatory items relevant to a specific user (especially for courses with a content tree). [Source: services/course/app/models/section_goals.rb]",
        "interactions": {
          "interaction_0": "Interacts with `Section` and `Item` models. [Source: services/course/app/models/section_goals.rb]",
          "interaction_1": "Uses `Structure::UserItemsSelector` for courses with content trees. [Source: services/course/app/models/section_goals.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/section_goals.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 36,
              "code": "# frozen_string_literal: true\n\n##\n# What goals can be achieved in this section based on its items?\n#\n# This takes into account content that will become *available* at a later time,\n# but ignores the content that is not *published*.\n#\nclass SectionGoals\n  def initialize(section, user_id)\n    @section = section\n    @user_id = user_id\n  end\n\n  # How many visits can be achieved by this user for this section?\n  def max_visits\n    @max_visits ||= relevant_items\n      .published.mandatory\n      .count\n  end\n\n  # How many points can be achieved by this user for this section?\n  # This takes into account homework and exams, but no bonus tasks.\n  def max_dpoints\n    @max_dpoints ||= relevant_items\n      .published.where(exercise_type: 'main')\n      .sum(:max_dpoints)\n  end\n\n  def relevant_items\n    @relevant_items ||= if @section.course.legacy?\n                          @section.items\n                        else\n                          Structure::UserItemsSelector.new(@section.node, @user_id)....\n",
              "source": "services/course/app/models/section_goals.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/section_goals.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Teacher": {
        "type": "Model",
        "description": "Represents a teacher or instructor associated with courses. It includes name, description, and handles picture uploads to S3. [Source: services/course/app/models/teacher.rb]",
        "interactions": {
          "interaction_0": "Has many `Course`s (via `teacher_ids` array column on Course). [Source: services/course/app/models/teacher.rb]",
          "interaction_1": "Interacts with `Xikolo::S3` for picture uploads and `FileDeletionWorker` for cleanup. [Source: services/course/app/models/teacher.rb]",
          "interaction_2": "Triggers `UpdateCourseSearchIndexWorker` on name changes to update associated courses. [Source: services/course/app/models/teacher.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/teacher.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 10,
              "code": "module Xikolo   module Entities     class Teacher < Grape::Entity       expose :id       expose :name     end   end end",
              "source": "api/xikolo/entities/teacher.rb"
            },
            {
              "startLine": 3,
              "endLine": 5,
              "code": "module Course   class Teacher < ::ApplicationRecord; end end",
              "source": "api/xikolo/entities/teacher.rb"
            },
            {
              "startLine": 43,
              "endLine": 60,
              "code": "  class TeacherPresenter     def initialize(teacher, active: false)       @teacher = teacher       @active = active     end      def id       @teacher['id']     end      def name       @teacher['name']     end      def picture_url       @teacher['picture_url']     end     alias picture? picture_url",
              "source": "api/xikolo/entities/teacher.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/entities/teacher.rb",
              "relevance": 30
            },
            {
              "path": "app/models/course/teacher.rb",
              "relevance": 30
            },
            {
              "path": "app/presenters/course/teacher_list_presenter.rb",
              "relevance": 30
            }
          ]
        }
      },
      "CourseProgress::Calculate": {
        "type": "Operation",
        "description": "Encapsulates the logic for finding or creating a CourseProgress record and triggering its calculate! method. Handles race conditions during creation.",
        "interactions": {
          "interaction_0": "Interacts with CourseProgress model."
        },
        "techDebt": [
          "The rescue ActiveRecord::RecordNotUnique with retry is a common pattern for race conditions but should be monitored for excessive retries."
        ],
        "provenance": {
          "sources": [
            "services/course/app/operations/course_progress/calculate.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 25,
              "code": "# frozen_string_literal: true\n\nclass CourseProgress::Calculate < ApplicationOperation\n  def initialize(course_id, user_id)\n    super()\n\n    @course_id = course_id\n    @user_id = user_id\n  end\n\n  def call\n    course_progress.calculate!\n\n    course_progress\n  end\n\n  private\n\n  def course_progress\n    @course_progress ||= CourseProgress.find_or_create_by!(\n      user_id: @user_id,\n      course_id: @course_id\n    )\n  rescue ActiveRecord::RecordNotUnique\n    # Retry on race condition in between find and create.\n    retry\n  end\nend",
              "source": "services/timeeffort/app/jobs/calculate_time_effort_job.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/timeeffort/app/jobs/calculate_time_effort_job.rb",
              "relevance": 30
            },
            {
              "path": "services/course/app/operations/course_progress/calculate.rb",
              "relevance": 15
            },
            {
              "path": "services/course/app/operations/section_progress/calculate.rb",
              "relevance": 11
            }
          ]
        }
      },
      "Section::Destroy": {
        "type": "Operation",
        "description": "An operation to destroy a `Section`. If the section is a 'parent' alternative section, it recursively destroys all its 'child' alternative sections first. [Source: services/course/app/operations/section/destroy.rb]",
        "interactions": {
          "interaction_0": "Recursively calls itself to destroy child sections if the target section is a parent. [Source: services/course/app/operations/section/destroy.rb]",
          "interaction_1": "Calls `destroy` on the `Section` instance within a transaction. [Source: services/course/app/operations/section/destroy.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/operations/section/destroy.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 21,
              "code": "class Section::Destroy < ApplicationOperation   attr_reader :section    def initialize(section)     super()      @section = section   end    def call     ActiveRecord::Base.transaction do       if section.parent?         section.children.each do |child|           Section::Destroy.call(child)         end       end        section.destroy     end   end end",
              "source": "services/course/app/operations/section/destroy.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/operations/section/destroy.rb",
              "relevance": 18
            },
            {
              "path": "services/account/app/operations/user/destroy.rb",
              "relevance": 11
            },
            {
              "path": "services/account/app/workers/user_destroy_worker.rb",
              "relevance": 11
            }
          ]
        }
      },
      "CourseProviderWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job that synchronizes course data with external course providers. It dynamically loads the appropriate adapter based on the provider type. [Source: services/course/app/workers/course_provider_worker.rb]",
        "interactions": {
          "interaction_0": "Finds the `Course` by ID. [Source: services/course/app/workers/course_provider_worker.rb]",
          "interaction_1": "Instantiates and calls `sync` on a `#{type}::Adapter` (e.g., `Lti::Adapter`). [Source: services/course/app/workers/course_provider_worker.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/workers/course_provider_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\nclass CourseProviderWorker\n  include Sidekiq::Job\n\n  def perform(name, type, config, course_id)\n    course = Course.find_by(id: course_id)\n    return unless course\n\n    \"#{type}::Adapter\".constantize.new(name, course, config).sync\n  end\nend",
              "source": "services/course/app/workers/course_provider_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/course_provider_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "EnrollmentCompletionWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job that processes enrollments for a given course (or a specific user within a course) to determine if they are completed and publishes an `xikolo.course.enrollment.completed` event. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
        "interactions": {
          "interaction_0": "Finds the `Course` and relevant `Enrollment`s. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
          "interaction_1": "Uses `Enrollment.with_learning_evaluation` to get completion data. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
          "interaction_2": "Publishes `xikolo.course.enrollment.completed` event via `Msgr`. [Source: services/course/app/workers/enrollment_completion_worker.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/workers/enrollment_completion_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 16,
              "code": "  def perform(course_id, user_id = nil)\n    course = Course.find(course_id)\n\n    return unless course.records_released?\n\n    enrollments = course.enrollments\n    enrollments = enrollments.where(user_id:) if user_id\n    enrollments = Enrollment.with_learning_evaluation(enrollments)\n\n    enrollments.find_each do |completed_enrollment|\n      Msgr.publish(EnrollmentDecorator.decorate(completed_enrollment).as_event,\n        to: 'xikolo.course.enrollment.completed')\n    end\n  end",
              "source": "services/course/app/workers/enrollment_completion_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/enrollment_completion_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "EnrollmentGroupWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job that creates a membership for a user in the course's student group, typically triggered when prerequisites are fulfilled. [Source: services/course/app/workers/enrollment_group_worker.rb]",
        "interactions": {
          "interaction_0": "Finds the `Enrollment` by course and user ID. [Source: services/course/app/workers/enrollment_group_worker.rb]",
          "interaction_1": "Calls `create_membership!` on the enrollment, which interacts with the `account` service. [Source: services/course/app/workers/enrollment_group_worker.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/workers/enrollment_group_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\nclass EnrollmentGroupWorker\n  include Sidekiq::Job\n\n  def perform(course_id, user_id)\n    Enrollment\n      .find_by!(course_id:, user_id:, deleted: false)\n      .create_membership!\n  rescue ActiveRecord::RecordNotFound\n    # This should never be called without an enrollment.\n  end\nend",
              "source": "services/course/app/workers/enrollment_group_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/enrollment_group_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "PersistRankingWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job that calculates and persists the quantile (ranking) and quantiled user dpoints for enrollments within a course. It only ranks users who meet the course's RoA threshold percentage. [Source: services/course/app/workers/persist_ranking_worker.rb]",
        "interactions": {
          "interaction_0": "Updates `Enrollment` records, clearing previous quantiles. [Source: services/course/app/workers/persist_ranking_worker.rb]",
          "interaction_1": "Uses `Enrollment.with_learning_evaluation` to get current scores. [Source: services/course/app/workers/persist_ranking_worker.rb]",
          "interaction_2": "Calculates quantiles using SQL window functions. [Source: services/course/app/workers/persist_ranking_worker.rb]",
          "interaction_3": "Interacts with `Course` to get `roa_threshold_percentage`. [Source: services/course/app/workers/persist_ranking_worker.rb]"
        },
        "techDebt": [
          "The worker uses `rubocop:disable Rails/SkipsModelValidations` for `update_all`, which bypasses ActiveRecord callbacks and validations. [Source: services/course/app/workers/persist_ranking_worker.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/workers/persist_ranking_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "class PersistRankingWorker\n  include Sidekiq::Job\n\n  def perform(course_id)\n    enrollments = Enrollment.where(course_id:)\n    # 1. Clear all previous quantiles:\n    # rubocop:disable Rails/SkipsModelValidations\n    enrollments.update_all quantile: nil, quantiled_user_dpoints: nil\n    # rubocop:enable Rails/SkipsModelValidations",
              "source": "services/course/app/workers/persist_ranking_worker.rb"
            },
            {
              "startLine": 12,
              "endLine": 13,
              "code": "    # 2. Load learning evaluation data:\n    enrollments = Enrollment.with_learning_evaluation(enrollments)",
              "source": "services/course/app/workers/persist_ranking_worker.rb"
            },
            {
              "startLine": 14,
              "endLine": 23,
              "code": "    # 3. Set quantiles for all users with more than 50% of the total points:\n    course = Course.find(course_id)\n    ranked_enrollments = Enrollment\n      .from(enrollments.arel.as('enrollments'))\n      .select(\n        'enrollments.id',\n        'cume_dist() OVER (ORDER BY user_dpoints) AS quantile',\n        'enrollments.user_dpoints'\n      ).where(\n        '((enrollments.user_dpoints * 1.0) / NULLIF(enrollments.maximal_dpoints,0)) >= ? / 100.0',\n        course.roa_threshold_percentage\n      )",
              "source": "services/course/app/workers/persist_ranking_worker.rb"
            },
            {
              "startLine": 25,
              "endLine": 26,
              "code": "    sql = <<-SQL.squish\n      U...",
              "source": "services/course/app/workers/persist_ranking_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/persist_ranking_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Structure::CreateCourseContentTreeWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job to create the course content tree (`Structure` nodes) for courses that do not yet have them. This is intended to ease migration from legacy course structures. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
        "interactions": {
          "interaction_0": "Finds the `Course` by identifier. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
          "interaction_1": "Creates `Structure::Root` node for the course. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
          "interaction_2": "Iterates through `Section`s and `Item`s to create corresponding `Structure::Section` and `Structure::Item` nodes. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]"
        },
        "techDebt": [
          "The worker raises exceptions if the course is not found or if the content tree already exists, which might indicate a need for more robust error handling or idempotent design. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]"
        ],
        "provenance": {
          "sources": [
            "services/course/app/workers/structure/create_course_content_tree_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 11,
              "endLine": 31,
              "code": "module Structure\n  class CreateCourseContentTreeWorker\n    include Sidekiq::Job\n\n    sidekiq_options retry: false\n\n    def perform(course)\n      course = Course.by_identifier(course).take\n      raise 'Course not found' unless course\n\n      if course.node.present?\n        raise 'The course content tree already exists.'\n      end\n\n      course.create_node!\n\n      # Create the sections and their items in the correct order.\n      course.sections.includes(:items).order(position: :asc).each do |section|\n        section.create_node!(course:, parent: course.node)\n\n        section.items.order('items.position ASC').each do |item|\n          item.create_node!(course:, parent: section.node)\n        end\n      end\n    end\n  end\nend",
              "source": "services/course/app/workers/structure/create_course_content_tree_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/structure/create_course_content_tree_worker.rb",
              "relevance": 26
            },
            {
              "path": "app/models/course/structure/branch.rb",
              "relevance": 7
            },
            {
              "path": "app/models/course/structure/fork.rb",
              "relevance": 7
            }
          ]
        }
      },
      "UpdateCourseSearchIndexWorker": {
        "type": "Sidekiq Worker",
        "description": "A background job that updates the text search index for a specific course. [Source: services/course/app/workers/update_course_search_index_worker.rb]",
        "interactions": {
          "interaction_0": "Finds the `Course` by ID. [Source: services/course/app/workers/update_course_search_index_worker.rb]",
          "interaction_1": "Calls `update_search_index` on the `Course` instance. [Source: services/course/app/workers/update_course_search_index_worker.rb]"
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/workers/update_course_search_index_worker.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\n# It updates the text search index for a course\nclass UpdateCourseSearchIndexWorker\n  include Sidekiq::Job\n\n  def perform(id)\n    Course.find(id).update_search_index\n  rescue ActiveRecord::RecordNotFound\n    # The course does not exist (anymore), no update is needed.\n  end\nend",
              "source": "services/course/app/workers/update_course_search_index_worker.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/workers/update_course_search_index_worker.rb",
              "relevance": 19
            }
          ]
        }
      },
      "ItemGradeController": {
        "type": "Controller",
        "description": "API endpoint to retrieve a user's grade for a specific learning item.",
        "interactions": {
          "interaction_0": "Interacts with Item model to find the item.",
          "interaction_1": "Calls Item#user_grade to retrieve the grade.",
          "interaction_2": "Uses ItemGradeDecorator for presentation."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/item_grade_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 28,
              "code": "# frozen_string_literal: true\n\nclass ItemGradeController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder\n\n  respond_to :json\n\n  def show\n    return head(:not_found, content_type: 'text/plain') unless grade\n\n    respond_with grade\n  end\n\n  def decorate(resource)\n    ItemGradeDecorator.decorate resource\n  end\n\n  private\n\n  def grade\n    @grade ||= Item.find(item_id).user_grade(user_id)\n  end\n\n  def item_id\n    params.require(:item_id)\n  end\n\n  def user_id\n    params.require(:user_id)\n  end\nend",
              "source": "services/course/app/controllers/item_grade_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/item_grade_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ItemResultsController": {
        "type": "Controller",
        "description": "API endpoint to retrieve results for a specific learning item, with options to filter by user or get the best result per user.",
        "interactions": {
          "interaction_0": "Interacts with Item model to find the item.",
          "interaction_1": "Queries Result model for item results, supporting 'best_per_user' scope."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/item_results_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 29,
              "code": "# frozen_string_literal: true\n\nclass ItemResultsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def index\n    results = if params[:best_per_user] == 'true'\n                Result.best_per_user(item.id)\n              else\n                Result.where(item_id: item.id)\n              end\n\n    results = results.where(user_id: params[:user_id]) if params[:user_id]\n\n    respond_with results\n  end\n\n  private\n\n  def item\n    Item.find(item_id)\n  end\n\n  def item_id\n    params.require(:item_id)\n  end\nend",
              "source": "services/course/app/controllers/item_results_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/item_results_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ItemStatisticsController": {
        "type": "Controller",
        "description": "API endpoint to retrieve statistics for a specific learning item, supporting embedding specific statistics like 'submissions_over_time'.",
        "interactions": {
          "interaction_0": "Interacts with Item model to find the item.",
          "interaction_1": "Calls Item#stats to retrieve statistics.",
          "interaction_2": "Uses decoration_context for embed and only parameters."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/item_statistics_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 52,
              "code": "class ItemStatisticsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder\n\n  respond_to :json\n\n  def show\n    if (embed - supported_statistics).present?\n      unsupported_statistic_error\n      return\n    end\n\n    if only.present? && supported_statistics.exclude?(only)\n      unsupported_statistic_error\n      return\n    end\n\n    item = Item.find(params['item_id'])\n\n    respond_with item.stats\n  end\n\n  def decoration_context\n    {\n      embed:,\n      only:,\n    }\n  end\n\n  private\n\n  def supported_statistics\n    %w[\n      submissions_over_time\n    ]\n  end\n\n  def unsupported_statistic_error\n    render json: {\n      error: \"Supported statistics are: #{supported_statistics.join(', ')}\",\n      status: 404,\n    }, status: :not_found\n  end\n\n  def embed\n    params[:embed].to_s.split(',').map(&:strip)\n  end\n\n  def only\n    params[:only].to_s.strip\n  end\nend",
              "source": "services/course/app/controllers/item_statistics_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/item_statistics_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "LastVisitsController": {
        "type": "Controller",
        "description": "API endpoint to retrieve the last visit record for a specific user within a given course.",
        "interactions": {
          "interaction_0": "Interacts with Enrollment model to find the enrollment.",
          "interaction_1": "Calls Enrollment#last_visit to get the visit.",
          "interaction_2": "Uses LastVisitDecorator for presentation."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/last_visits_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 28,
              "code": "class LastVisitsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder\n\n  respond_to :json\n\n  def show\n    if params[:user_id].blank?\n      return head(:not_found, content_type: 'text/plain')\n    end\n\n    enrollment = Enrollment.find_by(\n      user_id: params[:user_id],\n      course_id: params[:course_id]\n    )\n\n    return head(:not_found, content_type: 'text/plain') if enrollment.blank?\n\n    respond_with enrollment.last_visit\n  end\n\n  def decorate(res)\n    LastVisitDecorator.decorate res || Visit.new\n  end\nend",
              "source": "services/course/app/controllers/last_visits_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/last_visits_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "LearningEvaluation::RecalculationsController": {
        "type": "Controller",
        "description": "API endpoint to trigger asynchronous recalculation of learning evaluation for a specific course if it needs_recalculation? and recalculation_allowed?.",
        "interactions": {
          "interaction_0": "Interacts with Course model.",
          "interaction_1": "Enqueues LearningEvaluation::PersistForCourseWorker for background processing."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/learning_evaluation/recalculations_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 17,
              "code": "# frozen_string_literal: true\n\nmodule LearningEvaluation\n  class RecalculationsController < ApplicationController\n    respond_to :json\n\n    def create\n      unless course.needs_recalculation? && course.recalculation_allowed?\n        return head(:created, content_type: 'text/plain')\n      end\n\n      LearningEvaluation::PersistForCourseWorker.perform_async(course.id)\n\n      head(:created, content_type: 'text/plain')\n    end\n\n    private\n\n    def course\n      @course ||= Course.by_identifier(params[:course_id]).take!\n    end\n  end\nend",
              "source": "services/course/app/controllers/learning_evaluation/recalculations_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 30,
              "code": "# frozen_string_literal: true\n\nmodule Course::Admin::LearningEvaluation\n  class RecalculationsController < ApplicationController\n    before_action :recalculation_enabled?\n    require_permission 'course.course.recalculate'\n\n    def create\n      course = Course::Course.by_identifier(params[:course_id]).take!\n\n      return unless course.needs_recalculation?\n\n      if course.recalculation_allowed?\n        Xikolo.api(:course).value!\n          .rel(:course_learning_evaluation)\n          .post({}, params: {course_id: params[:course_id]})\n          .value!\n\n        add_flash_message :success, t(:'flash.success.recalculation_triggered')\n      else\n        add_flash_message :error, t(:'flash.error.recalculation_rejected')\n      end\n    rescue Restify::ResponseError\n      add_flash_message :error, t(:'flash.error.recalculation_failed')\n    ensure\n      redirect_to course_sections_path(params[:course_id])\n    end\n\n    private\n\n    def auth_context\n      the_course.context_id\n    end\n\n    def reque...",
              "source": "services/course/app/controllers/learning_evaluation/recalculations_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/learning_evaluation/recalculations_controller.rb",
              "relevance": 28
            },
            {
              "path": "app/controllers/course/admin/learning_evaluation/recalculations_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "PersistRankingTasksController": {
        "type": "Controller",
        "description": "API endpoint to trigger asynchronous persistence of course rankings.",
        "interactions": {
          "interaction_0": "Interacts with Course model.",
          "interaction_1": "Enqueues PersistRankingWorker for background processing."
        },
        "techDebt": [
          "Commented out responders line, indicating potential incomplete feature or refactoring."
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/persist_ranking_tasks_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 18,
              "code": "# frozen_string_literal: true\n\nclass PersistRankingTasksController < ApplicationController\n  # responders Responders::ApiResponder,\n  #           Responders::DecorateResponder,\n  #           Responders::HttpCacheResponder\n  respond_to :json\n\n  def create\n    PersistRankingWorker.perform_async(course.id)\n\n    render json: {course_id: course.id}, status: :created\n  end\n\n  private\n\n  def course\n    @course ||= Course.find params[:course_id]\n  end\nend",
              "source": "services/course/app/controllers/persist_ranking_tasks_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/persist_ranking_tasks_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "ResultsController": {
        "type": "Controller",
        "description": "API endpoint for CRUD operations on Result records, including parsing points and handling potential RecordNotFound for PUT requests by creating a new record.",
        "interactions": {
          "interaction_0": "Interacts with Result model.",
          "interaction_1": "Uses PointsProcessor concern for point parsing.",
          "interaction_2": "Triggers Msgr events and various Sidekiq workers (EnrollmentCompletionWorker, NextDate::ItemSubmissionPublishingCreateWorker, LearningEvaluation::UpdateSectionProgressWorker) via Result model callbacks."
        },
        "techDebt": [
          "The rescue ActiveRecord::RecordNotFound block for PUT to create is an unusual pattern and might hide issues or make debugging harder."
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/results_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 41,
              "code": "class ResultsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n  include PointsProcessor\n\n  respond_to :json\n\n  def create\n    result = Result.new result_params\n    result.dpoints = parse_points(:points)\n    result.save\n    fix_errors result, :dpoints, :points\n    respond_with result\n  end\n\n  def show\n    respond_with Result.find params[:id]\n  end\n\n  def update\n    result = Result.find params[:id]\n    result.dpoints = parse_points(:points)\n    result.save\n    fix_errors result, :dpoints, :points\n    respond_with result\n  rescue ActiveRecord::RecordNotFound\n    raise unless request.method == 'PUT'\n\n    create\n  end\n\n  private\n\n  def result_params\n    params.permit(:id, :user_id, :item_id)\n  end\nend",
              "source": "services/course/app/controllers/results_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/results_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "StatisticsController": {
        "type": "Controller",
        "description": "API endpoint to retrieve various course-level statistics (enrollment counts) and enrollment statistics filtered by date range and classifier.",
        "interactions": {
          "interaction_0": "Interacts with Course and Enrollment models.",
          "interaction_1": "Uses rfc6570_params for enrollment_stats method."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/statistics_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 25,
              "code": "# frozen_string_literal: true\n\nclass StatisticsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  def show\n    course = Course.find(params[:course_id])\n    enrollments = course.enrollments\n    current_enrollments = enrollments.active\n    respond_with(\n      course_id: course.id,\n      enrollments: enrollments.count + course.enrollment_delta,\n      current_enrollments: current_enrollments.count + course.enrollment_delta,\n      last_day_enrollments: enrollments.created_last_day.count,\n      last_7days_enrollments: enrollments.created_last_7days.count\n    )\n  end\n\n  rfc6570_params enrollment_stats: %i[start_date end_date classifier_id]\n  def enrollment_stats\n    start_date = params[:start_date]\n    end_date = params[:end_date]\n    classifier_id = params[:classifier_id]\n\n    enrollments = Enrollment.where(created_at: Time.zone.parse(start_da...",
              "source": "services/course/app/controllers/statistics_controller.rb"
            },
            {
              "startLine": 1,
              "endLine": 37,
              "code": "# frozen_string_literal: true\n\nclass StatisticsController < ApplicationController\n  responders Responders::HttpCacheResponder\n\n  respond_to :json\n\n  def index\n    stats = []\n    if params[:course_id]\n      members = []\n      if params[:for_teaching_team] == 'true'\n        members = teaching_team_members\n      elsif params[:most_active].present?\n        if params[:include_teaching_team].present?\n          members = most_active_users(Integer(params[:most_active]), with_teaching_team: params[:include_teaching_team])\n        else\n          members = most_active_users(Integer(params[:most_active]))\n        end\n      end\n      stats = stats_for_users(members)\n    end\n\n    respond_with stats\n  end\n\n  def show\n    respond_with Stats.new(\n      course_id: params[:id],\n      user_id: params[:user_id]\n    ).to_h\n  end\n\n  private\n\n  def stats_for_users(members)\n    members.map do |member|\n      Stats.new(\n        course_id: params[:course_id],\n        user_id: member['id']\n      ).to_h.merge(user:...",
              "source": "services/course/app/controllers/statistics_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/statistics_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/pinboard/app/controllers/statistics_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "StatsController": {
        "type": "Controller",
        "description": "API endpoint to retrieve simple, cached course statistics based on a key parameter (e.g., 'enrollments').",
        "interactions": {
          "interaction_0": "Interacts with Stat service object.",
          "interaction_1": "Uses Rails.cache for caching statistics.",
          "interaction_2": "Uses StatDecorator for presentation."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/controllers/stats_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 32,
              "code": "class StatsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::PaginateResponder\n\n  respond_to :json\n\n  # get some simple stats, for example the enrollments per course\n\n  def show\n    stats = Rails.cache.fetch(\n      \"course.stats/#{stat_params.to_query}\",\n      expires_in: 1.hour,\n      race_condition_ttl: 1.minute\n    ) do\n      Stat.new(stat_params)\n    end\n\n    respond_with stats\n  end\n\n  def decorate(res)\n    StatDecorator.new res\n  end\n\n  private\n\n  def stat_params\n    params.permit :key, :course_id\n  end\nend",
              "source": "services/course/app/controllers/stats_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/stats_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            },
            {
              "path": "app/controllers/abstract/bridge_api_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "VisitsController": {
        "type": "Controller",
        "description": "API endpoint to manage user visits to learning items, using UPSERT to efficiently record or update visit timestamps.",
        "interactions": {
          "interaction_0": "Interacts with Visit model.",
          "interaction_1": "Triggers Msgr events and various Sidekiq workers (EnrollmentCompletionWorker, LearningEvaluation::UpdateSectionProgressWorker) via Visit model callbacks."
        },
        "techDebt": [
          "rubocop:disable Rails/SkipsModelValidations comment indicates skipping validations for Visit.upsert, which might be a performance optimization but should be carefully managed."
        ],
        "provenance": {
          "sources": [
            "services/course/app/controllers/visits_controller.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 8,
              "code": "class VisitsController < ApplicationController\n  responders Responders::ApiResponder,\n    Responders::DecorateResponder,\n    Responders::HttpCacheResponder\n  respond_to :json",
              "source": "services/course/app/controllers/visits_controller.rb"
            },
            {
              "startLine": 12,
              "endLine": 24,
              "code": "  def create\n    # rubocop:disable Rails/SkipsModelValidations\n    Visit.upsert(\n      {user_id: params[:user_id], item_id: params[:item_id]},\n      unique_by: %i[user_id item_id],\n      on_duplicate: Arel.sql(<<~SQL.squish)\n        updated_at = CURRENT_TIMESTAMP\n      SQL\n    )\n    # rubocop:enable Rails/SkipsModelValidations\n\n    respond_with({}, {location: ''})\n  end",
              "source": "services/course/app/controllers/visits_controller.rb"
            },
            {
              "startLine": 26,
              "endLine": 31,
              "code": "  def show\n    respond_with Visit.find_by!(\n      user_id: params[:user_id],\n      item_id: params[:item_id]\n    )\n  end",
              "source": "services/course/app/controllers/visits_controller.rb"
            },
            {
              "startLine": 4,
              "endLine": 8,
              "code": "class VisitsController < ApplicationController\n  responders Responders::DecorateResponder,\n    Responders::HttpCacheResponder,\n    Responders::PaginateResponder\n\n  respond_to :json",
              "source": "services/course/app/controllers/visits_controller.rb"
            },
            {
              "startLine": 10,
              "endLine": 20,
              "code": "  def create\n    news = News.find_by(id: params[:announcement_id])\n\n    unless news\n      head(:not_found, content_type: 'text/plain')\n      return\n    end\n\n    news.mark_as_read(params[:user_id])\n\n    render body: nil\n  end",
              "source": "services/course/app/controllers/visits_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/visits_controller.rb",
              "relevance": 24
            },
            {
              "path": "services/news/app/controllers/visits_controller.rb",
              "relevance": 24
            },
            {
              "path": "app/controllers/abstract/ajax_controller.rb",
              "relevance": 5
            }
          ]
        }
      },
      "FixedLearningEvaluation": {
        "type": "Model",
        "description": "Stores legacy learning evaluation data, typically from older platforms, and is considered read-only.",
        "interactions": {
          "interaction_0": "Belongs to Course."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/fixed_learning_evaluation.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 10,
              "code": "# frozen_string_literal: true\n\n##\n# Legacy data from the old Canvas-based platform. These\n# were created manually and can be considered read-only.\n#\nclass FixedLearningEvaluation < ApplicationRecord\n  self.primary_key = %i[course_id user_id]\n\n  belongs_to :course\nend",
              "source": "services/course/app/models/fixed_learning_evaluation.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/models/fixed_learning_evaluation.rb",
              "relevance": 19
            }
          ]
        }
      },
      "ItemStatistics": {
        "type": "Service",
        "description": "A decorator-enabled service object that calculates various statistics for a given Item, such as total submissions, perfect submissions, max points, average points, and submissions over time.",
        "interactions": {
          "interaction_0": "Initializes with an Item.",
          "interaction_1": "Queries Result records associated with the item."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/item_statistics.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 52,
              "code": "class ItemStatistics\n  include Draper::Decoratable\n\n  def initialize(item)\n    @item = item\n  end\n\n  def total_submissions\n    results.count\n  end\n\n  def total_submissions_distinct\n    results.distinct.count(:user_id)\n  end\n\n  def perfect_submissions\n    results.where(dpoints: @item.max_dpoints).count\n  end\n\n  def perfect_submissions_distinct\n    results.where(dpoints: @item.max_dpoints).distinct.count(:user_id)\n  end\n\n  def max_points\n    @item.max_dpoints.try(:/, 10.0)\n  end\n\n  def avg_points\n    results.average(:dpoints).to_f.try(:/, 10.0).round(2)\n  end\n\n  def submissions_over_time\n    submissions_over_time = results.group_by_day(:created_at).count\n    if submissions_over_time.count < 4\n      # group by hour if less then four days\n      submissions_over_time = results.group_by_hour(:created_at).count\n    end\n    submissions_over_time\n  end\n\n  private\n\n  def results\n    @item.user_results\n  end\nend",
              "source": "services/course/app/controllers/item_statistics_controller.rb"
            },
            {
              "startLine": 3,
              "endLine": 20,
              "code": "class ItemStatisticsDecorator < ApplicationDecorator\n  delegate_all\n\n  def as_api_v1(opts = {})\n    if context[:only].present?\n      {context[:only].to_sym => model.send(context[:only].to_sym)}\n    else\n      {\n        total_submissions: model.total_submissions,\n        total_submissions_distinct: model.total_submissions_distinct,\n        perfect_submissions: model.perfect_submissions,\n        perfect_submissions_distinct: model.perfect_submissions_distinct,\n        max_points: model.max_points,\n        avg_points: model.avg_points,\n      }.tap do |attrs|\n        context[:embed].each do |type|\n          attrs[type.to_sym] = model.send(type.to_sym)\n        end\n      end\n    end.as_json(opts)\n  end\nend",
              "source": "services/course/app/controllers/item_statistics_controller.rb"
            },
            {
              "startLine": 8,
              "endLine": 47,
              "code": "  def show\n    if (embed - supported_statistics).present?\n      unsupported_statistic_error\n      return\n    end\n\n    if only.present? && supported_statistics.exclude?(only)\n      unsupported_statistic_error\n      return\n    end\n\n    item = Item.find(params['item_id'])\n\n    respond_with item.stats\n  end\n\n  def decoration_context\n    {\n      embed:,\n      only:,\n    }\n  end\n\n  private\n\n  def supported_statistics\n    %w[\n      submissions_over_time\n    ]\n  end\n\n  def unsupported_statistic_error\n    render json: {\n      error: \"Supported statistics are: #{supported_statistics.join(', ')}\",\n      status: 404,\n    }, status: :not_found\n  end\n\n  def embed\n    params[:embed].to_s.split(',').map(&:strip)\n  end\n\n  def only\n    params[:only].to_s.strip\n  end",
              "source": "services/course/app/controllers/item_statistics_controller.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/course/app/controllers/item_statistics_controller.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/decorators/item_statistics_decorator.rb",
              "relevance": 19
            },
            {
              "path": "services/course/app/models/item_statistics.rb",
              "relevance": 19
            }
          ]
        }
      },
      "LearningEvaluation (Module)": {
        "type": "Module/Strategy Pattern",
        "description": "Provides a strategy pattern for selecting the appropriate learning evaluation implementation (Dynamic, Persisted, SoftLaunch, Null) based on request parameters and configuration.",
        "interactions": {
          "interaction_0": "Uses Xikolo.config for configuration.",
          "interaction_1": "SoftLaunch uses Scientist gem for A/B testing/comparison of implementations.",
          "interaction_2": "Delegates to Dynamic, Persisted, or Null classes."
        },
        "techDebt": [
          "The SoftLaunch#ignore block contains specific logic to ignore mismatches in legacy courses or due to off-by-one visit counts, which might require careful maintenance."
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/learning_evaluation.rb"
          ]
        }
      },
      "Result": {
        "type": "Model",
        "description": "Stores a user's result (dpoints) for a specific learning item. Manages callbacks for publishing events and updating progress.",
        "interactions": {
          "interaction_0": "Belongs to Item.",
          "interaction_1": "Publishes Msgr events.",
          "interaction_2": "Triggers EnrollmentCompletionWorker, NextDate::ItemSubmissionPublishingCreateWorker, LearningEvaluation::UpdateSectionProgressWorker."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/result.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 29,
              "code": "# frozen_string_literal: true\n\nmodule Proctoring\n  ##\n  # This class represents the result of an online proctoring session.\n  # It contains a set of categories along with the number of violations\n  # for each category during this session.\n  #\n  # It can be used to represent the proctoring result for a single quiz,\n  # or an entire course.\n  class Result\n    def initialize(features, thresholds:)\n      @features = features.transform_values(&:to_i)\n      @thresholds = thresholds.transform_values(&:to_i)\n    end\n\n    def features\n      known_keys.index_with do |key|\n        @features.fetch(key, 0)\n      end\n    end\n\n    # Combine the current instance's scores with <i>other_features</i> and return a new instance with the\n    # accumulated scores.\n    def add(other_features)\n      self.class.new(\n        known_keys.index_with do |key|\n          @features.fetch(key, 0) + other_features.fetch(key, 0)\n        end,\n        thresholds: @thresholds\n      )\n    end\n\n    def empty?\n      @features.e...",
              "source": "app/lib/proctoring/result.rb"
            },
            {
              "startLine": 1,
              "endLine": 12,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  class Result < ::ApplicationRecord\n    belongs_to :item, class_name: '::Course::Item'\n    belongs_to :user, class_name: '::Account::User'\n\n    def self.best_for(item, user)\n      where(item:, user:).order(dpoints: :desc).first\n    end\n  end\nend",
              "source": "app/lib/proctoring/result.rb"
            },
            {
              "startLine": 1,
              "endLine": 38,
              "code": "# frozen_string_literal: true\n\n# generic item stats for all items with results\nmodule ItemStats\n  class ResultItemStats < BaseStats\n    def initialize(item)\n      super\n\n      @item = item\n      @stats_promise = item.rel(:statistics).get\n    end\n\n    def facts\n      percentage_avg = format(\n        '%.2f',\n        stats['avg_points'] / stats['max_points'] * 100\n      )\n\n      facts = [\n        I18n.t(\n          'course.admin.item_stats.result.submissions',\n          submissions: stats['total_submissions'],\n          users: stats['total_submissions_distinct']\n        ),\n        I18n.t(\n          'course.admin.item_stats.result.perfect_submissions',\n          submissions: stats['perfect_submissions'],\n          users: stats['perfect_submissions_distinct']\n        ),\n        I18n.t(\n          'course.admin.item_stats.result.points',\n          avg: format('%.2f', stats['avg_points']),\n          percentage_avg:,\n          max_points: stats['max_points']\n        ),\n      ]\n\n      facts.map(&...",
              "source": "app/lib/proctoring/result.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/lib/proctoring/result.rb",
              "relevance": 30
            },
            {
              "path": "app/models/course/result.rb",
              "relevance": 30
            },
            {
              "path": "app/presenters/item_stats/result_item_stats.rb",
              "relevance": 30
            }
          ]
        }
      },
      "SectionProgress": {
        "type": "Model",
        "description": "Stores and calculates a user's progress within a course section, including visits, points, and exercise counts. Handles logic for alternative sections and proctored enrollments.",
        "interactions": {
          "interaction_0": "Belongs to Section.",
          "interaction_1": "Triggers LearningEvaluation::UpdateCourseProgressWorker on destroy.",
          "interaction_2": "Queries Result and Visit models.",
          "interaction_3": "Uses Structure::UserItemsSelector and AlternativeSectionProgress."
        },
        "techDebt": [
          "The sum_dpoints_for method includes complex SQL for ordering results based on proctoring status."
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/section_progress.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 4,
              "endLine": 35,
              "code": "class SectionProgresses < Xikolo::Endpoint::CollectionEndpoint       entity do         type 'section-progresses'          id {|progress|           progress['resource_id']         }          attribute('title') {           description 'The section\\'s title'           type :string         }          attribute('description') {           description 'A text describing the section\\'s content'           type :string         }          attribute('position') {           description 'The sections\\'s position within its course'           type :integer         }          attribute('available') {           description 'Whether the section was unlocked yet'           type :boolean         }          attribute('parent') {           description 'Whether the section is a parent section'           type :boolean         }          attribute('main_exercises') {           description 'The sections\\'s main exercise statistics for user'   ...",
              "source": "api/xikolo/v2/courses/section_progresses.rb"
            },
            {
              "startLine": 7,
              "endLine": 45,
              "code": "      class Item < ApplicationComponent         include UUIDHelper         include ProgressHelper          def initialize(item, course)           @item = item           @course = course         end          def title           @item['title']         end          def css_classes           [].tap do |cls|             cls << \"section-progress__material-item--#{state}\" if state.present?             cls << 'section-progress__material-item--optional' if optional?           end         end          def percentage_variable           {             completed: '--percentage: 100%',             critical: '--percentage: 15%',             warning: \"--percentage: #{percentage}%\",           }.fetch(state, nil)         end          def path           Rails.application.routes.url_helpers.course_item_path(@course.course_code, short_uuid(@item['id']))         end          def icon           ::Course::Item::Ic...",
              "source": "api/xikolo/v2/courses/section_progresses.rb"
            },
            {
              "startLine": 6,
              "endLine": 33,
              "code": "class Main < ApplicationComponent         include ProgressHelper          def initialize(section_progress, course)           @section_progress = section_progress           @course = course         end          def main_statistic           @section_progress['main_exercises']         end          def bonus_statistic           @section_progress['bonus_exercises']         end          def selftest_statistic           @section_progress['selftest_exercises']         end          def items           # `@section_progress['items']` may be `nil` if the section is not available.           # Make sure to always return an enumerable object and avoid a tri-state.            @section_progress['items'].presence || []         end          def graded_percentage           return if main_statistic.blank? || main_statistic['max_points'].zero?            achieved_points = [             main_statistic['sub...",
              "source": "api/xikolo/v2/courses/section_progresses.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/courses/section_progresses.rb",
              "relevance": 19
            },
            {
              "path": "app/components/course/learner_dashboard/section_progress/item.rb",
              "relevance": 19
            },
            {
              "path": "app/components/course/learner_dashboard/section_progress/main.rb",
              "relevance": 19
            }
          ]
        }
      },
      "Stat": {
        "type": "Service",
        "description": "A plain Ruby object that aggregates various course-level and global statistics (enrollments, shows/no-shows, progress, certificates) based on a key parameter.",
        "interactions": {
          "interaction_0": "Initializes with attributes including course_id and key.",
          "interaction_1": "Queries Course, Enrollment, Visit, Result, FixedLearningEvaluation models."
        },
        "techDebt": [
          "The initialize method uses a large case statement to delegate to different private methods, which could be refactored using a more explicit strategy pattern or separate service objects for each 'key'.",
          "The global_stats method performs Enrollment.count and Course.count without specific scopes, potentially leading to performance issues or unintended global counts."
        ],
        "provenance": {
          "sources": [
            "services/course/app/models/stat.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 1,
              "endLine": 35,
              "code": "# frozen_string_literal: true\n\nmodule Course\n  module LearnerDashboard\n    module SectionProgress\n      class Statistic < ApplicationComponent\n        include ProgressHelper\n        include ActiveSupport::NumberHelper\n\n        def initialize(label:, values:, icon:)\n          @label = label\n          @values = values\n          @icon = icon\n        end\n\n        def percentage\n          return unless @values&.dig('max_points')&.positive?\n\n          calc_progress(@values['submitted_points'], @values['max_points'])\n        end\n\n        def points_scored\n          return unless @values&.dig('max_points')&.positive?\n\n          max_points = number_to_rounded(@values['max_points'], strip_insignificant_zeros: true)\n          submitted_points = number_to_rounded(@values['submitted_points'], strip_insignificant_zeros: true)\n\n          t(:'course.progress.statistics.points_achieved', submitted_points:, max_points:)\n        end\n\n        def exercises_taken\n          return if @values.blank?\n        ...\n",
              "source": "api/xikolo/v2/statistics_api.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "api/xikolo/v2/statistics_api.rb",
              "relevance": 30
            },
            {
              "path": "app/assets/legacy/lanalytics/plugins/lanalytics.plugins.staticHtmlEvents.js",
              "relevance": 30
            },
            {
              "path": "app/components/course/learner_dashboard/section_progress/statistic.rb",
              "relevance": 30
            }
          ]
        }
      },
      "Visit": {
        "type": "Model",
        "description": "Records a user's visit to a specific learning item, primarily tracking the updated_at timestamp for the last visit.",
        "interactions": {
          "interaction_0": "Belongs to Item.",
          "interaction_1": "Publishes Msgr events on touch/create.",
          "interaction_2": "Triggers EnrollmentCompletionWorker, LearningEvaluation::UpdateSectionProgressWorker."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/app/models/visit.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 5,
              "endLine": 35,
              "code": "window.Lanalytics.Plugins.VisitedEventsPlugin = class VisitedEventsPlugin extends (\n    Lanalytics.Plugin\n  ) {\n    // This is the interface method expected by Lanalytics\n    static newInstance(lanalytics) {\n      return new Lanalytics.Plugins.VisitedEventsPlugin(lanalytics);\n    }\n\n    constructor(lanalytics) {\n      super(lanalytics);\n      this._init();\n    }\n\n    _init() {\n      var inContext, path, resource, resourceType, verb;\n      // lanalytics: tracking user flow\n      if (gon.user_id == null) {\n        return;\n      }\n      path = window.location.pathname;\n      verb = void 0;\n      resource = void 0;\n      resourceType = void 0;\n      inContext = {};\n      if (//question/.test(path)) {\n        verb = 'visited_question';\n        resource = gon.question_id;\n        resourceType = 'question';\n        inContext['course_id'] = gon.course_id;\n      }\n      if (!gon.in_app) {\n        if (\n          //items/...",
              "source": "app/assets/legacy/lanalytics/plugins/lanalytics.plugins.visitedEvents.js"
            },
            {
              "startLine": 3,
              "endLine": 7,
              "code": "  class Visit < ::ApplicationRecord\n    belongs_to :item, class_name: '::Course::Item'\n    belongs_to :user, class_name: '::Account::User'\n  end\nend",
              "source": "app/assets/legacy/lanalytics/plugins/lanalytics.plugins.visitedEvents.js"
            },
            {
              "startLine": 2,
              "endLine": 33,
              "code": "module Gamification\n  module Rules\n    module Course\n      class VisitedItem < Gamification::Rules::Base\n        def create_score!\n          super\n\n          Gamification::Rules::Course::AttendedSection.new(@payload).create_score!\n        end\n\n        private\n\n        def name\n          :visited_item\n        end\n\n        def required_keys\n          %i[course_id item_id section_id id user_id]\n        end\n\n        def checksum\n          @payload.fetch :id\n        end\n\n        def data\n          {\n            visit_id: @payload.fetch(:id),\n            item_id: @payload.fetch(:item_id),\n            section_id: @payload.fetch(:section_id),\n          }\n        end\n      end\n    end\n  end\nend",
              "source": "app/assets/legacy/lanalytics/plugins/lanalytics.plugins.visitedEvents.js"
            }
          ],
          "sourceFiles": [
            {
              "path": "app/assets/legacy/lanalytics/plugins/lanalytics.plugins.visitedEvents.js",
              "relevance": 30
            },
            {
              "path": "app/models/course/visit.rb",
              "relevance": 30
            },
            {
              "path": "app/models/gamification/rules/course/visited_item.rb",
              "relevance": 30
            }
          ]
        }
      },
      "SectionProgress::Calculate": {
        "type": "Operation",
        "description": "Encapsulates the logic for finding or creating a SectionProgress record and triggering its calculate! method. Includes an optimization to skip recalculation if the record is not stale. Triggers LearningEvaluation::UpdateCourseProgressWorker.",
        "interactions": {
          "interaction_0": "Interacts with SectionProgress model.",
          "interaction_1": "Triggers LearningEvaluation::UpdateCourseProgressWorker."
        },
        "techDebt": [
          "The rescue ActiveRecord::RecordNotUnique with retry is a common pattern for race conditions but should be monitored for excessive retries."
        ],
        "provenance": {
          "sources": [
            "services/course/app/operations/section_progress/calculate.rb"
          ]
        },
        "codeImplementation": {
          "confidence": 0.95,
          "codeBlocks": [
            {
              "startLine": 3,
              "endLine": 39,
              "code": "class SectionProgress::Calculate < ApplicationOperation\n  def initialize(section_id, user_id, stale_at: nil, update_course_progress: true)\n    super()\n\n    @section_id = section_id\n    @user_id = user_id\n    @stale_at = stale_at\n    @update_course_progress = update_course_progress\n  end\n\n  def call\n    return section_progress if already_updated?\n\n    section_progress.calculate!\n    if @update_course_progress\n      LearningEvaluation::UpdateCourseProgressWorker\n        .perform_async(section_progress.section.course_id, @user_id)\n    end\n\n    section_progress\n  end\n\n  private\n\n  def section_progress\n    @section_progress ||= SectionProgress.find_or_create_by!(\n      user_id: @user_id,\n      section_id: @section_id\n    )\n  rescue ActiveRecord::RecordNotUnique\n    # Retry on race condition in between find and create.\n    retry\n  end\n\n  def already_updated?\n    return false unless @stale_at\n    # Do not skip the calculation if the section progress was just cre...\n",
              "source": "services/timeeffort/app/jobs/calculate_time_effort_job.rb"
            }
          ],
          "sourceFiles": [
            {
              "path": "services/timeeffort/app/jobs/calculate_time_effort_job.rb",
              "relevance": 30
            },
            {
              "path": "services/course/app/operations/section_progress/calculate.rb",
              "relevance": 15
            },
            {
              "path": "services/course/app/operations/course_progress/calculate.rb",
              "relevance": 11
            }
          ]
        }
      },
      "learning_evaluation.rake:compare": {
        "type": "Rake Task",
        "description": "A development/debugging task to compare the output of the Dynamic and Persisted learning evaluation implementations for a given enrollment.",
        "interactions": {
          "interaction_0": "Uses Enrollment model.",
          "interaction_1": "Uses LearningEvaluation module (Dynamic and Persisted implementations)."
        },
        "techDebt": [],
        "provenance": {
          "sources": [
            "services/course/lib/tasks/learning_evaluation.rake"
          ]
        }
      },
      "stats.rake:no_shows": {
        "type": "Rake Task",
        "description": "Generates a CSV-like output of 'no show' statistics for courses, calculating enrollments and visits within different timeframes relative to course start/end dates.",
        "interactions": {
          "interaction_0": "Queries Course, Enrollment, and Visit models."
        },
        "techDebt": [
          "The rubocop:disable comments indicate bypassed style rules, suggesting potentially long or complex lines of code.",
          "The output format is simple CSV to stdout, which might be less flexible than a dedicated reporting mechanism."
        ],
        "provenance": {
          "sources": [
            "services/course/lib/tasks/stats.rake"
          ]
        }
      }
    },
    "microservices": {},
    "interactions": {
      "interaction_0": "Processes `clone` messages from RabbitMQ. [Source: services/course/app/consumers/course_consumer.rb]",
      "interaction_1": "Delegates course cloning logic to `Course::Clone`. [Source: services/course/app/consumers/course_consumer.rb]",
      "interaction_2": "Responds to `GET /achievements` to list achievements for a given course and user. [Source: services/course/app/controllers/achievements_controller.rb]",
      "interaction_3": "Sets locale based on `http_accept_language`. [Source: services/course/app/controllers/achievements_controller.rb]",
      "interaction_4": "Interacts with `Achievements` (model not provided in chunk) to retrieve data. [Source: services/course/app/controllers/achievements_controller.rb]",
      "interaction_5": "Manages CRUD operations for `Channel` models. [Source: services/course/app/controllers/channels_controller.rb]",
      "interaction_6": "Uses `UUID4` for generating new channel IDs. [Source: services/course/app/controllers/channels_controller.rb]",
      "interaction_7": "Retrieves `Classifier` records based on various filters. [Source: services/course/app/controllers/classifiers_controller.rb]",
      "interaction_8": "Manages CRUD operations for `Course` models. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_9": "Filters courses by `cat_id` (classifier), `user_id` (enrollment status), `status`, `lang`, `course_code`, `channel_id`, `document_id`, `upcoming`, `current`, `finished`, `public`, `hidden`, `only_hidden`, `exclude_external`, `latest_first`, `alphabetic`, `promoted_for`, `not_enrolled`, `autocomplete`, `active_after`, and `sort` parameters. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_10": "Delegates course creation to `Course::Create.call` and updates to `Course::Update.call`. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_11": "Delegates course destruction to `Course::Destroy.call`. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_12": "Interacts with `Enrollment` to filter courses based on user enrollment status. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_13": "Interacts with `Cluster` to validate classifier parameters. [Source: services/course/app/controllers/courses_controller.rb]",
      "interaction_14": "Manages CRUD operations for `Enrollment` models. [Source: services/course/app/controllers/enrollments_controller.rb]",
      "interaction_15": "Filters enrollments by `course_id`, `user_id`, `learning_evaluation`, `deleted`, `current_course`, and `proctored`. [Source: services/course/app/controllers/enrollments_controller.rb]",
      "interaction_16": "Delegates enrollment creation to `Enrollment::Create.call`, updates to `Enrollment::Update.call`, and deletion to `Enrollment::Delete.call`. [Source: services/course/app/controllers/enrollments_controller.rb]",
      "interaction_17": "Interacts with `Course` to find the relevant course for an enrollment. [Source: services/course/app/controllers/enrollments_controller.rb]",
      "interaction_18": "Uses `LearningEvaluation.by_params` for filtering. [Source: services/course/app/controllers/enrollments_controller.rb]",
      "interaction_19": "Manages CRUD operations for `Item` models. [Source: services/course/app/controllers/items_controller.rb]",
      "interaction_20": "Filters items by `content_type`, `exercise_type`, `section_id`, `content_id`, `id`, `available`, `all_available`, `was_available`, `published`, `course_id`, `featured`, `open_mode`, `required_items`, `state_for`, `proctored`, `user_id`, and `new_for`. [Source: services/course/app/controllers/items_controller.rb]",
      "interaction_21": "Interacts with `Section`, `Course`, `Visit`, and `Structure::UserItemsSelector` for complex filtering and access control. [Source: services/course/app/controllers/items_controller.rb]",
      "interaction_22": "Handles versioning of items using `paper_trail`. [Source: services/course/app/controllers/items_controller.rb]",
      "interaction_23": "Determines 'current' item for a user based on last visit or first available item. [Source: services/course/app/controllers/items_controller.rb]",
      "interaction_24": "Retrieves `NextDate` records, filtering by `user_id`, `course_id`, `resource_type`, and `type`. [Source: services/course/app/controllers/next_dates_controller.rb]",
      "interaction_25": "Interacts with `Enrollment` and `Course` to determine the course filter for a user. [Source: services/course/app/controllers/next_dates_controller.rb]",
      "interaction_26": "Responds to `GET /prerequisite_status` with the fulfillment status. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
      "interaction_27": "Interacts with `Course` to retrieve prerequisites. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
      "interaction_28": "Uses `Prerequisites` to determine the status for a user. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
      "interaction_29": "Triggers `EnrollmentGroupWorker.perform_async` if prerequisites are fulfilled. [Source: services/course/app/controllers/prerequisite_status_controller.rb]",
      "interaction_30": "Responds to `GET /progresses` with detailed progress information. [Source: services/course/app/controllers/progresses_controller.rb]",
      "interaction_31": "Interacts with `Course`, `Section`, `Item`, `Result`, and `SectionChoice` models. [Source: services/course/app/controllers/progresses_controller.rb]",
      "interaction_32": "Uses `Structure::UserItemsSelector` for courses with content trees. [Source: services/course/app/controllers/progresses_controller.rb]",
      "interaction_33": "Constructs `Progress` objects for decoration. [Source: services/course/app/controllers/progresses_controller.rb]",
      "interaction_34": "Responds to `POST /reactivations` to reactivate an enrollment. [Source: services/course/app/controllers/reactivations_controller.rb]",
      "interaction_35": "Interacts with `Enrollment` to find the target enrollment. [Source: services/course/app/controllers/reactivations_controller.rb]",
      "interaction_36": "Delegates reactivation logic to `Enrollment::Reactivate.call`. [Source: services/course/app/controllers/reactivations_controller.rb]",
      "interaction_37": "Responds to `GET /repetition_suggestions` with a list of suggested items. [Source: services/course/app/controllers/repetition_suggestions_controller.rb]",
      "interaction_38": "Queries `Result` and `Item` models to identify repetition candidates. [Source: services/course/app/controllers/repetition_suggestions_controller.rb]",
      "interaction_39": "Responds to `GET /section_choices` to list choices for a user/section. [Source: services/course/app/controllers/section_choices_controller.rb]",
      "interaction_40": "Responds to `POST /section_choices` to create or update a user's section choice. [Source: services/course/app/controllers/section_choices_controller.rb]",
      "interaction_41": "Interacts with `SectionChoice` model. [Source: services/course/app/controllers/section_choices_controller.rb]",
      "interaction_42": "Manages CRUD operations for `Section` models. [Source: services/course/app/controllers/sections_controller.rb]",
      "interaction_43": "Filters sections by `course_id`, `published`, `available`, `id`, `position`, `parent_id`, and `include_alternatives`. [Source: services/course/app/controllers/sections_controller.rb]",
      "interaction_44": "Delegates section destruction to `Section::Destroy.call`. [Source: services/course/app/controllers/sections_controller.rb]",
      "interaction_45": "Updates `alternative_state` of a parent section when a child section is created. [Source: services/course/app/controllers/sections_controller.rb]",
      "interaction_46": "Manages CRUD operations for `Teacher` models. [Source: services/course/app/controllers/teachers_controller.rb]",
      "interaction_47": "Filters teachers by `course`, `user_id`, and `query`. [Source: services/course/app/controllers/teachers_controller.rb]",
      "interaction_48": "Handles picture uploads via URI or ID, interacting with `Xikolo::S3` and `FileDeletionWorker`. [Source: services/course/app/controllers/teachers_controller.rb]",
      "interaction_49": "Interacts with `SectionProgress` to find and update progress records. [Source: services/course/app/models/alternative_section_progress.rb]",
      "interaction_50": "Interacts with `Section` to get children and their goals. [Source: services/course/app/models/alternative_section_progress.rb]",
      "interaction_51": "Belongs to `Duplicated::Group` and `Fork`. [Source: services/course/app/models/branch.rb]",
      "interaction_52": "Has one `Structure::Branch` node, which is destroyed on deletion. [Source: services/course/app/models/branch.rb]",
      "interaction_53": "Creates a `Structure::Branch` node after creation. [Source: services/course/app/models/branch.rb]",
      "interaction_54": "Has many `Course`s. [Source: services/course/app/models/channel.rb]",
      "interaction_55": "Uses `FileReference` concern for S3 integration. [Source: services/course/app/models/channel.rb]",
      "interaction_56": "Interacts with `Xikolo::S3` to manage associated files. [Source: services/course/app/models/channel.rb]",
      "interaction_57": "Has and belongs to many `Course`s. [Source: services/course/app/models/classifier.rb]",
      "interaction_58": "Belongs to `Cluster`. [Source: services/course/app/models/classifier.rb]",
      "interaction_59": "Triggers `UpdateCourseSearchIndexWorker` on update or destroy to keep course search data current. [Source: services/course/app/models/classifier.rb]",
      "interaction_60": "Has many `Classifier`s. [Source: services/course/app/models/cluster.rb]",
      "interaction_61": "Belongs to `Course`. [Source: services/course/app/models/content_test.rb]",
      "interaction_62": "Has many `Fork`s. [Source: services/course/app/models/content_test.rb]",
      "interaction_63": "Interacts with `Duplicated::Group` and `Duplicated::Membership` to manage user groups and assignments. [Source: services/course/app/models/content_test.rb]",
      "interaction_64": "Has one `Structure::Root` node (for content tree). [Source: services/course/app/models/course.rb]",
      "interaction_65": "Has many `Section`s and `Item`s (through sections). [Source: services/course/app/models/course.rb]",
      "interaction_66": "Belongs to `Channel`. [Source: services/course/app/models/course.rb]",
      "interaction_67": "Has and belongs to many `Classifier`s and `Document`s. [Source: services/course/app/models/course.rb]",
      "interaction_68": "Has many `Enrollment`s. [Source: services/course/app/models/course.rb]",
      "interaction_69": "Has many `ContentTest`s and `Duplicated::Offer`s. [Source: services/course/app/models/course.rb]",
      "interaction_70": "Interacts with `CourseSet`, `CourseSetEntry`, `CourseSetRelation` for course tracks and prerequisites. [Source: services/course/app/models/course.rb, docs/app/features/courses/relations.md]",
      "interaction_71": "Publishes `xikolo.course.course.create`, `xikolo.course.course.update`, `xikolo.course.course.destroy` events via `Msgr`. [Source: services/course/app/models/course.rb]",
      "interaction_72": "Triggers `NextDate::CourseStartSyncWorker`, `UpdateCourseSearchIndexWorker`, `NextDate::SectionStartSyncWorker`, `NextDate::ItemSubmissionDeadlineSyncWorker`, `NextDate::ItemSubmissionPublishingSyncWorker`, and `EnrollmentCompletionWorker` on various lifecycle events. [Source: services/course/app/models/course.rb]",
      "interaction_73": "Uses `ForGroups` and `CourseProviderSync` concerns. [Source: services/course/app/models/course.rb]",
      "interaction_74": "Interacts with `Course`, `Section`, and `Item` models to aggregate data. [Source: services/course/app/models/course_goals.rb]",
      "interaction_75": "Belongs to `Course`. [Source: services/course/app/models/course_progress.rb]",
      "interaction_76": "Has one `FixedLearningEvaluation`. [Source: services/course/app/models/course_progress.rb]",
      "interaction_77": "Interacts with `SectionProgress` to sum up individual section progresses. [Source: services/course/app/models/course_progress.rb]",
      "interaction_78": "Uses `AlternativeSectionProgress` to determine the best alternative section for calculation. [Source: services/course/app/models/course_progress.rb]",
      "interaction_79": "Triggers `CourseProviderWorker` to perform synchronization for enabled providers. [Source: services/course/app/models/course_provider.rb]",
      "interaction_80": "Has many `CourseSetEntry`s and `Course`s (through entries). [Source: services/course/app/models/course_set.rb]",
      "interaction_81": "Has many `CourseSetRelation`s (as source sets) and `linked_sets` (as target sets). [Source: services/course/app/models/course_set.rb]",
      "interaction_82": "Belongs to `Course` and `CourseSet`. [Source: services/course/app/models/course_set_entry.rb]",
      "interaction_83": "Belongs to `source_set` and `target_set` (both `CourseSet`s). [Source: services/course/app/models/course_set_relation.rb]",
      "interaction_84": "Has many `target_courses` through the target set. [Source: services/course/app/models/course_set_relation.rb]",
      "interaction_85": "Belongs to `Course`. [Source: services/course/app/models/enrollment.rb]",
      "interaction_86": "Has one `FixedLearningEvaluation` and `CourseProgress`. [Source: services/course/app/models/enrollment.rb]",
      "interaction_87": "Publishes `xikolo.course.enrollment.update` events via `Msgr` on update. [Source: services/course/app/models/enrollment.rb]",
      "interaction_88": "Triggers `LearningEvaluation::UpdateCourseProgressWorker` on creation and `NextDate::OnDemandExpiresSyncWorker` if `forced_submission_date` is present. [Source: services/course/app/models/enrollment.rb]",
      "interaction_89": "Interacts with `Xikolo.api(:account)` to create group memberships. [Source: services/course/app/models/enrollment.rb]",
      "interaction_90": "Belongs to `ContentTest` and `Section`. [Source: services/course/app/models/fork.rb]",
      "interaction_91": "Has many `Branch`es. [Source: services/course/app/models/fork.rb]",
      "interaction_92": "Has one `Structure::Fork` node. [Source: services/course/app/models/fork.rb]",
      "interaction_93": "Creates a `Structure::Fork` node and `Branch`es after creation. [Source: services/course/app/models/fork.rb]",
      "interaction_94": "Belongs to `Section`. [Source: services/course/app/models/item.rb]",
      "interaction_95": "Has one `Structure::Item` node. [Source: services/course/app/models/item.rb]",
      "interaction_96": "Has many `Result`s (user_results) and `Visit`s (user_visits). [Source: services/course/app/models/item.rb]",
      "interaction_97": "Has many `Document`s (through `documents_items`). [Source: services/course/app/models/item.rb]",
      "interaction_98": "Uses `paper_trail` for versioning. [Source: services/course/app/models/item.rb]",
      "interaction_99": "Publishes `xikolo.course.item.create`, `xikolo.course.item.update`, `xikolo.course.item.destroy` events via `Msgr`. [Source: services/course/app/models/item.rb]",
      "interaction_100": "Triggers `NextDate::ItemSubmissionDeadlineSyncWorker` and `NextDate::ItemSubmissionPublishingSyncWorker` on commit. [Source: services/course/app/models/item.rb]",
      "interaction_101": "Marks its `Section` and `Course` for recalculation on relevant changes. [Source: services/course/app/models/item.rb]",
      "interaction_102": "Belongs to `Course`. [Source: services/course/app/models/next_date.rb]",
      "interaction_103": "Interacts with `CourseSetRelation` to retrieve prerequisite relations. [Source: services/course/app/models/prerequisites.rb]",
      "interaction_104": "Uses nested `UserStatus`, `CopStatus`, and `RoaStatus` classes to evaluate fulfillment. [Source: services/course/app/models/prerequisites.rb]",
      "interaction_105": "Interacts with `Enrollment` and `LearningEvaluation` to check user's progress in target courses. [Source: services/course/app/models/prerequisites.rb]",
      "interaction_106": "Initialized with a resource (Course or Section), items, and results. [Source: services/course/app/models/progress.rb]",
      "interaction_107": "Inherits from `CourseSetRelation`. [Source: services/course/app/models/relation.rb]",
      "interaction_108": "Belongs to `Course`. [Source: services/course/app/models/section.rb]",
      "interaction_109": "Has one `Structure::Section` node. [Source: services/course/app/models/section.rb]",
      "interaction_110": "Has many `Item`s and `Fork`s. [Source: services/course/app/models/section.rb]",
      "interaction_111": "Has many `SectionProgress`es. [Source: services/course/app/models/section.rb]",
      "interaction_112": "Can have `parent` and `children` sections for alternative content. [Source: services/course/app/models/section.rb]",
      "interaction_113": "Triggers `NextDate::SectionStartSyncWorker`, `NextDate::ItemSubmissionDeadlineSyncWorker`, and `NextDate::ItemSubmissionPublishingSyncWorker` on commit. [Source: services/course/app/models/section.rb]",
      "interaction_114": "Marks itself and its `Course` for recalculation on relevant changes. [Source: services/course/app/models/section.rb]",
      "interaction_115": "Belongs to `Section`. [Source: services/course/app/models/section_choice.rb]",
      "interaction_116": "Interacts with `Section` and `Item` models. [Source: services/course/app/models/section_goals.rb]",
      "interaction_117": "Uses `Structure::UserItemsSelector` for courses with content trees. [Source: services/course/app/models/section_goals.rb]",
      "interaction_118": "Has many `Course`s (via `teacher_ids` array column on Course). [Source: services/course/app/models/teacher.rb]",
      "interaction_119": "Interacts with `Xikolo::S3` for picture uploads and `FileDeletionWorker` for cleanup. [Source: services/course/app/models/teacher.rb]",
      "interaction_120": "Triggers `UpdateCourseSearchIndexWorker` on name changes to update associated courses. [Source: services/course/app/models/teacher.rb]",
      "interaction_121": "Finds or creates a `CourseProgress` record. [Source: services/course/app/operations/course_progress/calculate.rb]",
      "interaction_122": "Calls `calculate!` on the `CourseProgress` instance. [Source: services/course/app/operations/course_progress/calculate.rb]",
      "interaction_123": "Recursively calls itself to destroy child sections if the target section is a parent. [Source: services/course/app/operations/section/destroy.rb]",
      "interaction_124": "Calls `destroy` on the `Section` instance within a transaction. [Source: services/course/app/operations/section/destroy.rb]",
      "interaction_125": "Finds the `Course` by ID. [Source: services/course/app/workers/course_provider_worker.rb]",
      "interaction_126": "Instantiates and calls `sync` on a `#{type}::Adapter` (e.g., `Lti::Adapter`). [Source: services/course/app/workers/course_provider_worker.rb]",
      "interaction_127": "Finds the `Course` and relevant `Enrollment`s. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
      "interaction_128": "Uses `Enrollment.with_learning_evaluation` to get completion data. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
      "interaction_129": "Publishes `xikolo.course.enrollment.completed` event via `Msgr`. [Source: services/course/app/workers/enrollment_completion_worker.rb]",
      "interaction_130": "Finds the `Enrollment` by course and user ID. [Source: services/course/app/workers/enrollment_group_worker.rb]",
      "interaction_131": "Calls `create_membership!` on the enrollment, which interacts with the `account` service. [Source: services/course/app/workers/enrollment_group_worker.rb]",
      "interaction_132": "Updates `Enrollment` records, clearing previous quantiles. [Source: services/course/app/workers/persist_ranking_worker.rb]",
      "interaction_133": "Uses `Enrollment.with_learning_evaluation` to get current scores. [Source: services/course/app/workers/persist_ranking_worker.rb]",
      "interaction_134": "Calculates quantiles using SQL window functions. [Source: services/course/app/workers/persist_ranking_worker.rb]",
      "interaction_135": "Interacts with `Course` to get `roa_threshold_percentage`. [Source: services/course/app/workers/persist_ranking_worker.rb]",
      "interaction_136": "Finds the `Course` by identifier. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
      "interaction_137": "Creates `Structure::Root` node for the course. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
      "interaction_138": "Iterates through `Section`s and `Item`s to create corresponding `Structure::Section` and `Structure::Item` nodes. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
      "interaction_139": "Finds the `Course` by ID. [Source: services/course/app/workers/update_course_search_index_worker.rb]",
      "interaction_140": "Calls `update_search_index` on the `Course` instance. [Source: services/course/app/workers/update_course_search_index_worker.rb]",
      "interaction_141": "Interacts with Item model to find the item.",
      "interaction_142": "Calls Item#user_grade to retrieve the grade.",
      "interaction_143": "Uses ItemGradeDecorator for presentation.",
      "interaction_144": "Interacts with Item model to find the item.",
      "interaction_145": "Queries Result model for item results, supporting 'best_per_user' scope.",
      "interaction_146": "Interacts with Item model to find the item.",
      "interaction_147": "Calls Item#stats to retrieve statistics.",
      "interaction_148": "Uses decoration_context for embed and only parameters.",
      "interaction_149": "Interacts with Enrollment model to find the enrollment.",
      "interaction_150": "Calls Enrollment#last_visit to get the visit.",
      "interaction_151": "Uses LastVisitDecorator for presentation.",
      "interaction_152": "Interacts with Course model.",
      "interaction_153": "Enqueues LearningEvaluation::PersistForCourseWorker for background processing.",
      "interaction_154": "Interacts with Course model.",
      "interaction_155": "Enqueues PersistRankingWorker for background processing.",
      "interaction_156": "Interacts with Result model.",
      "interaction_157": "Uses PointsProcessor concern for point parsing.",
      "interaction_158": "Triggers Msgr events and various Sidekiq workers (EnrollmentCompletionWorker, NextDate::ItemSubmissionPublishingCreateWorker, LearningEvaluation::UpdateSectionProgressWorker) via Result model callbacks.",
      "interaction_159": "Interacts with Course and Enrollment models.",
      "interaction_160": "Uses rfc6570_params for enrollment_stats method.",
      "interaction_161": "Interacts with Stat service object.",
      "interaction_162": "Uses Rails.cache for caching statistics.",
      "interaction_163": "Uses StatDecorator for presentation.",
      "interaction_164": "Interacts with Visit model.",
      "interaction_165": "Triggers Msgr events and various Sidekiq workers (EnrollmentCompletionWorker, LearningEvaluation::UpdateSectionProgressWorker) via Visit model callbacks.",
      "interaction_166": "Belongs to Course.",
      "interaction_167": "Has one FixedLearningEvaluation.",
      "interaction_168": "Aggregates data from SectionProgress records.",
      "interaction_169": "Belongs to Course.",
      "interaction_170": "Has one FixedLearningEvaluation and CourseProgress.",
      "interaction_171": "Publishes Msgr events on update.",
      "interaction_172": "Triggers LearningEvaluation::UpdateCourseProgressWorker and NextDate::OnDemandExpiresSyncWorker.",
      "interaction_173": "Interacts with Item, Result, Visit for evaluation calculations.",
      "interaction_174": "Calls Xikolo.api(:account) to create memberships.",
      "interaction_175": "Belongs to Course.",
      "interaction_176": "Initializes with an Item.",
      "interaction_177": "Queries Result records associated with the item.",
      "interaction_178": "Uses Xikolo.config for configuration.",
      "interaction_179": "SoftLaunch uses Scientist gem for A/B testing/comparison of implementations.",
      "interaction_180": "Delegates to Dynamic, Persisted, or Null classes.",
      "interaction_181": "Belongs to Item.",
      "interaction_182": "Publishes Msgr events.",
      "interaction_183": "Triggers EnrollmentCompletionWorker, NextDate::ItemSubmissionPublishingCreateWorker, LearningEvaluation::UpdateSectionProgressWorker.",
      "interaction_184": "Belongs to Section.",
      "interaction_185": "Triggers LearningEvaluation::UpdateCourseProgressWorker on destroy.",
      "interaction_186": "Queries Result and Visit models.",
      "interaction_187": "Uses Structure::UserItemsSelector and AlternativeSectionProgress.",
      "interaction_188": "Initializes with attributes including course_id and key.",
      "interaction_189": "Queries Course, Enrollment, Visit, Result, FixedLearningEvaluation models.",
      "interaction_190": "Belongs to Item.",
      "interaction_191": "Publishes Msgr events on touch/create.",
      "interaction_192": "Triggers EnrollmentCompletionWorker, LearningEvaluation::UpdateSectionProgressWorker.",
      "interaction_193": "Interacts with CourseProgress model.",
      "interaction_194": "Interacts with SectionProgress model.",
      "interaction_195": "Triggers LearningEvaluation::UpdateCourseProgressWorker.",
      "interaction_196": "Uses Enrollment model.",
      "interaction_197": "Uses LearningEvaluation module (Dynamic and Persisted implementations).",
      "interaction_198": "Queries Course, Enrollment, and Visit models."
    },
    "technicalDebt": [
      "The `index` method contains a very large number of conditional filters, which could be refactored into a more modular query object pattern for better readability and maintainability. [Source: services/course/app/controllers/courses_controller.rb]",
      "The `index` method has a complex conditional logic for filtering, especially regarding `exercise_type` and `available` scopes, which could be simplified. [Source: services/course/app/controllers/items_controller.rb]",
      "The `TODO` comment regarding dropping items where requirements are not fulfilled suggests a known limitation due to the microservice architecture. [Source: services/course/app/controllers/items_controller.rb]",
      "The `index` method contains complex SQL queries and Ruby logic for aggregating progress, which could be challenging to maintain and optimize. [Source: services/course/app/controllers/progresses_controller.rb]",
      "The `alternatives_rating` method is marked with `rubocop:enable all` and `rubocop:disable all`, indicating a known area of complex or potentially non-standard code. [Source: services/course/app/controllers/progresses_controller.rb]",
      "The `upload_via_uri` and `upload_via_id` methods contain significant logic for S3 interactions and error handling, which could potentially be extracted into a dedicated service object for cleaner controller code. [Source: services/course/app/controllers/teachers_controller.rb]",
      "The `best_alternative` method's ranking logic is calculated in memory, which is noted as 'fine for the limited number of alternative sections' but could become a performance concern with many alternatives. [Source: services/course/app/models/alternative_section_progress.rb]",
      "The `mark_for_recalculation!` and `needs_recalculation?` methods contain `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation, which can be a source of data inconsistency if not carefully managed. [Source: services/course/app/models/course.rb]",
      "The `legacy?` method is marked as `@deprecated`, indicating that the course content tree (`Structure::Root`) is the preferred approach, and legacy courses represent technical debt. [Source: services/course/app/models/course.rb]",
      "The `with_learning_evaluation` scope contains complex SQL for dynamic calculation of visits and points, which is difficult to read and maintain. [Source: services/course/app/models/enrollment.rb]",
      "The `mark_for_recalculation!` method contains `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation. [Source: services/course/app/models/item.rb]",
      "The `mark_for_recalculation!` method contains `rubocop:disable Rails/SkipsModelValidations` comments, indicating direct attribute updates without full validation. [Source: services/course/app/models/section.rb]",
      "The worker uses `rubocop:disable Rails/SkipsModelValidations` for `update_all`, which bypasses ActiveRecord callbacks and validations. [Source: services/course/app/workers/persist_ranking_worker.rb]",
      "The worker raises exceptions if the course is not found or if the content tree already exists, which might indicate a need for more robust error handling or idempotent design. [Source: services/course/app/workers/structure/create_course_content_tree_worker.rb]",
      "Commented out responders line, indicating potential incomplete feature or refactoring.",
      "The rescue ActiveRecord::RecordNotFound block for PUT to create is an unusual pattern and might hide issues or make debugging harder.",
      "rubocop:disable Rails/SkipsModelValidations comment indicates skipping validations for Visit.upsert, which might be a performance optimization but should be carefully managed.",
      "Fixed-point arithmetic (_fpoints) adds complexity to calculations and requires careful handling.",
      "The self.with_learning_evaluation method contains highly complex SQL queries for dynamic learning evaluation, which could be difficult to maintain and optimize.",
      "The completed? logic is intricate and depends on multiple attributes and course associations.",
      "The SoftLaunch#ignore block contains specific logic to ignore mismatches in legacy courses or due to off-by-one visit counts, which might require careful maintenance.",
      "The sum_dpoints_for method includes complex SQL for ordering results based on proctoring status.",
      "The initialize method uses a large case statement to delegate to different private methods, which could be refactored using a more explicit strategy pattern or separate service objects for each 'key'.",
      "The global_stats method performs Enrollment.count and Course.count without specific scopes, potentially leading to performance issues or unintended global counts.",
      "The rescue ActiveRecord::RecordNotUnique with retry is a common pattern for race conditions but should be monitored for excessive retries.",
      "The rubocop:disable comments indicate bypassed style rules, suggesting potentially long or complex lines of code.",
      "The output format is simple CSV to stdout, which might be less flexible than a dedicated reporting mechanism."
    ]
  }
}