# Frontend Changes - Liberatorie Feature

## Overview

This document describes the frontend changes made to implement the "Liberatorie" (waivers) feature in the user booking form. This feature allows users to view and accept required waivers associated with facilities before submitting a booking.

## Date

2025-12-12

## Files Modified

### 1. TypeScript Component

**File:** `src/main/webapp/app/entities/prenotazione/prenotazione-form-user.component.ts`

#### Changes Made:

**Imports Added (lines 10-18):**

- `LiberatoriaService` - Service for managing waiver acceptances
- `ModelloLiberatoriaService` - Service for managing waiver templates
- `ILiberatoria` and `Liberatoria` - Liberatoria model interface and class
- `IModelloLiberatoria` - ModelloLiberatoria model interface

**Service Injections Added (lines 40-47):**

- `liberatoriaService` - Injected service for Liberatoria CRUD operations
- `modelloLiberatoriaService` - Injected service for ModelloLiberatoria CRUD operations
- `modelloLiberatorias` - Ref array to store all waiver templates
- `userLiberatorias` - Ref array to store user's accepted waivers
- `isLoadingLiberatorie` - Ref boolean for loading state
- `selectedModello` - Ref for the currently selected waiver template in modal

**Computed Properties Added (lines 71-96):**

- `liberatorieStatus` - Computed property that:
  - Filters ModelloLiberatoria by selected struttura
  - Maps each template to include acceptance status
  - Returns array with structure: `{ modello, liberatoria, isAccepted }`
- `allLiberatorieAccepted` - Computed property that:
  - Returns true if no waivers required OR all waivers are accepted
  - Used for form validation

**Data Loading Function Added (lines 98-119):**

- `loadLiberatorieData()` - Async function that:
  - Fetches all ModelloLiberatoria records
  - Fetches all Liberatoria records
  - Filters Liberatoria by current user ID (client-side filtering)
  - Handles loading states and errors

**initData() Modified (lines 121-142):**

- Added call to `loadLiberatorieData()` after fetching user and strutture
- Ensures liberatorie data is loaded on component mount

**Return Statement Updated (lines 155-179):**

- Added all new refs and computed properties to expose them to the template:
  - `liberatoriaService`
  - `modelloLiberatoriaService`
  - `modelloLiberatorias`
  - `userLiberatorias`
  - `isLoadingLiberatorie`
  - `selectedModello`
  - `liberatorieStatus`
  - `allLiberatorieAccepted`

**Methods Added (lines 181-254):**

1. **`save()` Modified (lines 182-211):**
   - Added validation check for liberatorie acceptance
   - Blocks form submission if `!allLiberatorieAccepted`
   - Shows error message to user if waivers not accepted

2. **`showLiberatoriaModal()` Added (lines 213-216):**
   - Sets selected waiver template
   - Opens modal using ref

3. **`closeLiberatoriaModal()` Added (lines 218-221):**
   - Clears selected waiver template
   - Closes modal

4. **`acceptLiberatoria()` Added (lines 223-253):**
   - Creates new Liberatoria instance
   - Sets `accettata` to current date
   - Associates with current user and selected template
   - Calls backend API to create record
   - Updates local state with new acceptance
   - Closes modal and shows success message
   - Handles errors gracefully

---

### 2. Vue Template

**File:** `src/main/webapp/app/entities/prenotazione/prenotazione-form-user.vue`

#### Changes Made:

**Liberatorie Section Added (lines 223-273):**

- New card section with title "Liberatorie"
- Conditional rendering based on `v-if="prenotazione.struttura"` - only shows when facility is selected
- Three states handled:
  1. **Loading State** (lines 229-233): Shows spinner while fetching data
  2. **No Waivers State** (lines 235-237): Shows info alert when no waivers required
  3. **Waivers List State** (lines 239-266): Displays list of waivers with:
     - Green badge + check icon for accepted waivers
     - Yellow badge + warning icon for pending waivers
     - Clickable link to open modal for pending waivers
     - Acceptance date for accepted waivers (formatted in Italian)
- Warning alert (lines 268-271): Shows when not all waivers are accepted

**Modal Added (lines 290-337):**

