@blackcode_sa/metaestetics-api 1.12.25 → 1.12.27

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/index.js CHANGED
@@ -9405,7 +9405,7 @@ var ClinicService = class extends BaseService {
9405
9405
  this.clinicAdminService = clinicAdminService;
9406
9406
  this.clinicGroupService = clinicGroupService;
9407
9407
  this.mediaService = mediaService;
9408
- this.functions = (0, import_functions2.getFunctions)(app);
9408
+ this.functions = (0, import_functions2.getFunctions)(app, "europe-west6");
9409
9409
  }
9410
9410
  /**
9411
9411
  * Get timezone from coordinates using the callable function
@@ -9539,6 +9539,7 @@ var ClinicService = class extends BaseService {
9539
9539
  const location = validatedData.location;
9540
9540
  const hash = (0, import_geofire_common7.geohashForLocation)([location.latitude, location.longitude]);
9541
9541
  const tz = await this.getTimezone(location.latitude, location.longitude);
9542
+ console.log("\u{1F3E5} Clinic timezone:", tz);
9542
9543
  const defaultReviewInfo = {
9543
9544
  totalReviews: 0,
9544
9545
  averageRating: 0,
package/dist/index.mjs CHANGED
@@ -9510,7 +9510,7 @@ var ClinicService = class extends BaseService {
9510
9510
  this.clinicAdminService = clinicAdminService;
9511
9511
  this.clinicGroupService = clinicGroupService;
9512
9512
  this.mediaService = mediaService;
9513
- this.functions = getFunctions2(app);
9513
+ this.functions = getFunctions2(app, "europe-west6");
9514
9514
  }
9515
9515
  /**
9516
9516
  * Get timezone from coordinates using the callable function
@@ -9644,6 +9644,7 @@ var ClinicService = class extends BaseService {
9644
9644
  const location = validatedData.location;
9645
9645
  const hash = geohashForLocation4([location.latitude, location.longitude]);
9646
9646
  const tz = await this.getTimezone(location.latitude, location.longitude);
9647
+ console.log("\u{1F3E5} Clinic timezone:", tz);
9647
9648
  const defaultReviewInfo = {
9648
9649
  totalReviews: 0,
9649
9650
  averageRating: 0,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@blackcode_sa/metaestetics-api",
3
3
  "private": false,
4
- "version": "1.12.25",
4
+ "version": "1.12.27",
5
5
  "description": "Firebase authentication service with anonymous upgrade support",
6
6
  "main": "dist/index.js",
7
7
  "module": "dist/index.mjs",
@@ -339,22 +339,33 @@ export class BookingAdmin {
339
339
  endTime: end.toDate().toISOString(),
340
340
  });
341
341
 
342
+ const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1000;
343
+ const queryStart = admin.firestore.Timestamp.fromMillis(
344
+ start.toMillis() - MAX_EVENT_DURATION_MS
345
+ );
346
+
342
347
  const eventsRef = this.db
343
348
  .collection(`clinics/${clinicId}/calendar`)
344
- .where("eventTime.start", ">=", start)
345
- .where("eventTime.start", "<=", end);
349
+ .where("eventTime.start", ">=", queryStart)
350
+ .where("eventTime.start", "<", end)
351
+ .orderBy("eventTime.start");
346
352
 
347
353
  const snapshot = await eventsRef.get();
348
354
 
349
- const events = snapshot.docs.map((doc) => ({
350
- ...doc.data(),
351
- id: doc.id,
352
- }));
355
+ const events = snapshot.docs
356
+ .map((doc) => ({
357
+ ...doc.data(),
358
+ id: doc.id,
359
+ }))
360
+ .filter((event: any) => {
361
+ return event.eventTime.end.toMillis() > start.toMillis();
362
+ });
353
363
 
354
364
  Logger.debug("[BookingAdmin] Retrieved clinic calendar events", {
355
365
  clinicId,
356
366
  eventsCount: events.length,
357
367
  eventsTypes: this.summarizeEventTypes(events),
368
+ queryStartTime: queryStart.toDate().toISOString(),
358
369
  });
359
370
 
360
371
  return events;
@@ -392,22 +403,33 @@ export class BookingAdmin {
392
403
  endTime: end.toDate().toISOString(),
393
404
  });
394
405
 
406
+ const MAX_EVENT_DURATION_MS = 24 * 60 * 60 * 1000;
407
+ const queryStart = admin.firestore.Timestamp.fromMillis(
408
+ start.toMillis() - MAX_EVENT_DURATION_MS
409
+ );
410
+
395
411
  const eventsRef = this.db
396
412
  .collection(`practitioners/${practitionerId}/calendar`)
397
- .where("eventTime.start", ">=", start)
398
- .where("eventTime.start", "<=", end);
413
+ .where("eventTime.start", ">=", queryStart)
414
+ .where("eventTime.start", "<", end)
415
+ .orderBy("eventTime.start");
399
416
 
400
417
  const snapshot = await eventsRef.get();
401
418
 
402
- const events = snapshot.docs.map((doc) => ({
403
- ...doc.data(),
404
- id: doc.id,
405
- }));
419
+ const events = snapshot.docs
420
+ .map((doc) => ({
421
+ ...doc.data(),
422
+ id: doc.id,
423
+ }))
424
+ .filter((event: any) => {
425
+ return event.eventTime.end.toMillis() > start.toMillis();
426
+ });
406
427
 
407
428
  Logger.debug("[BookingAdmin] Retrieved practitioner calendar events", {
408
429
  practitionerId,
409
430
  eventsCount: events.length,
410
431
  eventsTypes: this.summarizeEventTypes(events),
432
+ queryStartTime: queryStart.toDate().toISOString(),
411
433
  });
412
434
 
413
435
  return events;
@@ -96,7 +96,8 @@ export class BookingAvailabilityCalculator {
96
96
  const availableSlots = this.generateAvailableSlots(
97
97
  availableIntervals,
98
98
  schedulingIntervalMinutes,
99
- procedureDurationMinutes
99
+ procedureDurationMinutes,
100
+ tz
100
101
  );
101
102
 
102
103
  return { availableSlots };
@@ -469,16 +470,18 @@ export class BookingAvailabilityCalculator {
469
470
  * @param intervals - Final available intervals
470
471
  * @param intervalMinutes - Scheduling interval in minutes
471
472
  * @param durationMinutes - Procedure duration in minutes
473
+ * @param tz - IANA timezone of the clinic
472
474
  * @returns Array of available booking slots
473
475
  */
