# Patient Aggregation Service (Admin)

This service centralizes the logic for updating aggregated data in various Firestore collections _when patient data is updated or deleted_. It is designed primarily for use by Cloud Functions triggered by changes in the `patients` collection.

**Note:** No specific aggregations are currently defined for patient _creation_ events in this service.

## `PatientAggregationService` Class

### Constructor

```typescript
constructor(firestore?: admin.firestore.Firestore)
```

Initializes the service with an Admin Firestore instance. Uses the default instance if none is provided.

### Methods Triggered by Patient **Update**

- **`updatePatientInfoInCalendarEvents(patientId: string, patientInfo: any): Promise<void>`**
  - Uses a Collection Group query (`calendar` subcollection) to find all _upcoming_ calendar events associated with the `patientId`.
  - Updates the embedded `patientInfo` object in these calendar events with the provided `patientInfo`.

### Methods Triggered by Patient **Deletion**

- **`cancelUpcomingCalendarEventsForPatient(patientId: string): Promise<void>`**
  - Uses a Collection Group query (`calendar` subcollection) to find all _upcoming_ calendar events associated with the `patientId`.
  - Sets the `status` of these events to `CANCELED` and adds a `cancelReason` ("Patient deleted").