- Bootstrap Vue modal with ref `liberatoriaModal`
- Large size (`size="lg"`)
- Closes on hidden event
- **Modal Header (lines 292-294):**
  - Displays waiver template name
- **Modal Body (lines 296-326):**
  - Shows waiver text in bordered container with pre-wrap formatting (lines 298-303)
  - Download button for attached document if present (lines 305-316)
  - Acceptance statement with user's full name (lines 318-325)
  - Italian text: "Il sottoscritto {nome} {cognome} presa visione della documentazione proposta accetta le condizioni ivi indicate"
- **Modal Footer (lines 328-336):**
  - Cancel button - closes modal
  - Accept button - calls `acceptLiberatoria()` method
  - Both buttons disabled during save operation

**Submit Button Updated (line 281):**

- Added `!allLiberatorieAccepted` to disabled condition
- Button now disabled if: validation fails OR saving OR not all waivers accepted

---

### 3. Internationalization

**File:** `src/main/webapp/i18n/it/prenotazione.json`

#### Changes Made:

**New Translation Keys Added (lines 41-46):**

- `liberatorie`: "Liberatorie" - Section title
- `noLiberatorieRequired`: "Nessuna liberatoria richiesta per questa struttura" - Info message
- `liberatorieWarning`: "È necessario accettare tutte le liberatorie richieste prima di inviare la prenotazione" - Warning message
- `liberatorieRequired`: "Devi accettare tutte le liberatorie richieste" - Error message
- `acceptanceStatement`: "Dichiarazione di accettazione" - Modal acceptance statement label
- `accept`: "Accetta" - Accept button text

---

## Feature Functionality

### User Flow

1. **User navigates to new booking form** (`/prenotazione/nuova`)
2. **Form loads with existing sections:**
   - Booking Details (struttura selection, dates, participants, etc.)
   - User Data (personal information display)
3. **User selects a facility (struttura)**
4. **Liberatorie section appears** (if facility has associated waivers)
5. **System displays waiver status:**
   - ✅ Green check = already accepted
   - ⚠️ Warning icon + clickable link = pending acceptance
6. **User clicks on pending waiver link**
7. **Modal opens showing:**
   - Waiver name
   - Waiver text content
   - Document download link (if available)
   - Acceptance statement with user's name
8. **User clicks "Accetta" button**
9. **System creates Liberatoria record** with:
   - Current timestamp (`accettata`)
   - User reference
   - Waiver template reference
10. **Modal closes automatically**
11. **Liberatorie section updates** - waiver now shows as accepted
12. **User can submit form** once all waivers are accepted

### Validation Logic

**Form submission is blocked if:**

- Standard Vuelidate validation fails (struttura is required)
- Not all required waivers are accepted (`!allLiberatorieAccepted`)

**Visual feedback:**

- Submit button is disabled when waivers are pending
- Warning alert appears in Liberatorie section
- Error message shown if user attempts to submit without all acceptances

### Data Management

**Client-Side Filtering:**

- All ModelloLiberatoria records fetched on load
- All user's Liberatoria records fetched on load
- Filtered in `liberatorieStatus` computed property based on selected struttura

**State Updates:**

- When waiver is accepted, new Liberatoria is added to `userLiberatorias` array
- Computed property `liberatorieStatus` automatically recalculates
- UI updates reactively without page reload

**Reactive Behavior:**

- Changing struttura selection automatically updates displayed waivers
- No additional API calls needed (data is pre-loaded)

---

## Technical Details

### Dependencies

- **Services:** LiberatoriaService, ModelloLiberatoriaService
- **Models:** ILiberatoria, Liberatoria, IModelloLiberatoria
- **Vue:** Composition API with ref, computed
- **Bootstrap Vue Next:** b-modal component
- **Vuelidate:** Form validation
- **Font Awesome:** Icons (check, exclamation-triangle, download)

### API Endpoints Used

- `GET /api/modello-liberatorias` - Fetch all waiver templates
- `GET /api/liberatorias` - Fetch all waiver acceptances
- `POST /api/liberatorias` - Create new waiver acceptance

### Data Structures

