# PR Patient Survey System — Revised Laravel Solution Structure with Auth & Branch Execution

## Overview
This revised document updates the earlier solution structure to close the five targeted gaps identified in the review. The architecture remains sound: Laravel back end, MySQL database, shared service layer for API and Web delivery, Strategy pattern for response scoping, Template Method for PDFs, and strict DRY/SOLID application across all modules.[file:1][file:2][file:3][file:5]

The main revision is the addition of a dedicated authentication and branch-execution authorization layer for Module 1. This ensures the Flutter mobile flow remains secure by requiring the Laravel API to re-check branch authorization on every survey-filling request, not only at login or menu entry.[file:3][file:5]

## Confirmed Corrections

The following corrections are now part of the structure:

- Add JWT authentication services and blacklist persistence.[file:5]
- Add branch execution middleware and verification services for Module 1.[file:3][file:5]
- Split authentication, role authorization, and branch authorization into separate middleware classes to preserve Single Responsibility.[file:1]
- Add `ResponsePolicy` for response/PDF access control instead of controller-only checks.[file:1][file:3]
- Add a branch access key column and JWT blacklist table migrations.[file:5]
- Update route middleware chains for `GET /cycles/active` and `POST /responses`.[file:3][file:5]
- Expand service container bindings to include auth and authorization services.[file:1][file:2]

## Revised Top-Level Folder Purpose

| Folder | Why It Exists |
|---|---|
| `app/Http/Controllers/Api/` | JSON endpoints for Flutter and external clients; controllers stay thin and call services only.[file:2][file:5] |
| `app/Http/Controllers/Web/` | Blade/web delivery using the same shared services as API controllers, preventing duplicated query logic.[file:2] |
| `app/Http/Middleware/` | Separate request pipeline concerns: JWT parsing, role checking, and branch execution verification.[file:1] |
| `app/Http/Requests/` | Central request validation, including answer XOR validation and future branch-related request rules.[file:1] |
| `app/Models/` | Eloquent models representing normalized MySQL tables defined in the source-of-truth schema.[file:5] |
| `app/Policies/` | Central authorization rules such as template lock and response visibility/export checks.[file:1][file:3] |
| `app/Services/` | Shared business logic and orchestration layer used by both API and Web surfaces.[file:1][file:2] |
| `app/Services/Auth/` | Authentication-specific services: JWT issuing, blacklist checks, and authenticated user context hydration. |
| `app/Services/Authorization/` | Authorization services that decide whether a user may execute branch-bound actions. |
| `app/Services/Authorization/Strategies/` | Strategy implementations for different branch verification mechanisms. |
| `app/Services/Scopes/` | Role/data scoping strategies used across responses, reports, and dashboards.[file:1] |
| `app/Pdf/` | PDF engine classes, isolated from HTTP delivery and extensible through Template Method + registry.[file:2] |
| `app/Providers/` | Central IoC bindings for all reusable services.[file:1] |
| `database/migrations/` | Versioned MySQL schema definitions, including new auth/branch support tables. |
| `database/seeders/` | Mandatory seed data for roles, report permissions, and optionally branch access initialization.[file:5] |
| `routes/` | Route entry points split into API and Web concerns.[file:2][file:5] |
| `resources/views/` | Blade templates for PDFs and web reports.[file:2] |
| `config/` | Configuration values like report thresholds and JWT settings. |

## Revised Middleware Structure

The middleware layer is now explicitly separated by concern.

| File | Alias | Responsibility |
|---|---|---|
| `app/Http/Middleware/AuthenticateJwt.php` | `jwt.auth` | Parse JWT, validate token, check blacklist, and hydrate `AuthenticatedUserContext`. |
| `app/Http/Middleware/EnsureRoleMiddleware.php` | `role` | Validate that the authenticated user has one of the allowed roles, using context rather than raw token parsing.[file:1] |
| `app/Http/Middleware/RequireBranchExecution.php` | `branch.execution` | Enforce Module 1 branch execution rules by delegating to `BranchExecutionVerifier`. |

This split keeps JWT parsing, role checking, and branch verification independent, which is consistent with SRP and avoids a monolithic middleware class.[file:1]

## New Auth Services

### `app/Services/Auth/JwtAuthService.php`
Issues JWT tokens, validates credentials, and provides one reusable auth implementation for Flutter and any Laravel web entry point.

### `app/Services/Auth/JwtBlacklistService.php`
Stores invalidated JWT identifiers and checks them on each authenticated request so logout becomes enforceable server-side.

### `app/Services/Auth/AuthenticatedUserContext.php`
A DTO/value object containing the authenticated user, roles, branch id, and any resolved claims needed downstream.

### `app/Services/Authorization/RoleAuthorizationService.php`
Performs reusable role authorization checks outside controllers and keeps role rules consistent with middleware/policies.

### `app/Services/Authorization/BranchExecutionVerifier.php`
Coordinates branch execution validation for Module 1. It receives the authenticated context and branch key and delegates to a selected strategy.

## New Authorization Strategies

