# UC-03 Fill Survey (Module 1) - Architectural Mapping

This document maps the visual components from the **UC-03 Fill Survey (Module 1)** Use Case diagram to the Laravel backend implementation, strictly adhering to **SOLID** and **DRY** principles.

## 1. Actor & Roles
* **Actor**: PR Employee.
* **Role Protection**: The diagram notes "Role: PR only. PRHeader CANNOT fill surveys". This is enforced via the `EnsureRoleMiddleware` (aliased to `role:PR`). The routing layer completely blocks `PRHeader`, `Quality`, and `Admin` users from accessing the `POST /responses` endpoint, returning an HTTP 403. As an additional defense-in-depth measure, the `ResponseController::store` method explicitly checks `$user->hasRole('PR')`.

## 2. "Select Active Survey Cycle" (<<include>>) & "Load Template Questions" (<<include>>)
* **API Endpoint**: `GET /cycles/active`.
* **DRY/SOLID Implementation**: The loading of active cycles and their associated templates is handled by the `TemplateQueryService`. By using the `TemplateFilter::forFillSurvey()` specification object, this service dynamically applies the necessary query scopes (e.g., `Status = Active` AND `IsActive = true`). This prevents duplicating query logic across controllers (SRP and DRY).

## 3. "Search / Register Patient (MRN)" & "Register New Patient" (<<extend>>)
* **API Endpoints**: `GET /patients?q={MRN}` and `POST /patients`.
* **Data Access**: Controlled by `PatientRepositoryInterface` to decouple Eloquent queries from the controller logic. The `PatientController` handles the HTTP request and delegates to the repository.

## 4. "Validate Required Fields" (<<include>>)
* **Validation Centralization**: Input validation is entirely abstracted from the controller into the `StoreResponseRequest` Form Request class.
* **Mutual Exclusivity Logic**: The rule stating "Answer must have exactly one of OptionId or TextValue" is implemented within the `withValidator` method of `StoreResponseRequest` using an `$validator->after()` hook. This adheres to DRY as it acts as a single source of truth for validation before data reaches the controller.

## 5. "Submit Response & Answers" (<<include>>)
* **API Endpoint**: `POST /responses`.
* **Service Layer & Database Transaction**: Handled by the `SurveyService::submitResponse` method. This method uses a DB transaction to ensure atomic saves:
    1. It creates the `Response` record.
    2. It loops through and saves individual `Answer` records.
    3. It updates the `SurveyTemplate.HasResponses` flag to `true`, which locks the template from future edits.