**liberatorieStatus (computed property):**

```typescript
[
  {
    modello: IModelloLiberatoria,     // Waiver template
    liberatoria: ILiberatoria | null, // User's acceptance (null if not accepted)
    isAccepted: boolean               // True if accepted
  },
  ...
]
```

**Liberatoria creation:**

```typescript
{
  accettata: Date,                    // Current timestamp
  utente: IUtenteApp,                 // Current user
  modelloLiberatoria: IModelloLiberatoria  // Selected template
}
```

---

## Performance Considerations

### Current Implementation (Client-Side Filtering)

- **Advantages:**
  - No backend changes required
  - Works immediately
  - Simple implementation
- **Disadvantages:**
  - Fetches ALL ModelloLiberatoria (could be many)
  - Fetches ALL Liberatoria (could be thousands)
  - Network overhead on initial load
  - Client-side filtering overhead

### Future Optimization (Backend Filtering)

For production environments with large datasets, consider adding backend endpoints:

- `GET /api/modello-liberatorias?strutturaId={id}` - Filter templates by facility
- `GET /api/liberatorias?utenteId={id}` - Filter acceptances by user

---

## Edge Cases Handled

1. **No Struttura Selected:** Liberatorie section remains hidden
2. **Struttura with No Waivers:** Shows "Nessuna liberatoria richiesta" message
3. **Struttura Changed:** Computed property automatically updates displayed waivers
4. **User Already Accepted Some Waivers:** Shows correct status for each
5. **API Failures:** Error messages displayed via alert service
6. **Modal State Management:** selectedModello cleared on close to prevent stale data
7. **Concurrent Operations:** isSaving flag prevents multiple simultaneous actions

---

## Browser Compatibility

- **Date Formatting:** Uses `toLocaleDateString('it-IT')` for Italian date format
- **Modal:** Bootstrap Vue Next modals compatible with modern browsers
- **Icons:** Font Awesome icons render correctly in all modern browsers

---

## Testing Recommendations

### Manual Testing Checklist

- [ ] Form loads successfully
- [ ] Liberatorie section hidden when no struttura selected
- [ ] Liberatorie section appears when struttura selected
- [ ] Correct waivers displayed for each struttura
- [ ] Accepted waivers show green check
- [ ] Pending waivers show warning icon and link
- [ ] Clicking pending waiver opens modal
- [ ] Modal displays waiver name, text, and document
- [ ] Acceptance statement shows correct user name
- [ ] Accept button creates Liberatoria
- [ ] Modal closes after acceptance
- [ ] Waiver status updates to accepted
- [ ] Submit button disabled when waivers pending
- [ ] Error message shown when trying to submit without acceptances
- [ ] Form submits successfully when all waivers accepted
- [ ] Changing struttura updates waiver list

### Integration Testing

- Test with strutture that have 0, 1, and multiple waivers
- Test with users who have already accepted some waivers
- Test API error scenarios (network failure, server error)
- Test modal close on Escape key
- Test keyboard navigation

---

## Known Limitations

1. **No Backend Filtering:** All records fetched and filtered client-side
2. **No Date Validation:** ModelloLiberatoria `validoDal`/`validoAl` not currently enforced
3. **No Versioning:** No tracking of which version of waiver was accepted
4. **No Revocation:** Users cannot revoke acceptances
5. **Document Type Assumption:** Download link assumes PDF extension

---

## Future Enhancements

1. **Backend Optimization:** Add filtered query endpoints
2. **Date Validation:** Filter by validity period
3. **Versioning:** Track waiver template versions
4. **Revocation Feature:** Allow users to revoke and re-accept
5. **Document Preview:** Inline PDF viewer
6. **Audit Trail:** Show full acceptance history
7. **Notifications:** Email confirmation of waiver acceptance

---

## Summary

This implementation successfully adds a complete waiver management system to the user booking form. Users must review and accept all required waivers before submitting a booking. The solution is fully reactive, handles edge cases gracefully, and provides clear visual feedback throughout the process.

The feature follows Vue 3 Composition API best practices, integrates seamlessly with the existing JHipster application structure, and maintains consistency with the application's UI/UX patterns.