| File | Responsibility |
|---|---|
| `app/Services/Authorization/Strategies/UserBranchMatchStrategy.php` | Verifies branch execution by matching the user’s assigned branch against the requested or resolved branch context. |
| `app/Services/Authorization/Strategies/BranchAccessKeyStrategy.php` | Verifies `branch_id + branch_access_key` against the `branches` table before Module 1 actions are allowed. |

This matches the reviewed mobile flow: the app can obtain a branch proof from the local branch machine, but the central Laravel API still performs the authoritative check on every protected Module 1 request.

## Policies

### Existing
- `app/Policies/SurveyTemplatePolicy.php` — keeps the `HasResponses` lock centralized for template, section, question, and option updates/deletes.[file:1]

### New
- `app/Policies/ResponsePolicy.php` — controls response visibility and PDF export access, replacing controller-body authorization for response detail and response PDF routes.[file:3]

## Required Model and Schema Updates

### Branch model update
The `Branch` model must include the new `branch_access_key` column because branch verification depends on server-side comparison between the authenticated user’s assigned branch and the provided branch proof.

### New migrations

| Migration | Purpose |
|---|---|
| `..._add_branch_access_key_to_branches.php` | Adds `branch_access_key` to `branches` for branch proof verification. |
| `..._create_jwt_blacklist_table.php` | Stores blacklisted JWT identifiers/tokens for logout enforcement. |

These migrations are required before coding starts because both features are referenced directly by the reviewed security flow.

## Routes — Revised API Middleware Chains

The API route definition must be updated so Module 1 endpoints are protected by the full auth chain.

### Required route groups

```php
Route::middleware(['jwt.auth', 'role:PR', 'branch.execution'])->group(function () {
    Route::get('/cycles/active', [CycleController::class, 'active']);
    Route::post('/responses', [ResponseController::class, 'store']);
});
```

This ensures the server re-checks branch authorization on every survey-fill request, which is the required production-safe behavior for Flutter mobile execution.

### Additional route correction
`GET /responses/{id}/pdf` should not rely on controller-body checks alone. It must be protected by policy or explicit middleware-aligned authorization, consistent with the rest of the structure.

## Revised Services Registration

`SurveyServiceProvider` must register the newly added auth and authorization services so they are resolved through the container instead of manual instantiation.

### Required bindings

- `JwtAuthService`
- `JwtBlacklistService`
- `AuthenticatedUserContext` factory/builder as needed
- `RoleAuthorizationService`
- `BranchExecutionVerifier`
- `UserBranchMatchStrategy`
- `BranchAccessKeyStrategy`
- Existing shared services from the earlier document, including query services, clone services, report services, scope factories, data services, and PDF rendering services.[file:1][file:2]

## Revised Folder Tree

