@blackcode_sa/metaestetics-api 1.12.72 → 1.13.1

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 (37) hide show
  1. package/dist/admin/index.d.mts +872 -1
  2. package/dist/admin/index.d.ts +872 -1
  3. package/dist/admin/index.js +3604 -356
  4. package/dist/admin/index.mjs +3594 -357
  5. package/dist/index.d.mts +1349 -1
  6. package/dist/index.d.ts +1349 -1
  7. package/dist/index.js +5325 -2141
  8. package/dist/index.mjs +4939 -1767
  9. package/package.json +1 -1
  10. package/src/admin/analytics/analytics.admin.service.ts +278 -0
  11. package/src/admin/analytics/index.ts +2 -0
  12. package/src/admin/index.ts +6 -0
  13. package/src/backoffice/services/analytics.service.proposal.md +4 -0
  14. package/src/services/analytics/ARCHITECTURE.md +199 -0
  15. package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -0
  16. package/src/services/analytics/GROUPED_ANALYTICS.md +501 -0
  17. package/src/services/analytics/QUICK_START.md +393 -0
  18. package/src/services/analytics/README.md +304 -0
  19. package/src/services/analytics/SUMMARY.md +141 -0
  20. package/src/services/analytics/TRENDS.md +380 -0
  21. package/src/services/analytics/USAGE_GUIDE.md +518 -0
  22. package/src/services/analytics/analytics-cloud.service.ts +222 -0
  23. package/src/services/analytics/analytics.service.ts +2142 -0
  24. package/src/services/analytics/index.ts +4 -0
  25. package/src/services/analytics/review-analytics.service.ts +941 -0
  26. package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -0
  27. package/src/services/analytics/utils/cost-calculation.utils.ts +182 -0
  28. package/src/services/analytics/utils/grouping.utils.ts +434 -0
  29. package/src/services/analytics/utils/stored-analytics.utils.ts +347 -0
  30. package/src/services/analytics/utils/time-calculation.utils.ts +186 -0
  31. package/src/services/analytics/utils/trend-calculation.utils.ts +200 -0
  32. package/src/services/index.ts +1 -0
  33. package/src/types/analytics/analytics.types.ts +597 -0
  34. package/src/types/analytics/grouped-analytics.types.ts +173 -0
  35. package/src/types/analytics/index.ts +4 -0
  36. package/src/types/analytics/stored-analytics.types.ts +137 -0
  37. package/src/types/index.ts +3 -0
@@ -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,182 @@
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
+ * IMPORTANT: This function should only be called with COMPLETED appointments.
71
+ * Only completed procedures generate revenue. Confirmed, pending, canceled, and no-show
72
+ * appointments should be filtered out before calling this function.
73
+ *
74
+ * @param appointments - Array of appointments (should be filtered to COMPLETED only)
75
+ * @returns Total revenue and currency
76
+ */
77
+ export function calculateTotalRevenue(appointments: Appointment[]): {
78
+ totalRevenue: number;
79
+ currency: string;
80
+ } {
81
+ if (appointments.length === 0) {
82
+ return { totalRevenue: 0, currency: 'CHF' };
83
+ }
84
+
85
+ let totalRevenue = 0;
86
+ const currencies = new Set<string>();
87
+
88
+ appointments.forEach(appointment => {
89
+ const costData = calculateAppointmentCost(appointment);
90
+ totalRevenue += costData.cost;
91
+ currencies.add(costData.currency);
92
+ });
93
+
94
+ // Use the most common currency, or first one found
95
+ const currency = currencies.size > 0 ? Array.from(currencies)[0] : 'CHF';
96
+
97
+ return { totalRevenue, currency };
98
+ }
99
+
100
+ /**
101
+ * Extracts product usage from appointment metadata
102
+ *
103
+ * IMPORTANT: This function should only be called with COMPLETED appointments.
104
+ * Products are only considered "used" when the procedure has been completed.
105
+ * Only completed procedures generate product usage and revenue.
106
+ *
107
+ * NOTE ON PRICING:
108
+ * - Price overrides (priceOverrideAmount) are always applied if available
109
+ * - Subtotal is recalculated to ensure price overrides are reflected
110
+ * - Product revenue shows SUBTOTAL (before tax) - tax is applied at appointment level
111
+ * - Tax is included in appointment revenue (finalbilling.finalPrice) but not in product revenue
112
+ * - Product subtotals should sum to finalbilling.subtotalAll (before tax)
113
+ *
114
+ * @param appointment - The appointment to extract products from (should be COMPLETED)
115
+ * @returns Array of product usage data with subtotal (before tax)
116
+ */
117
+ export function extractProductUsage(appointment: Appointment): Array<{
118
+ productId: string;
119
+ productName: string;
120
+ brandId: string;
121
+ brandName: string;
122
+ quantity: number;
123
+ price: number;
124
+ subtotal: number;
125
+ currency: string;
126
+ }> {
127
+ const products: Array<{
128
+ productId: string;
129
+ productName: string;
130
+ brandId: string;
131
+ brandName: string;
132
+ quantity: number;
133
+ price: number;
134
+ subtotal: number;
135
+ currency: string;
136
+ }> = [];
137
+
138
+ const metadata = appointment.metadata;
139
+ if (!metadata?.zonesData) {
140
+ return products;
141
+ }
142
+
143
+ const zonesData = metadata.zonesData as Record<string, ZoneItemData[]>;
144
+ const currency = appointment.currency || 'CHF';
145
+
146
+ Object.values(zonesData).forEach(items => {
147
+ items.forEach(item => {
148
+ if (item.type === 'item' && item.productId) {
149
+ // Always use priceOverrideAmount if available, otherwise use price
150
+ // This ensures price overrides are properly applied to product calculations
151
+ const price = item.priceOverrideAmount || item.price || 0;
152
+ const quantity = item.quantity || 1;
153
+
154
+ // Always recalculate subtotal based on the actual price (with override)
155
+ // This ensures price overrides are reflected in product revenue
156
+ // Use stored subtotal only if it matches the calculated value (to handle rounding)
157
+ const calculatedSubtotal = price * quantity;
158
+ const storedSubtotal = item.subtotal || 0;
159
+
160
+ // Use stored subtotal if it's close to calculated (within 0.01 for rounding differences)
161
+ // Otherwise recalculate to ensure price override is applied correctly
162
+ const subtotal = Math.abs(storedSubtotal - calculatedSubtotal) < 0.01
163
+ ? storedSubtotal
164
+ : calculatedSubtotal;
165
+
166
+ products.push({
167
+ productId: item.productId,
168
+ productName: item.productName || 'Unknown Product',
169
+ brandId: item.productBrandId || '',
170
+ brandName: item.productBrandName || '',
171
+ quantity,
172
+ price,
173
+ subtotal,
174
+ currency: item.currency || currency,
175
+ });
176
+ }
177
+ });
178
+ });
179
+
180
+ return products;
181
+ }
182
+