@blackcode_sa/metaestetics-api 1.12.68 → 1.13.0

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.
Files changed (39) hide show
  1. package/dist/admin/index.d.mts +801 -2
  2. package/dist/admin/index.d.ts +801 -2
  3. package/dist/admin/index.js +2332 -153
  4. package/dist/admin/index.mjs +2321 -153
  5. package/dist/index.d.mts +1057 -2
  6. package/dist/index.d.ts +1057 -2
  7. package/dist/index.js +4150 -2117
  8. package/dist/index.mjs +3832 -1810
  9. package/package.json +1 -1
  10. package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +140 -0
  11. package/src/admin/analytics/analytics.admin.service.ts +278 -0
  12. package/src/admin/analytics/index.ts +2 -0
  13. package/src/admin/index.ts +6 -0
  14. package/src/backoffice/services/README.md +17 -0
  15. package/src/backoffice/services/analytics.service.proposal.md +863 -0
  16. package/src/backoffice/services/analytics.service.summary.md +143 -0
  17. package/src/services/analytics/ARCHITECTURE.md +199 -0
  18. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -0
  19. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -0
  20. package/src/services/analytics/QUICK_START.md +393 -0
  21. package/src/services/analytics/README.md +287 -0
  22. package/src/services/analytics/SUMMARY.md +141 -0
  23. package/src/services/analytics/USAGE_GUIDE.md +518 -0
  24. package/src/services/analytics/analytics-cloud.service.ts +222 -0
  25. package/src/services/analytics/analytics.service.ts +1632 -0
  26. package/src/services/analytics/index.ts +3 -0
  27. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -0
  28. package/src/services/analytics/utils/cost-calculation.utils.ts +154 -0
  29. package/src/services/analytics/utils/grouping.utils.ts +394 -0
  30. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -0
  31. package/src/services/analytics/utils/time-calculation.utils.ts +186 -0
  32. package/src/services/appointment/appointment.service.ts +50 -6
  33. package/src/services/index.ts +1 -0
  34. package/src/types/analytics/analytics.types.ts +500 -0
  35. package/src/types/analytics/grouped-analytics.types.ts +148 -0
  36. package/src/types/analytics/index.ts +4 -0
  37. package/src/types/analytics/stored-analytics.types.ts +137 -0
  38. package/src/types/index.ts +3 -0
  39. package/src/types/notifications/index.ts +21 -0
