@blackcode_sa/metaestetics-api 1.6.5 → 1.6.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/admin/index.d.mts +195 -172
- package/dist/admin/index.d.ts +195 -172
- package/dist/admin/index.js +8928 -8364
- package/dist/admin/index.mjs +8920 -8356
- package/dist/index.d.mts +8 -2
- package/dist/index.d.ts +8 -2
- package/dist/index.js +3 -0
- package/dist/index.mjs +3 -0
- package/package.json +1 -1
- package/src/admin/aggregation/appointment/README.md +128 -0
- package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +950 -218
- package/src/admin/booking/README.md +125 -0
- package/src/admin/booking/booking.admin.ts +288 -26
- package/src/admin/calendar/calendar.admin.service.ts +183 -0
- package/src/admin/documentation-templates/document-manager.admin.ts +131 -0
- package/src/admin/mailing/appointment/appointment.mailing.service.ts +264 -0
- package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -0
- package/src/admin/mailing/base.mailing.service.ts +1 -1
- package/src/admin/mailing/index.ts +2 -0
- package/src/admin/notifications/notifications.admin.ts +397 -1
- package/src/types/appointment/index.ts +1 -0
- package/src/types/notifications/index.ts +4 -2
- package/src/validations/appointment.schema.ts +1 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
## BookingAdmin Service (`Api/src/admin/booking/booking.admin.ts`)
|
|
2
|
+
|
|
3
|
+
This service is responsible for handling complex booking-related operations on the admin/backend side, intended primarily for use within Firebase Cloud Functions or other trusted server environments.
|
|
4
|
+
|
|
5
|
+
### Class: `BookingAdmin`
|
|
6
|
+
|
|
7
|
+
Manages booking availability calculations and the orchestration of appointment creation, including associated calendar events and documentation.
|
|
8
|
+
|
|
9
|
+
#### Constructor
|
|
10
|
+
|
|
11
|
+
```typescript
|
|
12
|
+
constructor(firestore?: admin.firestore.Firestore)
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
- **`firestore`**: An optional `admin.firestore.Firestore` instance. If not provided, it initializes a default Firestore instance.
|
|
16
|
+
- Initializes an instance of `DocumentManagerAdminService` for handling linked document operations.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
#### Method: `getAvailableBookingSlots`
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
async getAvailableBookingSlots(
|
|
24
|
+
clinicId: string,
|
|
25
|
+
practitionerId: string,
|
|
26
|
+
procedureId: string,
|
|
27
|
+
timeframe: { start: Date | admin.firestore.Timestamp; end: Date | admin.firestore.Timestamp; }
|
|
28
|
+
): Promise<{ availableSlots: { start: admin.firestore.Timestamp }[] }>
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
- Calculates and returns available booking time slots for a specified clinic, practitioner, and procedure within a given timeframe.
|
|
32
|
+
- **Steps Involved**:
|
|
33
|
+
1. Fetches data for the clinic, practitioner, and procedure.
|
|
34
|
+
2. Retrieves calendar events for both the clinic and the practitioner within the specified timeframe.
|
|
35
|
+
3. Converts admin Firestore Timestamps to a client-compatible format for the `BookingAvailabilityCalculator`.
|
|
36
|
+
4. Uses `BookingAvailabilityCalculator.calculateSlots()` to determine available slots based on working hours, existing events, and procedure duration.
|
|
37
|
+
5. Converts the resulting available slot timestamps back to admin Firestore Timestamps before returning.
|
|
38
|
+
- **Error Handling**: Throws an error if essential entities (clinic, practitioner, procedure) are not found or if any other issue occurs during the calculation.
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
#### Method: `orchestrateAppointmentCreation`
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
async orchestrateAppointmentCreation(
|
|
46
|
+
data: OrchestrateAppointmentCreationData, // { patientId, procedureId, appointmentStartTime, appointmentEndTime, patientNotes? }
|
|
47
|
+
authenticatedUserId: string
|
|
48
|
+
): Promise<{
|
|
49
|
+
success: boolean;
|
|
50
|
+
appointmentId?: string;
|
|
51
|
+
appointmentData?: Appointment; // The created Appointment object
|
|
52
|
+
practitionerCalendarEventId?: string; // ID of the practitioner's calendar event
|
|
53
|
+
patientCalendarEventId?: string; // ID of the patient's calendar event
|
|
54
|
+
clinicCalendarEventId?: string; // ID of the clinic's calendar event
|
|
55
|
+
error?: string;
|
|
56
|
+
}>
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
- Orchestrates the comprehensive creation of a new appointment. This is a critical backend process that ensures data integrity and sets up all related entities atomically.
|
|
60
|
+
- **Input Data (`OrchestrateAppointmentCreationData`)**:
|
|
61
|
+
- `patientId`: ID of the patient for whom the appointment is being booked.
|
|
62
|
+
- `procedureId`: ID of the procedure.
|
|
63
|
+
- `appointmentStartTime`: Firestore Timestamp for the start of the appointment.
|
|
64
|
+
- `appointmentEndTime`: Firestore Timestamp for the end of the appointment.
|
|
65
|
+
- `patientNotes` (optional): Any notes provided by the patient during booking.
|
|
66
|
+
- **`authenticatedUserId`**: The ID of the user making the request (typically the patient themselves, used for auditing and authorization checks).
|
|
67
|
+
|
|
68
|
+
- **Core Operations (performed within a single Firestore batch transaction)**:
|
|
69
|
+
|
|
70
|
+
1. **Input Validation**: Checks for required fields and valid timeframes.
|
|
71
|
+
2. **Data Fetching**: Retrieves all necessary documents:
|
|
72
|
+
- `Procedure` (based on `data.procedureId`)
|
|
73
|
+
- `Clinic` (based on `procedure.clinicBranchId`)
|
|
74
|
+
- `Practitioner` (based on `procedure.practitionerId`)
|
|
75
|
+
- `PatientProfile` and `PatientSensitiveInfo` (based on `data.patientId`)
|
|
76
|
+
- `ClinicGroup` (based on `clinicData.clinicGroupId`)
|
|
77
|
+
3. **Information Aggregation**: Creates summarized info objects (`ClinicInfo`, `PractitionerProfileInfo`, `PatientProfileInfo`, `CalendarProcedureInfo`) from the fetched data.
|
|
78
|
+
4. **Status Determination**: Calculates the initial status for the appointment (`AppointmentStatus.CONFIRMED` or `PENDING`) and associated calendar events (`CalendarEventStatus.CONFIRMED` or `PENDING`) based on the `clinicGroupData.autoConfirmAppointments` setting.
|
|
79
|
+
5. **Calendar Event Creation**: For each of the practitioner, patient, and clinic:
|
|
80
|
+
- Generates a unique ID for the calendar event.
|
|
81
|
+
- Constructs the `CalendarEvent` data, including links to the appointment, relevant profiles, procedure details, event times, and status.
|
|
82
|
+
- Adds a `set` operation to the Firestore batch for creating this calendar event in the respective entity's `calendar` subcollection (e.g., `practitioners/{id}/calendar/{eventId}`).
|
|
83
|
+
6. **Documentation Initialization (via `DocumentManagerAdminService`)**:
|
|
84
|
+
- Calls `this.documentManagerAdmin.batchInitializeAppointmentForms()`.
|
|
85
|
+
- This service method iterates through the `procedure.documentationTemplates`.
|
|
86
|
+
- For each template, it creates a `FilledDocument` (in `DRAFT` or `PENDING` status) in the appropriate subcollection of the new appointment (`appointments/{newAppointmentId}/user-forms/{formId}` or `appointments/{newAppointmentId}/doctor-forms/{formId}`).
|
|
87
|
+
- These creation operations are added to the _same Firestore batch_.
|
|
88
|
+
- The method returns an object containing:
|
|
89
|
+
- `initializedFormsInfo: LinkedFormInfo[]`: Detailed info for each initialized form.
|
|
90
|
+
- `pendingUserFormsIds: string[]`: IDs of required user form templates.
|
|
91
|
+
- `allLinkedTemplateIds: string[]`: IDs of all templates linked to the procedure.
|
|
92
|
+
7. **Appointment Object Construction**: Creates the main `Appointment` data object, populating all its fields, including:
|
|
93
|
+
- `id`: The newly generated appointment ID.
|
|
94
|
+
- `calendarEventId`: Linked to the `practitionerCalendarEventId`.
|
|
95
|
+
- All aggregated info objects.
|
|
96
|
+
- Timestamps (booking, confirmation, start, end), correctly using `FirebaseClientTimestamp` for client compatibility.
|
|
97
|
+
- `pendingUserFormsIds` and `linkedFormIds`: Populated from the result of `batchInitializeAppointmentForms`.
|
|
98
|
+
- `linkedForms`: Populated with the `initializedFormsInfo` array from `batchInitializeAppointmentForms`.
|
|
99
|
+
8. **Batch Commit**: Commits all the `set` operations (appointment, 3 calendar events, all filled documents) to Firestore. This ensures atomicity – either all documents are created, or none are.
|
|
100
|
+
|
|
101
|
+
- **Return Value**: On success, returns an object with `success: true`, the `appointmentId`, the full `appointmentData`, and the IDs of the three created calendar events. On failure, returns `success: false` and an error message.
|
|
102
|
+
|
|
103
|
+
---
|
|
104
|
+
|
|
105
|
+
### Helper Methods (Private)
|
|
106
|
+
|
|
107
|
+
- **`_generateCalendarProcedureInfo(procedure: Procedure): CalendarProcedureInfo`**
|
|
108
|
+
- Creates a `CalendarProcedureInfo` object from a `Procedure` object, used when constructing `CalendarEvent` data.
|
|
109
|
+
- **`_generateProcedureSummaryInfo(procedure: Procedure, clinicData: Clinic, practitionerData: Practitioner): ProcedureSummaryInfo`**
|
|
110
|
+
- Creates a `ProcedureSummaryInfo` object, used when constructing the `Appointment` data.
|
|
111
|
+
- **`_generateProcedureExtendedInfo(procedure: Procedure): ProcedureExtendedInfo`**
|
|
112
|
+
- Creates a `ProcedureExtendedInfo` object, also used for the `Appointment` data.
|
|
113
|
+
- **`getPractitionerCalendarEvents(...)` / `getClinicCalendarEvents(...)`** (example, actual might vary if used by `getAvailableBookingSlots`)
|
|
114
|
+
- Fetches calendar events for a specific entity within a time range.
|
|
115
|
+
- **Timestamp Conversion Utilities** (example, if present for `getAvailableBookingSlots`)
|
|
116
|
+
- Handles conversions between admin and client Firestore Timestamp objects.
|
|
117
|
+
|
|
118
|
+
---
|
|
119
|
+
|
|
120
|
+
### Dependencies
|
|
121
|
+
|
|
122
|
+
- **`DocumentManagerAdminService`**: Used to handle the creation and management of `FilledDocument` instances associated with appointments.
|
|
123
|
+
- **Firebase Admin SDK**: For all Firestore interactions.
|
|
124
|
+
- **Various Type Definitions**: From `../../types/` for `Appointment`, `CalendarEvent`, `Procedure`, `Clinic`, `Practitioner`, `Patient`, `DocumentTemplate`, `LinkedFormInfo`, etc.
|
|
125
|
+
- **`BookingAvailabilityCalculator`**: For calculating available booking slots.
|
|
@@ -37,7 +37,13 @@ import {
|
|
|
37
37
|
ProcedureExtendedInfo,
|
|
38
38
|
} from "../../types/appointment";
|
|
39
39
|
import { Currency } from "../../backoffice/types/static/pricing.types";
|
|
40
|
-
import {
|
|
40
|
+
import {
|
|
41
|
+
DocumentTemplate as AppDocumentTemplate,
|
|
42
|
+
FilledDocument,
|
|
43
|
+
FilledDocumentStatus,
|
|
44
|
+
USER_FORMS_SUBCOLLECTION,
|
|
45
|
+
DOCTOR_FORMS_SUBCOLLECTION,
|
|
46
|
+
} from "../../types/documentation-templates";
|
|
41
47
|
import {
|
|
42
48
|
ClinicInfo,
|
|
43
49
|
PractitionerProfileInfo,
|
|
@@ -47,6 +53,15 @@ import { Category } from "../../backoffice/types/category.types";
|
|
|
47
53
|
import { Subcategory } from "../../backoffice/types/subcategory.types";
|
|
48
54
|
import { Technology } from "../../backoffice/types/technology.types";
|
|
49
55
|
import { Product } from "../../backoffice/types/product.types";
|
|
56
|
+
import {
|
|
57
|
+
CalendarEvent,
|
|
58
|
+
CalendarEventTime,
|
|
59
|
+
CalendarSyncStatus,
|
|
60
|
+
ProcedureInfo as CalendarProcedureInfo,
|
|
61
|
+
CALENDAR_COLLECTION,
|
|
62
|
+
} from "../../types/calendar";
|
|
63
|
+
import { DocumentManagerAdminService } from "../documentation-templates/document-manager.admin";
|
|
64
|
+
import { LinkedFormInfo } from "../../types/appointment";
|
|
50
65
|
|
|
51
66
|
/**
|
|
52
67
|
* Interface for the data required by orchestrateAppointmentCreation
|
|
@@ -65,6 +80,7 @@ export interface OrchestrateAppointmentCreationData {
|
|
|
65
80
|
*/
|
|
66
81
|
export class BookingAdmin {
|
|
67
82
|
private db: admin.firestore.Firestore;
|
|
83
|
+
private documentManagerAdmin: DocumentManagerAdminService;
|
|
68
84
|
|
|
69
85
|
/**
|
|
70
86
|
* Creates a new BookingAdmin instance
|
|
@@ -72,6 +88,7 @@ export class BookingAdmin {
|
|
|
72
88
|
*/
|
|
73
89
|
constructor(firestore?: admin.firestore.Firestore) {
|
|
74
90
|
this.db = firestore || admin.firestore();
|
|
91
|
+
this.documentManagerAdmin = new DocumentManagerAdminService(this.db);
|
|
75
92
|
}
|
|
76
93
|
|
|
77
94
|
/**
|
|
@@ -281,6 +298,18 @@ export class BookingAdmin {
|
|
|
281
298
|
}
|
|
282
299
|
}
|
|
283
300
|
|
|
301
|
+
private _generateCalendarProcedureInfo(
|
|
302
|
+
procedure: Procedure
|
|
303
|
+
): CalendarProcedureInfo {
|
|
304
|
+
return {
|
|
305
|
+
name: procedure.name,
|
|
306
|
+
description: procedure.description,
|
|
307
|
+
duration: procedure.duration, // in minutes
|
|
308
|
+
price: procedure.price,
|
|
309
|
+
currency: procedure.currency,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
284
313
|
/**
|
|
285
314
|
* Orchestrates the creation of a new appointment, including data aggregation.
|
|
286
315
|
* This method is intended to be called from a trusted backend environment (e.g., an Express route handler in a Cloud Function).
|
|
@@ -296,11 +325,17 @@ export class BookingAdmin {
|
|
|
296
325
|
success: boolean;
|
|
297
326
|
appointmentId?: string;
|
|
298
327
|
appointmentData?: Appointment;
|
|
328
|
+
practitionerCalendarEventId?: string;
|
|
329
|
+
patientCalendarEventId?: string;
|
|
330
|
+
clinicCalendarEventId?: string;
|
|
299
331
|
error?: string;
|
|
300
332
|
}> {
|
|
301
333
|
console.log(
|
|
302
334
|
`[BookingAdmin] Orchestrating appointment creation for patient ${data.patientId} by user ${authenticatedUserId}`
|
|
303
335
|
);
|
|
336
|
+
const batch = this.db.batch();
|
|
337
|
+
const adminTsNow = admin.firestore.Timestamp.now();
|
|
338
|
+
const serverTimestampValue = admin.firestore.FieldValue.serverTimestamp();
|
|
304
339
|
|
|
305
340
|
try {
|
|
306
341
|
// --- 1. Input Validation ---
|
|
@@ -412,9 +447,12 @@ export class BookingAdmin {
|
|
|
412
447
|
|
|
413
448
|
// --- 4. Determine initialStatus (based on clinic settings) ---
|
|
414
449
|
const autoConfirm = clinicGroupData.autoConfirmAppointments || false;
|
|
415
|
-
const
|
|
450
|
+
const initialAppointmentStatus = autoConfirm
|
|
416
451
|
? AppointmentStatus.CONFIRMED
|
|
417
452
|
: AppointmentStatus.PENDING;
|
|
453
|
+
const initialCalendarEventStatus = autoConfirm
|
|
454
|
+
? CalendarEventStatus.CONFIRMED
|
|
455
|
+
: CalendarEventStatus.PENDING;
|
|
418
456
|
|
|
419
457
|
// --- 5. Aggregate Information (Snapshots) ---
|
|
420
458
|
const clinicInfo: ClinicInfo = {
|
|
@@ -503,12 +541,12 @@ export class BookingAdmin {
|
|
|
503
541
|
) {
|
|
504
542
|
pendingUserFormsIds = procedure.documentationTemplates
|
|
505
543
|
.filter(
|
|
506
|
-
(template:
|
|
544
|
+
(template: AppDocumentTemplate) =>
|
|
507
545
|
template.isUserForm && template.isRequired
|
|
508
546
|
)
|
|
509
|
-
.map((template:
|
|
547
|
+
.map((template: AppDocumentTemplate) => template.id);
|
|
510
548
|
linkedFormIds = procedure.documentationTemplates.map(
|
|
511
|
-
(template:
|
|
549
|
+
(template: AppDocumentTemplate) => template.id
|
|
512
550
|
);
|
|
513
551
|
}
|
|
514
552
|
|
|
@@ -516,12 +554,154 @@ export class BookingAdmin {
|
|
|
516
554
|
const newAppointmentId = this.db
|
|
517
555
|
.collection(APPOINTMENTS_COLLECTION)
|
|
518
556
|
.doc().id;
|
|
519
|
-
const serverTimestampValue = admin.firestore.FieldValue.serverTimestamp();
|
|
520
|
-
const adminTsNow = admin.firestore.Timestamp.now();
|
|
521
557
|
|
|
558
|
+
const eventTimeForCalendarEvents: CalendarEventTime = {
|
|
559
|
+
start: new FirebaseClientTimestamp(
|
|
560
|
+
data.appointmentStartTime.seconds,
|
|
561
|
+
data.appointmentStartTime.nanoseconds
|
|
562
|
+
),
|
|
563
|
+
end: new FirebaseClientTimestamp(
|
|
564
|
+
data.appointmentEndTime.seconds,
|
|
565
|
+
data.appointmentEndTime.nanoseconds
|
|
566
|
+
),
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
// Practitioner Calendar Event
|
|
570
|
+
const practitionerCalendarEventId = this.db
|
|
571
|
+
.collection(PRACTITIONERS_COLLECTION)
|
|
572
|
+
.doc(practitionerData.id)
|
|
573
|
+
.collection(CALENDAR_COLLECTION)
|
|
574
|
+
.doc().id;
|
|
575
|
+
const practitionerCalendarEventData: CalendarEvent = {
|
|
576
|
+
id: practitionerCalendarEventId,
|
|
577
|
+
appointmentId: newAppointmentId,
|
|
578
|
+
clinicBranchId: clinicData.id,
|
|
579
|
+
clinicBranchInfo: clinicInfo,
|
|
580
|
+
practitionerProfileId: practitionerData.id,
|
|
581
|
+
practitionerProfileInfo: practitionerInfo,
|
|
582
|
+
patientProfileId: patientProfileData.id,
|
|
583
|
+
patientProfileInfo: patientInfo,
|
|
584
|
+
procedureId: procedure.id,
|
|
585
|
+
procedureInfo: this._generateCalendarProcedureInfo(procedure),
|
|
586
|
+
eventName: `Appointment: ${procedure.name} with ${patientInfo.fullName}`,
|
|
587
|
+
eventLocation: clinicData.location,
|
|
588
|
+
eventTime: eventTimeForCalendarEvents,
|
|
589
|
+
description: procedure.description || undefined,
|
|
590
|
+
status: initialCalendarEventStatus,
|
|
591
|
+
syncStatus: CalendarSyncStatus.INTERNAL,
|
|
592
|
+
eventType: CalendarEventType.APPOINTMENT,
|
|
593
|
+
createdAt: serverTimestampValue as any,
|
|
594
|
+
updatedAt: serverTimestampValue as any,
|
|
595
|
+
};
|
|
596
|
+
batch.set(
|
|
597
|
+
this.db
|
|
598
|
+
.collection(PRACTITIONERS_COLLECTION)
|
|
599
|
+
.doc(practitionerData.id)
|
|
600
|
+
.collection(CALENDAR_COLLECTION)
|
|
601
|
+
.doc(practitionerCalendarEventId),
|
|
602
|
+
practitionerCalendarEventData
|
|
603
|
+
);
|
|
604
|
+
|
|
605
|
+
// Patient Calendar Event
|
|
606
|
+
const patientCalendarEventId = this.db
|
|
607
|
+
.collection(PATIENTS_COLLECTION)
|
|
608
|
+
.doc(patientProfileData.id)
|
|
609
|
+
.collection(CALENDAR_COLLECTION)
|
|
610
|
+
.doc().id;
|
|
611
|
+
const patientCalendarEventData: CalendarEvent = {
|
|
612
|
+
id: patientCalendarEventId,
|
|
613
|
+
appointmentId: newAppointmentId,
|
|
614
|
+
clinicBranchId: clinicData.id,
|
|
615
|
+
clinicBranchInfo: clinicInfo,
|
|
616
|
+
practitionerProfileId: practitionerData.id,
|
|
617
|
+
practitionerProfileInfo: practitionerInfo,
|
|
618
|
+
procedureId: procedure.id,
|
|
619
|
+
procedureInfo: this._generateCalendarProcedureInfo(procedure),
|
|
620
|
+
eventName: `Appointment: ${procedure.name} at ${clinicData.name}`,
|
|
621
|
+
eventLocation: clinicData.location,
|
|
622
|
+
eventTime: eventTimeForCalendarEvents,
|
|
623
|
+
description: data.patientNotes || undefined,
|
|
624
|
+
status: initialCalendarEventStatus,
|
|
625
|
+
syncStatus: CalendarSyncStatus.INTERNAL,
|
|
626
|
+
eventType: CalendarEventType.APPOINTMENT,
|
|
627
|
+
createdAt: serverTimestampValue as any,
|
|
628
|
+
updatedAt: serverTimestampValue as any,
|
|
629
|
+
};
|
|
630
|
+
batch.set(
|
|
631
|
+
this.db
|
|
632
|
+
.collection(PATIENTS_COLLECTION)
|
|
633
|
+
.doc(patientProfileData.id)
|
|
634
|
+
.collection(CALENDAR_COLLECTION)
|
|
635
|
+
.doc(patientCalendarEventId),
|
|
636
|
+
patientCalendarEventData
|
|
637
|
+
);
|
|
638
|
+
|
|
639
|
+
// Clinic Calendar Event
|
|
640
|
+
const clinicCalendarEventId = this.db
|
|
641
|
+
.collection(CLINICS_COLLECTION)
|
|
642
|
+
.doc(clinicData.id)
|
|
643
|
+
.collection(CALENDAR_COLLECTION)
|
|
644
|
+
.doc().id;
|
|
645
|
+
const clinicCalendarEventData: CalendarEvent = {
|
|
646
|
+
id: clinicCalendarEventId,
|
|
647
|
+
appointmentId: newAppointmentId,
|
|
648
|
+
clinicBranchId: clinicData.id,
|
|
649
|
+
clinicBranchInfo: clinicInfo,
|
|
650
|
+
practitionerProfileId: practitionerData.id,
|
|
651
|
+
practitionerProfileInfo: practitionerInfo,
|
|
652
|
+
patientProfileId: patientProfileData.id,
|
|
653
|
+
patientProfileInfo: patientInfo,
|
|
654
|
+
procedureId: procedure.id,
|
|
655
|
+
procedureInfo: this._generateCalendarProcedureInfo(procedure),
|
|
656
|
+
eventName: `Appointment: ${procedure.name} for ${patientInfo.fullName} with ${practitionerInfo.name}`,
|
|
657
|
+
eventLocation: clinicData.location,
|
|
658
|
+
eventTime: eventTimeForCalendarEvents,
|
|
659
|
+
description: data.patientNotes || undefined,
|
|
660
|
+
status: initialCalendarEventStatus,
|
|
661
|
+
syncStatus: CalendarSyncStatus.INTERNAL,
|
|
662
|
+
eventType: CalendarEventType.APPOINTMENT,
|
|
663
|
+
createdAt: serverTimestampValue as any,
|
|
664
|
+
updatedAt: serverTimestampValue as any,
|
|
665
|
+
};
|
|
666
|
+
batch.set(
|
|
667
|
+
this.db
|
|
668
|
+
.collection(CLINICS_COLLECTION)
|
|
669
|
+
.doc(clinicData.id)
|
|
670
|
+
.collection(CALENDAR_COLLECTION)
|
|
671
|
+
.doc(clinicCalendarEventId),
|
|
672
|
+
clinicCalendarEventData
|
|
673
|
+
);
|
|
674
|
+
|
|
675
|
+
// --- Initialize Pending/Draft Filled Documents and get form IDs ---
|
|
676
|
+
let initializedFormsInfo: LinkedFormInfo[] = [];
|
|
677
|
+
let pendingUserFormTemplateIds: string[] = [];
|
|
678
|
+
let allLinkedFormTemplateIds: string[] = [];
|
|
679
|
+
|
|
680
|
+
if (
|
|
681
|
+
procedure.documentationTemplates &&
|
|
682
|
+
Array.isArray(procedure.documentationTemplates) &&
|
|
683
|
+
procedure.documentationTemplates.length > 0
|
|
684
|
+
) {
|
|
685
|
+
const formInitResult =
|
|
686
|
+
this.documentManagerAdmin.batchInitializeAppointmentForms(
|
|
687
|
+
batch,
|
|
688
|
+
newAppointmentId,
|
|
689
|
+
procedure.id, // Pass the actual procedureId for the forms
|
|
690
|
+
procedure.documentationTemplates as AppDocumentTemplate[],
|
|
691
|
+
data.patientId,
|
|
692
|
+
procedure.practitionerId,
|
|
693
|
+
procedure.clinicBranchId,
|
|
694
|
+
adminTsNow.toMillis()
|
|
695
|
+
);
|
|
696
|
+
initializedFormsInfo = formInitResult.initializedFormsInfo;
|
|
697
|
+
pendingUserFormTemplateIds = formInitResult.pendingUserFormsIds;
|
|
698
|
+
allLinkedFormTemplateIds = formInitResult.allLinkedTemplateIds;
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
// --- Construct Appointment Object ---
|
|
522
702
|
const newAppointmentData: Appointment = {
|
|
523
703
|
id: newAppointmentId,
|
|
524
|
-
calendarEventId:
|
|
704
|
+
calendarEventId: practitionerCalendarEventId,
|
|
525
705
|
clinicBranchId: procedure.clinicBranchId,
|
|
526
706
|
clinicInfo,
|
|
527
707
|
practitionerId: procedure.practitionerId,
|
|
@@ -529,13 +709,23 @@ export class BookingAdmin {
|
|
|
529
709
|
patientId: data.patientId,
|
|
530
710
|
patientInfo,
|
|
531
711
|
procedureId: data.procedureId,
|
|
532
|
-
procedureInfo
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
712
|
+
procedureInfo: this._generateProcedureSummaryInfo(
|
|
713
|
+
procedure,
|
|
714
|
+
clinicData,
|
|
715
|
+
practitionerData
|
|
716
|
+
),
|
|
717
|
+
procedureExtendedInfo: this._generateProcedureExtendedInfo(procedure),
|
|
718
|
+
status: initialAppointmentStatus,
|
|
719
|
+
bookingTime: new FirebaseClientTimestamp(
|
|
720
|
+
adminTsNow.seconds,
|
|
721
|
+
adminTsNow.nanoseconds
|
|
722
|
+
),
|
|
536
723
|
confirmationTime:
|
|
537
|
-
|
|
538
|
-
? (
|
|
724
|
+
initialAppointmentStatus === AppointmentStatus.CONFIRMED
|
|
725
|
+
? new FirebaseClientTimestamp(
|
|
726
|
+
adminTsNow.seconds,
|
|
727
|
+
adminTsNow.nanoseconds
|
|
728
|
+
)
|
|
539
729
|
: null,
|
|
540
730
|
appointmentStartTime: new FirebaseClientTimestamp(
|
|
541
731
|
data.appointmentStartTime.seconds,
|
|
@@ -553,14 +743,14 @@ export class BookingAdmin {
|
|
|
553
743
|
: PaymentStatus.NOT_APPLICABLE,
|
|
554
744
|
patientNotes: data.patientNotes || null,
|
|
555
745
|
blockingConditions: procedure.blockingConditions || [],
|
|
556
|
-
contraindications: procedure.contraindications || [],
|
|
746
|
+
contraindications: (procedure as any).contraindications || [],
|
|
557
747
|
preProcedureRequirements: procedure.preRequirements || [],
|
|
558
748
|
postProcedureRequirements: procedure.postRequirements || [],
|
|
559
|
-
pendingUserFormsIds:
|
|
749
|
+
pendingUserFormsIds: pendingUserFormTemplateIds,
|
|
750
|
+
linkedFormIds: allLinkedFormTemplateIds,
|
|
560
751
|
completedPreRequirements: [],
|
|
561
752
|
completedPostRequirements: [],
|
|
562
|
-
|
|
563
|
-
linkedForms: [],
|
|
753
|
+
linkedForms: initializedFormsInfo,
|
|
564
754
|
media: [],
|
|
565
755
|
reviewInfo: null,
|
|
566
756
|
finalizedDetails: undefined,
|
|
@@ -574,23 +764,34 @@ export class BookingAdmin {
|
|
|
574
764
|
isRecurring: false,
|
|
575
765
|
recurringAppointmentId: null,
|
|
576
766
|
isArchived: false,
|
|
577
|
-
createdAt:
|
|
578
|
-
|
|
767
|
+
createdAt: new FirebaseClientTimestamp(
|
|
768
|
+
adminTsNow.seconds,
|
|
769
|
+
adminTsNow.nanoseconds
|
|
770
|
+
),
|
|
771
|
+
updatedAt: new FirebaseClientTimestamp(
|
|
772
|
+
adminTsNow.seconds,
|
|
773
|
+
adminTsNow.nanoseconds
|
|
774
|
+
),
|
|
579
775
|
};
|
|
580
776
|
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
777
|
+
batch.set(
|
|
778
|
+
this.db.collection(APPOINTMENTS_COLLECTION).doc(newAppointmentId),
|
|
779
|
+
newAppointmentData
|
|
780
|
+
);
|
|
781
|
+
|
|
782
|
+
// Commit Batch
|
|
783
|
+
await batch.commit();
|
|
586
784
|
|
|
587
785
|
console.log(
|
|
588
|
-
`[BookingAdmin] Appointment ${newAppointmentId}
|
|
786
|
+
`[BookingAdmin] Appointment ${newAppointmentId} and associated calendar events created successfully.`
|
|
589
787
|
);
|
|
590
788
|
return {
|
|
591
789
|
success: true,
|
|
592
790
|
appointmentId: newAppointmentId,
|
|
593
791
|
appointmentData: newAppointmentData,
|
|
792
|
+
practitionerCalendarEventId,
|
|
793
|
+
patientCalendarEventId,
|
|
794
|
+
clinicCalendarEventId,
|
|
594
795
|
};
|
|
595
796
|
} catch (error) {
|
|
596
797
|
console.error(
|
|
@@ -604,4 +805,65 @@ export class BookingAdmin {
|
|
|
604
805
|
return { success: false, error: errorMessage };
|
|
605
806
|
}
|
|
606
807
|
}
|
|
808
|
+
|
|
809
|
+
private _generateProcedureSummaryInfo(
|
|
810
|
+
procedure: Procedure,
|
|
811
|
+
clinicData: Clinic,
|
|
812
|
+
practitionerData: Practitioner
|
|
813
|
+
): ProcedureSummaryInfo {
|
|
814
|
+
const procedureCategory = procedure.category as Category;
|
|
815
|
+
const procedureSubCategory = procedure.subcategory as Subcategory;
|
|
816
|
+
const procedureTechnology = procedure.technology as Technology;
|
|
817
|
+
const procedureProduct = procedure.product as Product;
|
|
818
|
+
return {
|
|
819
|
+
id: procedure.id,
|
|
820
|
+
name: procedure.name,
|
|
821
|
+
description: procedure.description,
|
|
822
|
+
family: procedure.family,
|
|
823
|
+
categoryName: procedureCategory?.name || "",
|
|
824
|
+
subcategoryName: procedureSubCategory?.name || "",
|
|
825
|
+
technologyName: procedureTechnology?.name || "",
|
|
826
|
+
price: procedure.price,
|
|
827
|
+
pricingMeasure: procedure.pricingMeasure,
|
|
828
|
+
currency: procedure.currency,
|
|
829
|
+
duration: procedure.duration,
|
|
830
|
+
clinicId: procedure.clinicBranchId,
|
|
831
|
+
clinicName: clinicData.name,
|
|
832
|
+
practitionerId: procedure.practitionerId,
|
|
833
|
+
practitionerName: `${practitionerData.basicInfo.firstName} ${practitionerData.basicInfo.lastName}`,
|
|
834
|
+
photo:
|
|
835
|
+
(procedureTechnology as any)?.photos?.[0]?.url ||
|
|
836
|
+
(procedureProduct as any)?.photos?.[0]?.url ||
|
|
837
|
+
"",
|
|
838
|
+
brandName: (procedureProduct as any)?.brand?.name || "",
|
|
839
|
+
productName: procedureProduct?.name || "",
|
|
840
|
+
};
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
private _generateProcedureExtendedInfo(
|
|
844
|
+
procedure: Procedure
|
|
845
|
+
): ProcedureExtendedInfo {
|
|
846
|
+
const procedureCategory = procedure.category as Category;
|
|
847
|
+
const procedureSubCategory = procedure.subcategory as Subcategory;
|
|
848
|
+
const procedureTechnology = procedure.technology as Technology;
|
|
849
|
+
const procedureProduct = procedure.product as Product;
|
|
850
|
+
return {
|
|
851
|
+
id: procedure.id,
|
|
852
|
+
name: procedure.name,
|
|
853
|
+
description: procedure.description,
|
|
854
|
+
cost: procedure.price,
|
|
855
|
+
duration: procedure.duration,
|
|
856
|
+
procedureFamily: procedure.family,
|
|
857
|
+
procedureCategoryId: procedureCategory?.id || "",
|
|
858
|
+
procedureCategoryName: procedureCategory?.name || "",
|
|
859
|
+
procedureSubCategoryId: procedureSubCategory?.id || "",
|
|
860
|
+
procedureSubCategoryName: procedureSubCategory?.name || "",
|
|
861
|
+
procedureTechnologyId: procedureTechnology?.id || "",
|
|
862
|
+
procedureTechnologyName: procedureTechnology?.name || "",
|
|
863
|
+
procedureProductBrandId: (procedureProduct as any)?.brand?.id || "",
|
|
864
|
+
procedureProductBrandName: (procedureProduct as any)?.brand?.name || "",
|
|
865
|
+
procedureProductId: procedureProduct?.id || "",
|
|
866
|
+
procedureProductName: procedureProduct?.name || "",
|
|
867
|
+
};
|
|
868
|
+
}
|
|
607
869
|
}
|