```text
app/
├── Http/
│   ├── Controllers/
│   │   ├── Api/
│   │   │   ├── AuthController.php
│   │   │   ├── UserController.php
│   │   │   ├── PatientController.php
│   │   │   ├── CycleController.php
│   │   │   ├── TemplateController.php
│   │   │   ├── SectionController.php
│   │   │   ├── QuestionController.php
│   │   │   ├── OptionController.php
│   │   │   ├── ResponseController.php
│   │   │   ├── ReportController.php
│   │   │   └── DashboardController.php
│   │   └── Web/
│   │       ├── ReportWebController.php
│   │       └── TemplateWebController.php
│   ├── Middleware/
│   │   ├── AuthenticateJwt.php
│   │   ├── EnsureRoleMiddleware.php
│   │   └── RequireBranchExecution.php
│   └── Requests/
│       ├── LoginRequest.php
│       ├── StoreUserRequest.php
│       ├── StorePatientRequest.php
│       ├── StoreTemplateRequest.php
│       ├── StoreSectionRequest.php
│       ├── StoreQuestionRequest.php
│       ├── StoreOptionRequest.php
│       ├── StoreCycleRequest.php
│       └── StoreResponseRequest.php
├── Models/
│   ├── ApplicationUser.php
│   ├── Role.php
│   ├── UserRole.php
│   ├── Department.php
│   ├── Branch.php
│   ├── DepartmentBranch.php
│   ├── Patient.php
│   ├── SurveyTemplate.php
│   ├── SurveySection.php
│   ├── Question.php
│   ├── Option.php
│   ├── SurveyCycle.php
│   ├── Response.php
│   ├── Answer.php
│   └── ReportPermission.php
├── Policies/
│   ├── SurveyTemplatePolicy.php
│   └── ResponsePolicy.php
├── Services/
│   ├── Auth/
│   │   ├── JwtAuthService.php
│   │   ├── JwtBlacklistService.php
│   │   └── AuthenticatedUserContext.php
│   ├── Authorization/
│   │   ├── RoleAuthorizationService.php
│   │   ├── BranchExecutionVerifier.php
│   │   └── Strategies/
│   │       ├── UserBranchMatchStrategy.php
│   │       └── BranchAccessKeyStrategy.php
│   ├── TemplateQueryService.php
│   ├── TemplateFilter.php
│   ├── TemplateCloneService.php
│   ├── TemplateFactory.php
│   ├── ReportPermissionService.php
│   ├── DashboardService.php
│   ├── ResponseSheetDataService.php
│   ├── EmployeeAuditDataService.php
│   ├── CycleAnalysisDataService.php
│   ├── TemplateUsageDataService.php
│   ├── BranchSummaryDataService.php
│   ├── FullAuditDataService.php
│   └── Scopes/
│       ├── ResponseScopeStrategy.php
│       ├── PrResponseScope.php
│       ├── PrHeaderResponseScope.php
│       ├── QualityResponseScope.php
│       ├── AdminResponseScope.php
│       └── ResponseScopeFactory.php
├── Pdf/
│   ├── AbstractPdfReport.php
│   ├── PdfRenderService.php
│   ├── ResponseSheetPdf.php
│   ├── EmployeeAuditPdf.php
│   ├── CycleAnalysisPdf.php
│   ├── TemplateUsagePdf.php
│   ├── BranchSummaryPdf.php
│   └── FullAuditPdf.php
└── Providers/
    └── SurveyServiceProvider.php

database/
├── migrations/
│   ├── ..._create_branches_table.php
│   ├── ..._add_branch_access_key_to_branches.php
│   ├── ..._create_departments_table.php
│   ├── ..._create_department_branches_table.php
│   ├── ..._create_application_users_table.php
│   ├── ..._create_roles_table.php
│   ├── ..._create_user_roles_table.php
│   ├── ..._create_patients_table.php
│   ├── ..._create_survey_templates_table.php
│   ├── ..._create_survey_sections_table.php
│   ├── ..._create_questions_table.php
│   ├── ..._create_options_table.php
│   ├── ..._create_survey_cycles_table.php
│   ├── ..._create_responses_table.php
│   ├── ..._create_answers_table.php
│   ├── ..._create_report_permissions_table.php
│   ├── ..._create_jwt_blacklist_table.php
│   └── ..._add_indexes.php
└── seeders/
    ├── DatabaseSeeder.php
    ├── RoleSeeder.php
    └── ReportPermissionSeeder.php

routes/
├── api.php
└── web.php

resources/views/
├── pdf/
│   ├── partials/
│   │   ├── header.blade.php
│   │   ├── filters-bar.blade.php
│   │   └── footer.blade.php
│   ├── response-sheet.blade.php
│   ├── employee-audit.blade.php
│   ├── cycle-analysis.blade.php
│   ├── template-usage.blade.php
│   ├── branch-summary.blade.php
│   └── full-audit.blade.php
└── reports/
    ├── employee-audit.blade.php
    ├── employee-audit-print.blade.php
    ├── cycle-analysis.blade.php
    ├── branch-summary.blade.php
    ├── templates-index.blade.php
    └── cycles-index.blade.php

config/
├── reports.php
└── auth_jwt.php
```

## Clarifications Added

### Quality response scope
A dedicated `QualityResponseScope.php` is added so the factory does not silently treat Quality as Admin. This keeps intent explicit and avoids accidental over-broad data access.

### Web routes
The web layer was previously too thin. If the admin web panel will expose template management and cycle management, matching web routes should be added for the listed controllers/views, not only report pages.

### JWT config separation
A dedicated `config/auth_jwt.php` is added so token TTL, blacklist behavior, and related auth settings remain isolated from report configuration.

## Revised File Count

| Category | Previous | Revised |
|---|---:|---:|
| Middleware | 1 | 3 |
| Auth services | 0 | 3 |
| Authorization services/strategies | 0 | 4 |
| Policies | 1 | 2 |
| Migrations | 16 | 18 |
| Scope classes | 4 | 5 |
| Config files | 1 | 2 |
| Total | 100 | 112 |

## Production Interpretation for Flutter Module 1

The secure mobile execution flow is now:

1. User logs in through central Laravel API and receives JWT with identity, roles, and branch context.
2. Flutter checks visible modules by role.
3. When PR accesses Module 1, Flutter obtains branch proof from the local branch environment.
4. Flutter sends that proof on every Module 1 request, for example via `X-Branch-Key`.
5. Laravel runs `jwt.auth + role:PR + branch.execution` before serving active cycles or storing responses.
6. The server, not the client, remains the final authority for branch authorization.

This matches the required correction: the app may assist with branch proof collection, but only Laravel may decide whether the request is allowed.

## Build Order Addendum

Insert these new steps into the original dependency-correct build order:

- After base migrations, add `branch_access_key` and `jwt_blacklist` migrations.
- Before general services, create `Auth/` and `Authorization/` services.
- Before route definitions, register middleware aliases `jwt.auth`, `role`, and `branch.execution`.
- Before final controller wiring, add `ResponsePolicy` and route authorization for response PDF access.

## Final Status

With these additions, the solution structure is no longer just architecturally clean; it is also aligned with the branch-bound execution policy required for Flutter Module 1. The revised structure preserves DRY, respects SOLID, keeps Laravel concerns separated by responsibility, and supports a production-safe PR survey flow using JWT, blacklist enforcement, role gating, and per-request branch verification.[file:1][file:2][file:3][file:5]