@@ -0,0 +1,3 @@
1
+ export * from './analytics.service';
2
+ export * from './analytics-cloud.service';
3
+
@@ -0,0 +1,138 @@
1
+ import { Appointment, AppointmentStatus } from '../../../types/appointment';
2
+ import { AnalyticsDateRange, AnalyticsFilters } from '../../../types/analytics';
3
+
4
+ /**
5
+ * Filters appointments by date range
6
+ *
7
+ * @param appointments - Array of appointments
8
+ * @param dateRange - Date range filter
9
+ * @returns Filtered appointments
10
+ */
11
+ export function filterByDateRange(
12
+ appointments: Appointment[],
13
+ dateRange?: AnalyticsDateRange,
14
+ ): Appointment[] {
15
+ if (!dateRange) {
16
+ return appointments;
17
+ }
18
+
19
+ const startTime = dateRange.start.getTime();
20
+ const endTime = dateRange.end.getTime();
21
+
22
+ return appointments.filter(appointment => {
23
+ const appointmentTime = appointment.appointmentStartTime.toMillis();
24
+ return appointmentTime >= startTime && appointmentTime <= endTime;
25
+ });
26
+ }
27
+
28
+ /**
29
+ * Filters appointments by various criteria
30
+ *
31
+ * @param appointments - Array of appointments
32
+ * @param filters - Filter criteria
33
+ * @returns Filtered appointments
34
+ */
35
+ export function filterAppointments(
36
+ appointments: Appointment[],
37
+ filters?: AnalyticsFilters,
38
+ ): Appointment[] {
39
+ if (!filters) {
40
+ return appointments;
41
+ }
42
+
43
+ return appointments.filter(appointment => {
44
+ if (filters.clinicBranchId && appointment.clinicBranchId !== filters.clinicBranchId) {
45
+ return false;
46
+ }
47
+ if (filters.practitionerId && appointment.practitionerId !== filters.practitionerId) {
48
+ return false;
49
+ }
50
+ if (filters.procedureId && appointment.procedureId !== filters.procedureId) {
51
+ return false;
52
+ }
53
+ if (filters.patientId && appointment.patientId !== filters.patientId) {
54
+ return false;
55
+ }
56
+ return true;
57
+ });
58
+ }
59
+
60
+ /**
61
+ * Filters appointments by status
62
+ *
63
+ * @param appointments - Array of appointments
64
+ * @param statuses - Array of statuses to include
65
+ * @returns Filtered appointments
66
+ */
67
+ export function filterByStatus(
68
+ appointments: Appointment[],
69
+ statuses: AppointmentStatus[],
70
+ ): Appointment[] {
71
+ return appointments.filter(appointment => statuses.includes(appointment.status));
72
+ }
73
+
74
+ /**
75
+ * Gets completed appointments (status = COMPLETED)
76
+ *
77
+ * @param appointments - Array of appointments
78
+ * @returns Completed appointments
79
+ */
80
+ export function getCompletedAppointments(appointments: Appointment[]): Appointment[] {
81
+ return filterByStatus(appointments, [AppointmentStatus.COMPLETED]);
82
+ }
83
+
84
+ /**
85
+ * Gets canceled appointments (all cancellation statuses)
86
+ *
87
+ * @param appointments - Array of appointments
88
+ * @returns Canceled appointments
89
+ */
90
+ export function getCanceledAppointments(appointments: Appointment[]): Appointment[] {
91
+ return filterByStatus(appointments, [
92
+ AppointmentStatus.CANCELED_PATIENT,
93
+ AppointmentStatus.CANCELED_CLINIC,
94
+ AppointmentStatus.CANCELED_PATIENT_RESCHEDULED,
95
+ ]);
96
+ }
97
+
98
+ /**
99
+ * Gets no-show appointments
100
+ *
101
+ * @param appointments - Array of appointments
102
+ * @returns No-show appointments
103
+ */
104
+ export function getNoShowAppointments(appointments: Appointment[]): Appointment[] {
105
+ return filterByStatus(appointments, [AppointmentStatus.NO_SHOW]);
106
+ }
107
+
108
+ /**
109
+ * Gets active appointments (not canceled or no-show)
110
+ *
111
+ * @param appointments - Array of appointments
112
+ * @returns Active appointments
113
+ */
114
+ export function getActiveAppointments(appointments: Appointment[]): Appointment[] {
115
+ const inactiveStatuses = [
116
+ AppointmentStatus.CANCELED_PATIENT,
117
+ AppointmentStatus.CANCELED_CLINIC,
118
+ AppointmentStatus.CANCELED_PATIENT_RESCHEDULED,
119
+ AppointmentStatus.NO_SHOW,
120
+ ];
121
+
122
+ return appointments.filter(appointment => !inactiveStatuses.includes(appointment.status));
123
+ }
124
+
125
+ /**
126
+ * Calculates percentage
127
+ *
128
+ * @param part - Part value
129
+ * @param total - Total value
130
+ * @returns Percentage (0-100)
131
+ */
132
+ export function calculatePercentage(part: number, total: number): number {
133
+ if (total === 0) {
134
+ return 0;
135
+ }
136
+ return Math.round((part / total) * 100 * 100) / 100;
137
+ }
138
+
@@ -0,0 +1,154 @@
1
+ import { Appointment, AppointmentMetadata, FinalBilling, ZoneItemData } from '../../../types/appointment';
2
+
3
+ /**
4
+ * Calculates the total cost from an appointment's metadata
5
+ * Priority: finalbilling.finalPrice > zonesData subtotals > appointment.cost
6
+ *
7
+ * @param appointment - The appointment to calculate cost for
8
+ * @returns Object with cost, currency, and calculation source
9
+ */
10
+ export function calculateAppointmentCost(appointment: Appointment): {
11
+ cost: number;
12
+ currency: string;
13
+ source: 'finalbilling' | 'zonesData' | 'baseCost';
14
+ subtotal?: number;
15
+ tax?: number;
16
+ } {
17
+ const metadata = appointment.metadata;
18
+ const currency = appointment.currency || 'CHF';
19
+
20
+ // Priority 1: Use finalbilling if available
21
+ if (metadata?.finalbilling) {
22
+ const finalbilling = metadata.finalbilling as FinalBilling;
23
+ return {
24
+ cost: finalbilling.finalPrice,
25
+ currency: finalbilling.currency || currency,
26
+ source: 'finalbilling',
27
+ subtotal: finalbilling.subtotalAll,
28
+ tax: finalbilling.taxPrice,
29
+ };
30
+ }
31
+
32
+ // Priority 2: Calculate from zonesData
33
+ if (metadata?.zonesData) {
34
+ const zonesData = metadata.zonesData as Record<string, ZoneItemData[]>;
35
+ let subtotal = 0;
36
+ let foundCurrency = currency;
37
+
38
+ Object.values(zonesData).forEach(items => {
39
+ items.forEach(item => {
40
+ if (item.type === 'item' && item.subtotal) {
41
+ subtotal += item.subtotal;
42
+ if (item.currency && !foundCurrency) {
43
+ foundCurrency = item.currency;
44
+ }
45
+ }
46
+ });
47
+ });
48
+
49
+ if (subtotal > 0) {
50
+ return {
51
+ cost: subtotal, // Note: This doesn't include tax, but zonesData might not have tax info
52
+ currency: foundCurrency,
53
+ source: 'zonesData',
54
+ subtotal,
55
+ };
56
+ }
57
+ }
58
+
59
+ // Priority 3: Fallback to base appointment cost
60
+ return {
61
+ cost: appointment.cost || 0,
62
+ currency,
63
+ source: 'baseCost',
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Calculates total revenue from an array of appointments
69
+ *
70
+ * @param appointments - Array of appointments
71
+ * @returns Total revenue and currency
72
+ */
73
+ export function calculateTotalRevenue(appointments: Appointment[]): {
74
+ totalRevenue: number;
75
+ currency: string;
76
+ } {
77
+ if (appointments.length === 0) {
78
+ return { totalRevenue: 0, currency: 'CHF' };
79
+ }
80
+
81
+ let totalRevenue = 0;
82
+ const currencies = new Set<string>();
83
+
84
+ appointments.forEach(appointment => {
85
+ const costData = calculateAppointmentCost(appointment);
86
+ totalRevenue += costData.cost;
87
+ currencies.add(costData.currency);
88
+ });
89
+
90
+ // Use the most common currency, or first one found
91
+ const currency = currencies.size > 0 ? Array.from(currencies)[0] : 'CHF';
92
+
93
+ return { totalRevenue, currency };
94
+ }
95
+
96
+ /**
97
+ * Extracts product usage from appointment metadata
98
+ *
99
+ * @param appointment - The appointment to extract products from
100
+ * @returns Array of product usage data
101
+ */
102
+ export function extractProductUsage(appointment: Appointment): Array<{
103
+ productId: string;
104
+ productName: string;
105
+ brandId: string;
106
+ brandName: string;
107
+ quantity: number;
108
+ price: number;
109
+ subtotal: number;
110
+ currency: string;
111
+ }> {
112
+ const products: Array<{
113
+ productId: string;
114
+ productName: string;
115
+ brandId: string;
116
+ brandName: string;
117
+ quantity: number;
118
+ price: number;
119
+ subtotal: number;
120
+ currency: string;
121
+ }> = [];
122
+
123
+ const metadata = appointment.metadata;
124
+ if (!metadata?.zonesData) {
125
+ return products;
126
+ }
127
+
128
+ const zonesData = metadata.zonesData as Record<string, ZoneItemData[]>;
129
+ const currency = appointment.currency || 'CHF';
130
+
131
+ Object.values(zonesData).forEach(items => {
132
+ items.forEach(item => {
133
+ if (item.type === 'item' && item.productId) {
134
+ const price = item.priceOverrideAmount || item.price || 0;
135
+ const quantity = item.quantity || 1;
136
+ const subtotal = item.subtotal || price * quantity;
137
+
138
+ products.push({
139
+ productId: item.productId,
140
+ productName: item.productName || 'Unknown Product',
141
+ brandId: item.productBrandId || '',
142
+ brandName: item.productBrandName || '',
143
+ quantity,
144
+ price,
145
+ subtotal,
146
+ currency: item.currency || currency,
147
+ });
148
+ }
149
+ });
150
+ });
151
+
152
+ return products;
153
+ }
154
+
@@ -0,0 +1,394 @@
1
+ import { Appointment, AppointmentStatus } from '../../../types/appointment';
2
+ import { EntityType } from '../../../types/analytics';
3
+ import {
4
+ GroupedRevenueMetrics,
5
+ GroupedProductUsageMetrics,
6
+ GroupedTimeEfficiencyMetrics,
7
+ GroupedPatientBehaviorMetrics,
8
+ } from '../../../types/analytics/grouped-analytics.types';
9
+ import { calculateAppointmentCost, extractProductUsage, calculateTotalRevenue } from './cost-calculation.utils';
10
+ import { calculateTimeEfficiency, calculateAverageTimeMetrics } from './time-calculation.utils';
11
+ import { getCompletedAppointments, getCanceledAppointments, getNoShowAppointments, calculatePercentage } from './appointment-filtering.utils';
12
+
13
+ /**
14
+ * Helper to get technology ID from appointment
15
+ */
16
+ function getTechnologyId(appointment: Appointment): string {
17
+ return (
18
+ appointment.procedureExtendedInfo?.procedureTechnologyId || 'unknown-technology'
19
+ );
20
+ }
21
+
22
+ /**
23
+ * Helper to get technology name from appointment
24
+ */
25
+ function getTechnologyName(appointment: Appointment): string {
26
+ return (
27
+ appointment.procedureExtendedInfo?.procedureTechnologyName ||
28
+ appointment.procedureInfo?.technologyName ||
29
+ 'Unknown'
30
+ );
31
+ }
32
+
33
+ /**
34
+ * Helper to get entity name from appointment
35
+ */
36
+ function getEntityName(appointment: Appointment, entityType: EntityType): string {
37
+ switch (entityType) {
38
+ case 'clinic':
39
+ return appointment.clinicInfo?.name || 'Unknown';
40
+ case 'practitioner':
41
+ return appointment.practitionerInfo?.name || 'Unknown';
42
+ case 'patient':
43
+ return appointment.patientInfo?.fullName || 'Unknown';
44
+ case 'procedure':
45
+ return appointment.procedureInfo?.name || 'Unknown';
46
+ case 'technology':
47
+ return appointment.procedureExtendedInfo?.procedureTechnologyName ||
48
+ appointment.procedureInfo?.technologyName ||
49
+ 'Unknown';
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Helper to get entity ID from appointment
55
+ */
56
+ function getEntityId(appointment: Appointment, entityType: EntityType): string {
57
+ switch (entityType) {
58
+ case 'clinic':
59
+ return appointment.clinicBranchId;
60
+ case 'practitioner':
61
+ return appointment.practitionerId;
62
+ case 'patient':
63
+ return appointment.patientId;
64
+ case 'procedure':
65
+ return appointment.procedureId;
66
+ case 'technology':
67
+ return appointment.procedureExtendedInfo?.procedureTechnologyId ||
68
+ 'unknown-technology';
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Groups appointments by entity type
74
+ */
75
+ export function groupAppointmentsByEntity(
76
+ appointments: Appointment[],
77
+ entityType: EntityType,
78
+ ): Map<string, { name: string; appointments: Appointment[] }> {
79
+ const entityMap = new Map<string, { name: string; appointments: Appointment[] }>();
80
+
81
+ appointments.forEach(appointment => {
82
+ let entityId: string;
83
+ let entityName: string;
84
+
85
+ if (entityType === 'technology') {
86
+ entityId = getTechnologyId(appointment);
87
+ entityName = getTechnologyName(appointment);
88
+ } else {
89
+ entityId = getEntityId(appointment, entityType);
90
+ entityName = getEntityName(appointment, entityType);
91
+ }
92
+
93
+ if (!entityMap.has(entityId)) {
94
+ entityMap.set(entityId, { name: entityName, appointments: [] });
95
+ }
96
+ entityMap.get(entityId)!.appointments.push(appointment);
97
+ });
98
+
99
+ return entityMap;
100
+ }
101
+
102
+ /**
103
+ * Calculates grouped revenue metrics
104
+ */
105
+ export function calculateGroupedRevenueMetrics(
106
+ appointments: Appointment[],
107
+ entityType: EntityType,
108
+ ): GroupedRevenueMetrics[] {
109
+ const entityMap = groupAppointmentsByEntity(appointments, entityType);
110
+ const completed = getCompletedAppointments(appointments);
111
+
112
+ return Array.from(entityMap.entries()).map(([entityId, data]) => {
113
+ const entityAppointments = data.appointments;
114
+ const entityCompleted = entityAppointments.filter(a =>
115
+ completed.some(c => c.id === a.id),
116
+ );
117
+
118
+ const { totalRevenue, currency } = calculateTotalRevenue(entityCompleted);
119
+
120
+ // Calculate tax and subtotal
121
+ let totalTax = 0;
122
+ let totalSubtotal = 0;
123
+ let unpaidRevenue = 0;
124
+ let refundedRevenue = 0;
125
+
126
+ entityCompleted.forEach(appointment => {
127
+ const costData = calculateAppointmentCost(appointment);
128
+ if (costData.source === 'finalbilling') {
129
+ totalTax += costData.tax || 0;
130
+ totalSubtotal += costData.subtotal || 0;
131
+ } else {
132
+ totalSubtotal += costData.cost;
133
+ }
134
+
135
+ if (appointment.paymentStatus === 'unpaid') {
136
+ unpaidRevenue += costData.cost;
137
+ } else if (appointment.paymentStatus === 'refunded') {
138
+ refundedRevenue += costData.cost;
139
+ }
140
+ });
141
+
142
+ return {
143
+ entityId,
144
+ entityName: data.name,
145
+ entityType,
146
+ totalRevenue,
147
+ averageRevenuePerAppointment:
148
+ entityCompleted.length > 0 ? totalRevenue / entityCompleted.length : 0,
149
+ totalAppointments: entityAppointments.length,
150
+ completedAppointments: entityCompleted.length,
151
+ currency,
152
+ unpaidRevenue,
153
+ refundedRevenue,
154
+ totalTax,
155
+ totalSubtotal,
156
+ };
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Calculates grouped product usage metrics
162
+ */
163
+ export function calculateGroupedProductUsageMetrics(
164
+ appointments: Appointment[],
165
+ entityType: EntityType,
166
+ ): GroupedProductUsageMetrics[] {
167
+ const entityMap = groupAppointmentsByEntity(appointments, entityType);
168
+ const completed = getCompletedAppointments(appointments);
169
+
170
+ return Array.from(entityMap.entries()).map(([entityId, data]) => {
171
+ const entityAppointments = data.appointments;
172
+ const entityCompleted = entityAppointments.filter(a =>
173
+ completed.some(c => c.id === a.id),
174
+ );
175
+
176
+ // Extract all products from completed appointments
177
+ const productMap = new Map<
178
+ string,
179
+ {
180
+ name: string;
181
+ brandName: string;
182
+ quantity: number;
183
+ revenue: number;
184
+ usageCount: number;
185
+ }
186
+ >();
187
+
188
+ entityCompleted.forEach(appointment => {
189
+ const products = extractProductUsage(appointment);
190
+ products.forEach(product => {
191
+ if (productMap.has(product.productId)) {
192
+ const existing = productMap.get(product.productId)!;
193
+ existing.quantity += product.quantity;
194
+ existing.revenue += product.subtotal;
195
+ existing.usageCount++;
196
+ } else {
197
+ productMap.set(product.productId, {
198
+ name: product.productName,
199
+ brandName: product.brandName,
200
+ quantity: product.quantity,
201
+ revenue: product.subtotal,
202
+ usageCount: 1,
203
+ });
204
+ }
205
+ });
206
+ });
207
+
208
+ const topProducts = Array.from(productMap.entries())
209
+ .map(([productId, productData]) => ({
210
+ productId,
211
+ productName: productData.name,
212
+ brandName: productData.brandName,
213
+ totalQuantity: productData.quantity,
214
+ totalRevenue: productData.revenue,
215
+ usageCount: productData.usageCount,
216
+ }))
217
+ .sort((a, b) => b.totalRevenue - a.totalRevenue)
218
+ .slice(0, 10);
219
+
220
+ const totalProductRevenue = topProducts.reduce((sum, p) => sum + p.totalRevenue, 0);
221
+ const totalProductQuantity = topProducts.reduce((sum, p) => sum + p.totalQuantity, 0);
222
+
223
+ return {
224
+ entityId,
225
+ entityName: data.name,
226
+ entityType,
227
+ totalProductsUsed: productMap.size,
228
+ uniqueProducts: productMap.size,
229
+ totalProductRevenue,
230
+ totalProductQuantity,
231
+ averageProductsPerAppointment:
232
+ entityCompleted.length > 0 ? productMap.size / entityCompleted.length : 0,
233
+ topProducts,
234
+ };
235
+ });
236
+ }
237
+
238
+ /**
239
+ * Calculates grouped time efficiency metrics
240
+ */
241
+ export function calculateGroupedTimeEfficiencyMetrics(
242
+ appointments: Appointment[],
243
+ entityType: EntityType,
244
+ ): GroupedTimeEfficiencyMetrics[] {
245
+ const entityMap = groupAppointmentsByEntity(appointments, entityType);
246
+ const completed = getCompletedAppointments(appointments);
247
+
248
+ return Array.from(entityMap.entries()).map(([entityId, data]) => {
249
+ const entityAppointments = data.appointments;
250
+ const entityCompleted = entityAppointments.filter(a =>
251
+ completed.some(c => c.id === a.id),
252
+ );
253
+
254
+ const timeMetrics = calculateAverageTimeMetrics(entityCompleted);
255
+
256
+ return {
257
+ entityId,
258
+ entityName: data.name,
259
+ entityType,
260
+ totalAppointments: entityCompleted.length,
261
+ appointmentsWithActualTime: timeMetrics.appointmentsWithActualTime,
262
+ averageBookedDuration: timeMetrics.averageBookedDuration,
263
+ averageActualDuration: timeMetrics.averageActualDuration,
264
+ averageEfficiency: timeMetrics.averageEfficiency,
265
+ totalOverrun: timeMetrics.totalOverrun,
266
+ totalUnderutilization: timeMetrics.totalUnderutilization,
267
+ averageOverrun: timeMetrics.averageOverrun,
268
+ averageUnderutilization: timeMetrics.averageUnderutilization,
269
+ };
270
+ });
271
+ }
272
+
273
+ /**
274
+ * Calculates grouped patient behavior metrics
275
+ */
276
+ export function calculateGroupedPatientBehaviorMetrics(
277
+ appointments: Appointment[],
278
+ entityType: EntityType,
279
+ ): GroupedPatientBehaviorMetrics[] {
280
+ const entityMap = groupAppointmentsByEntity(appointments, entityType);
281
+ const canceled = getCanceledAppointments(appointments);
282
+ const noShow = getNoShowAppointments(appointments);
283
+
284
+ return Array.from(entityMap.entries()).map(([entityId, data]) => {
285
+ const entityAppointments = data.appointments;
286
+
287
+ // Group by patient to analyze behavior
288
+ const patientMap = new Map<
289
+ string,
290
+ {
291
+ name: string;
292
+ appointments: Appointment[];
293
+ noShows: Appointment[];
294
+ cancellations: Appointment[];
295
+ }
296
+ >();
297
+
298
+ entityAppointments.forEach(appointment => {
299
+ const patientId = appointment.patientId;
300
+ const patientName = appointment.patientInfo?.fullName || 'Unknown';
301
+
302
+ if (!patientMap.has(patientId)) {
303
+ patientMap.set(patientId, {
304
+ name: patientName,
305
+ appointments: [],
306
+ noShows: [],
307
+ cancellations: [],
308
+ });
309
+ }
310
+
311
+ const patientData = patientMap.get(patientId)!;
312
+ patientData.appointments.push(appointment);
313
+
314
+ if (noShow.some(ns => ns.id === appointment.id)) {
315
+ patientData.noShows.push(appointment);
316
+ }
317
+ if (canceled.some(c => c.id === appointment.id)) {
318
+ patientData.cancellations.push(appointment);
319
+ }
320
+ });
321
+
322
+ // Calculate patient-level metrics
323
+ const patientMetrics = Array.from(patientMap.entries()).map(([patientId, patientData]) => ({
324
+ patientId,
325
+ patientName: patientData.name,
326
+ noShowCount: patientData.noShows.length,
327
+ cancellationCount: patientData.cancellations.length,
328
+ totalAppointments: patientData.appointments.length,
329
+ noShowRate: calculatePercentage(
330
+ patientData.noShows.length,
331
+ patientData.appointments.length,
332
+ ),
333
+ cancellationRate: calculatePercentage(
334
+ patientData.cancellations.length,
335
+ patientData.appointments.length,
336
+ ),
337
+ }));
338
+
339
+ const patientsWithNoShows = patientMetrics.filter(p => p.noShowCount > 0).length;
340
+ const patientsWithCancellations = patientMetrics.filter(p => p.cancellationCount > 0).length;
341
+
342
+ const averageNoShowRate =
343
+ patientMetrics.length > 0
344
+ ? patientMetrics.reduce((sum, p) => sum + p.noShowRate, 0) / patientMetrics.length
345
+ : 0;
346
+
347
+ const averageCancellationRate =
348
+ patientMetrics.length > 0
349
+ ? patientMetrics.reduce((sum, p) => sum + p.cancellationRate, 0) / patientMetrics.length
350
+ : 0;
351
+
352
+ const topNoShowPatients = patientMetrics
353
+ .filter(p => p.noShowCount > 0)
354
+ .sort((a, b) => b.noShowRate - a.noShowRate)
355
+ .slice(0, 10)
356
+ .map(p => ({
357
+ patientId: p.patientId,
358
+ patientName: p.patientName,
359
+ noShowCount: p.noShowCount,
360
+ totalAppointments: p.totalAppointments,
361
+ noShowRate: p.noShowRate,
362
+ }));
363
+
364
+ const topCancellationPatients = patientMetrics
365
+ .filter(p => p.cancellationCount > 0)
366
+ .sort((a, b) => b.cancellationRate - a.cancellationRate)
367
+ .slice(0, 10)
368
+ .map(p => ({
369
+ patientId: p.patientId,
370
+ patientName: p.patientName,
371
+ cancellationCount: p.cancellationCount,
372
+ totalAppointments: p.totalAppointments,
373
+ cancellationRate: p.cancellationRate,
374
+ }));
375
+
376
+ // Determine new vs returning patients
377
+ const newPatients = patientMetrics.filter(p => p.totalAppointments === 1).length;
378
+ const returningPatients = patientMetrics.filter(p => p.totalAppointments > 1).length;
379
+
380
+ return {
381
+ entityId,
382
+ entityName: data.name,
383
+ entityType,
384
+ totalPatients: patientMap.size,
385
+ patientsWithNoShows,
386
+ patientsWithCancellations,
387
+ averageNoShowRate: Math.round(averageNoShowRate * 100) / 100,
388
+ averageCancellationRate: Math.round(averageCancellationRate * 100) / 100,
389
+ topNoShowPatients,
390
+ topCancellationPatients,
391
+ };
392
+ });
393
+ }
394
+