474
476
  private static generateAvailableSlots(
475
477
  intervals: TimeInterval[],
476
478
  intervalMinutes: number,
477
- durationMinutes: number
479
+ durationMinutes: number,
480
+ tz: string
478
481
  ): AvailableSlot[] {
479
482
  const slots: AvailableSlot[] = [];
480
483
  console.log(
481
- `Generating slots with ${intervalMinutes}min intervals for ${durationMinutes}min procedure`
484
+ `Generating slots with ${intervalMinutes}min intervals for ${durationMinutes}min procedure in timezone ${tz}`
482
485
  );
483
486
 
484
487
  // Convert duration to milliseconds
@@ -492,8 +495,8 @@ export class BookingAvailabilityCalculator {
492
495
  const intervalStart = interval.start.toDate();
493
496
  const intervalEnd = interval.end.toDate();
494
497
 
495
- // Start at the beginning of the interval
496
- let slotStart = DateTime.fromJSDate(intervalStart);
498
+ // Start at the beginning of the interval IN CLINIC TIMEZONE
499
+ let slotStart = DateTime.fromMillis(intervalStart.getTime(), { zone: tz });
497
500
 
498
501
  // Adjust slotStart to the nearest interval boundary if needed
499
502
  const minutesIntoDay = slotStart.hour * 60 + slotStart.minute;
@@ -511,7 +514,7 @@ export class BookingAvailabilityCalculator {
511
514
  const slotEnd = slotStart.plus({ minutes: durationMinutes });
512
515
 
513
516
  // Check if this slot fits entirely within one of our available intervals
514
- if (this.isSlotFullyAvailable(slotStart, slotEnd, intervals)) {
517
+ if (this.isSlotFullyAvailable(slotStart, slotEnd, intervals, tz)) {
515
518
  slots.push({
516
519
  start: Timestamp.fromMillis(slotStart.toMillis()),
517
520
  });
@@ -532,17 +535,19 @@ export class BookingAvailabilityCalculator {
532
535
  * @param slotStart - Start time of the slot
533
536
  * @param slotEnd - End time of the slot
534
537
  * @param intervals - Available intervals
538
+ * @param tz - IANA timezone of the clinic
535
539
  * @returns True if the slot is fully contained within an available interval
536
540
  */
537
541
  private static isSlotFullyAvailable(
538
542
  slotStart: DateTime,
539
543
  slotEnd: DateTime,
540
- intervals: TimeInterval[]
544
+ intervals: TimeInterval[],
545
+ tz: string
541
546
  ): boolean {
542
547
  // Check if the slot is fully contained in any of the available intervals
543
548
  return intervals.some((interval) => {
544
- const intervalStart = DateTime.fromMillis(interval.start.toMillis());
545
- const intervalEnd = DateTime.fromMillis(interval.end.toMillis());
549
+ const intervalStart = DateTime.fromMillis(interval.start.toMillis(), { zone: tz });
550
+ const intervalEnd = DateTime.fromMillis(interval.end.toMillis(), { zone: tz });
546
551
 
547
552
  return slotStart >= intervalStart && slotEnd <= intervalEnd;
548
553
  });
@@ -0,0 +1,185 @@
1
+ ## Booking timezones and time types: current state, issues, and alignment plan
2
+
3
+ ### Scope and goal
4
+ This document explains how booking availability is computed across the admin layer and calculator, how time types and timezones are used today, where mismatches occur, and what to align to make results consistent in every environment and across DST.
5
+
6
+ Applies to:
7
+ - `Api/src/admin/booking/booking.admin.ts`
8
+ - `Api/src/admin/booking/booking.calculator.ts`
9
+ - `Api/src/admin/booking/booking.types.ts`
10
+
11
+ ### High-level flow (availability)
12
+ 1) `BookingAdmin.getAvailableBookingSlots`
13
+ - Accepts timeframe as `Date` or `admin.firestore.Timestamp` and normalizes to admin Timestamp.
14
+ - Loads `clinic`, `practitioner`, `procedure`.
15
+ - Fetches calendar events for clinic and practitioner within the timeframe using admin Timestamps.
16
+ - Converts all timestamps (timeframe and events) to client `firebase/firestore` `Timestamp` for the calculator via `TimestampUtils.adminToClient`.
17
+ - Passes clinic timezone `tz = clinic.location.tz` to the calculator.
18
+ - Calls `BookingAvailabilityCalculator.calculateSlots`.
19
+ - Converts resulting client `Timestamp`s back to admin Timestamp in the response.
20
+
21
+ 2) `BookingAvailabilityCalculator.calculateSlots`
22
+ - Uses client `Timestamp` + Luxon `DateTime`.
23
+ - Steps: apply clinic working hours → subtract clinic blocking events → apply practitioner working hours for the target clinic → subtract practitioner busy times → generate slots on a fixed interval grid.
24
+
25
+ 3) Types (`BookingAvailabilityRequest`)
26
+ - Requires that all time values be client `Timestamp` (from `firebase/firestore`).
27
+ - Admin layer converts before calling the calculator and converts back afterwards.
28
+
29
+ ### Time representations in play
30
+ - Admin/server: `admin.firestore.Timestamp` (backend)
31
+ - Client/runtime in calculator: `firebase/firestore` `Timestamp`
32
+ - Luxon `DateTime` for tz-aware computations
33
+ - String wall-clock specs in working hours, e.g. "HH:mm" for open/close/breaks
34
+ - JavaScript `Date` only used transiently at boundaries
35
+
36
+ ### Where timezone handling is correct
37
+ - Building per-day working-hour intervals (clinic and practitioner) uses:
38
+ - `DateTime.fromMillis(value, { zone: tz })` (avoids local-time reinterpretation)
39
+ - Explicit `tz` carried from `clinic.location.tz`
40
+
41
+ ### Where timezone context is dropped (root cause of shifts)
42
+ - Slot generation rounds and iterates using system-local timezone instead of clinic `tz`.
43
+ - Slot containment checks compare times constructed without explicit `tz`.
44
+ - Effects:
45
+ - Servers not in the clinic’s zone (e.g., UTC) will produce slots offset or misaligned to the expected clinic grid.
46
+ - DST boundaries can produce off-by-60-min effects and incorrect inclusion/exclusion of slots.
47
+
48
+ Problematic patterns to replace:
49
+ ```ts
50
+ // Uses system-local timezone implicitly
51
+ let slotStart = DateTime.fromJSDate(intervalStart);
52
+
53
+ // Also builds DateTimes without { zone: tz }
54
+ const intervalStart = DateTime.fromMillis(interval.start.toMillis());
55
+ const intervalEnd = DateTime.fromMillis(interval.end.toMillis());
56
+ ```
57
+
58
+ Target pattern:
59
+ ```ts
60
+ // Always specify the clinic timezone
61
+ let slotStart = DateTime.fromMillis(intervalStartMillis, { zone: tz });
62
+ const intervalStart = DateTime.fromMillis(interval.start.toMillis(), { zone: tz });
63
+ const intervalEnd = DateTime.fromMillis(interval.end.toMillis(), { zone: tz });
64
+ ```
65
+
66
+ ### Event retrieval misses overlapping events
67
+ - Current queries fetch events with `eventTime.start` within `[timeframe.start, timeframe.end]` only.
68
+ - Events that start before the window but overlap into it (or extend beyond it) are omitted, so busy time subtraction can miss conflicts.
69
+
70
+ Correct overlapping logic should include events where:
71
+ - `eventTime.start < timeframe.end` AND `eventTime.end > timeframe.start`
72
+
73
+ Firestore considerations:
74
+ - Firestore cannot do range filters on two different fields in a single query without workarounds. Practical options:
75
+ - Run two queries and union results, or
76
+ - Add a single-field index (e.g., duplicated fields like `startAt` and `endAt`) and leverage composite queries appropriately, or
77
+ - Query the broader of the two constraints and post-filter in memory. De-duplicate by `id`.
78
+
79
+ ### Appointment creation normalization
80
+ - `orchestrateAppointmentCreation` writes calendar events with `eventTime` taken directly from input admin Timestamps.
81
+ - If the client produced those Timestamps by converting wall-clock times in a different timezone than the clinic, users will observe unexpected local renderings relative to clinic working hours.
82
+
83
+ Alignment expectation:
84
+ - UI should interpret user-picked wall-clock times in the clinic’s `tz`, convert once to UTC epoch, and send as Timestamp.
85
+ - Backend stores the UTC epoch as-is; all display/logic that needs wall-clock context must apply the clinic `tz` explicitly.
86
+
87
+ ### Alignment decisions (non-code policy)
88
+ 1) Single invariant for the calculator
89
+ - Inputs are client `Timestamp`s (UTC epoch) plus explicit `tz`.
90
+ - Every Luxon `DateTime` must be created with `{ zone: tz }`.
91
+ - Prefer `DateTime.fromMillis(...)` over `fromJSDate(...)`.
92
+
93
+ 2) Slot generation/containment
94
+ - `generateAvailableSlots` uses `tz` when rounding to interval grid and when iterating.
95
+ - `isSlotFullyAvailable` constructs interval boundaries with `{ zone: tz }`.
96
+
97
+ 3) Event retrieval strategy
98
+ - For timeframe `[S, E]`, include events where `start < E` and `end > S`.
99
+ - Implement via union of queries or data model support; post-filter and de-dup in memory if needed.
100
+
101
+ 4) Conversion boundaries
102
+ - Admin layer converts admin → client Timestamps only at the calculator boundary and client → admin at the response boundary.
103
+ - Do not mix admin/client Timestamp types in a single object passed to the calculator.
104
+
105
+ 5) UI and API contract
106
+ - UI times are wall-clock in clinic `tz`, converted once to UTC Timestamp before sending.
107
+ - Backend accepts/returns admin Timestamps on API, but calculator-only paths use client Timestamps internally.
108
+
109
+ ### Testing matrix (must pass)
110
+ - Timezone variance:
111
+ - Clinics in multiple IANA zones; server in UTC and in a non-UTC zone.
112
+ - DST boundaries:
113
+ - Days that enter/exit DST in clinic `tz`.
114
+ - Timeframe edges:
115
+ - Windows that straddle midnight in clinic `tz`.
116
+ - Very short windows (e.g., ≤ duration) and long windows (multi-day).
117
+ - Event overlap cases:
118
+ - Events starting before S and ending between S..E.
119
+ - Events starting between S..E and ending after E.
120
+ - Long events fully covering S..E.
121
+ - Grid checks:
122
+ - Interval sizes that don’t divide 60 (e.g., 20 min), and variable procedure durations.
123
+
124
+ ### Actionable checklist
125
+ - ✅ Make all DateTime constructions in slot generation and containment checks use `{ zone: tz }`.
126
+ - ✅ Replace `fromJSDate` with `fromMillis` in calculator paths.
127
+ - ✅ Update event fetching to include overlaps with the timeframe; union queries or adjust model.
128
+ - ⏳ Re-assert the type contract: calculator receives only client `Timestamp` + `tz`.
129
+ - ⏳ Document UI responsibility to convert wall-clock (clinic `tz`) → UTC Timestamp exactly once.
130
+
131
+ ### PHASE 1 COMPLETED: Backend Calculator Fixes ✅
132
+
133
+ **Date Completed:** October 1, 2025
134
+
135
+ **Changes Made:**
136
+
137
+ 1. **booking.calculator.ts - generateAvailableSlots()**
138
+ - Added `tz: string` parameter
139
+ - Changed `DateTime.fromJSDate(intervalStart)` → `DateTime.fromMillis(intervalStart.getTime(), { zone: tz })`
140
+ - Now explicitly creates DateTime in clinic timezone for all slot calculations
141
+
142
+ 2. **booking.calculator.ts - isSlotFullyAvailable()**
143
+ - Added `tz: string` parameter
144
+ - Changed `DateTime.fromMillis(interval.start.toMillis())` → `DateTime.fromMillis(interval.start.toMillis(), { zone: tz })`
145
+ - Interval boundary checks now use clinic timezone context
146
+
147
+ 3. **booking.calculator.ts - calculateSlots()**
148
+ - Updated call to `generateAvailableSlots()` to pass `tz` parameter
149
+ - Updated call to `isSlotFullyAvailable()` to pass `tz` parameter
150
+
151
+ 4. **booking.admin.ts - getClinicCalendarEvents()**
152
+ - Fixed event overlap logic with bounded query
153
+ - Added lower bound: `queryStart = start - 24 hours` to prevent querying all historical events
154
+ - Query: `eventTime.start >= queryStart AND eventTime.start < end`
155
+ - Added post-filter: `eventTime.end > start` to catch all overlapping events
156
+ - Prevents missing events that start before window but overlap into it
157
+ - Performance optimized: only queries ~24-48 hours of events instead of entire history
158
+
159
+ 5. **booking.admin.ts - getPractitionerCalendarEvents()**
160
+ - Applied same overlap fix with 24-hour lookback window
161
+ - Ensures busy time subtraction includes all conflicting events
162
+ - Efficient: assumes no appointments longer than 24 hours
163
+
164
+ **Impact:**
165
+ - Slot generation now correctly happens in clinic timezone
166
+ - Slots are properly converted to UTC for storage/transmission
167
+ - Event blocking now catches all overlapping events, not just those starting within window
168
+ - Fixes timezone display issues for users in different timezones
169
+
170
+ **Next Steps:**
171
+ - Phase 2: Mobile app fixes (use original UTC timestamp from slots)
172
+ - Phase 3: ClinicApp fixes (same as Mobile)
173
+ - Phase 4: Testing across multiple timezones and DST boundaries
174
+
175
+ ### Known risks
176
+ - DST transitions can produce days with 23/25 hours; rounding/iteration must not assume 24h.
177
+ - Post-filtering events after union queries can be memory-intensive for very large windows; constrain timeframe appropriately.
178
+
179
+ ### Quick glossary
180
+ - Admin Timestamp: `admin.firestore.Timestamp` (backend SDK)
181
+ - Client Timestamp: `firebase/firestore` `Timestamp` (web SDK)
182
+ - `tz`: Clinic’s IANA timezone string, e.g., `Europe/Belgrade`
183
+ - Luxon `DateTime`: tz-aware date-time object used for calendar math
184
+
185
+
@@ -78,7 +78,7 @@ export class ClinicService extends BaseService {
78
78
  this.clinicAdminService = clinicAdminService;
79
79
  this.clinicGroupService = clinicGroupService;
80
80
  this.mediaService = mediaService;
81
- this.functions = getFunctions(app);
81
+ this.functions = getFunctions(app, "europe-west6"); // All functions now in europe-west6
82
82
  }
83
83
 
84
84
  /**
@@ -250,7 +250,7 @@ export class ClinicService extends BaseService {
250
250
  const location = validatedData.location;
251
251
  const hash = geohashForLocation([location.latitude, location.longitude]);
252
252
  const tz = await this.getTimezone(location.latitude, location.longitude);
253
-
253
+ console.log("🏥 Clinic timezone:", tz);
254
254
  const defaultReviewInfo: ClinicReviewInfo = {
255
255
  totalReviews: 0,
256
256
  averageRating: 0,