@blackcode_sa/metaestetics-api 1.13.5 → 1.13.8
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 +20 -1
- package/dist/admin/index.d.ts +20 -1
- package/dist/admin/index.js +217 -1
- package/dist/admin/index.mjs +217 -1
- package/dist/index.d.mts +26 -3
- package/dist/index.d.ts +26 -3
- package/dist/index.js +168 -6
- package/dist/index.mjs +168 -6
- package/package.json +121 -121
- package/src/__mocks__/firstore.ts +10 -10
- package/src/admin/aggregation/README.md +79 -79
- package/src/admin/aggregation/appointment/README.md +128 -128
- package/src/admin/aggregation/appointment/appointment.aggregation.service.ts +1984 -1984
- package/src/admin/aggregation/appointment/index.ts +1 -1
- package/src/admin/aggregation/clinic/README.md +52 -52
- package/src/admin/aggregation/clinic/clinic.aggregation.service.ts +966 -703
- package/src/admin/aggregation/clinic/index.ts +1 -1
- package/src/admin/aggregation/forms/README.md +13 -13
- package/src/admin/aggregation/forms/filled-forms.aggregation.service.ts +322 -322
- package/src/admin/aggregation/forms/index.ts +1 -1
- package/src/admin/aggregation/index.ts +8 -8
- package/src/admin/aggregation/patient/README.md +27 -27
- package/src/admin/aggregation/patient/index.ts +1 -1
- package/src/admin/aggregation/patient/patient.aggregation.service.ts +141 -141
- package/src/admin/aggregation/practitioner/README.md +42 -42
- package/src/admin/aggregation/practitioner/index.ts +1 -1
- package/src/admin/aggregation/practitioner/practitioner.aggregation.service.ts +433 -433
- package/src/admin/aggregation/practitioner-invite/index.ts +1 -1
- package/src/admin/aggregation/practitioner-invite/practitioner-invite.aggregation.service.ts +961 -961
- package/src/admin/aggregation/procedure/README.md +43 -43
- package/src/admin/aggregation/procedure/index.ts +1 -1
- package/src/admin/aggregation/procedure/procedure.aggregation.service.ts +702 -702
- package/src/admin/aggregation/reviews/index.ts +1 -1
- package/src/admin/aggregation/reviews/reviews.aggregation.service.ts +689 -689
- package/src/admin/analytics/analytics.admin.service.ts +278 -278
- package/src/admin/analytics/index.ts +2 -2
- package/src/admin/booking/README.md +125 -125
- package/src/admin/booking/booking.admin.ts +1037 -1037
- package/src/admin/booking/booking.calculator.ts +712 -712
- package/src/admin/booking/booking.types.ts +59 -59
- package/src/admin/booking/index.ts +3 -3
- package/src/admin/booking/timezones-problem.md +185 -185
- package/src/admin/calendar/README.md +7 -7
- package/src/admin/calendar/calendar.admin.service.ts +345 -345
- package/src/admin/calendar/index.ts +1 -1
- package/src/admin/documentation-templates/document-manager.admin.ts +260 -260
- package/src/admin/documentation-templates/index.ts +1 -1
- package/src/admin/free-consultation/free-consultation-utils.admin.ts +148 -148
- package/src/admin/free-consultation/index.ts +1 -1
- package/src/admin/index.ts +81 -81
- package/src/admin/logger/index.ts +78 -78
- package/src/admin/mailing/README.md +95 -95
- package/src/admin/mailing/appointment/appointment.mailing.service.ts +732 -732
- package/src/admin/mailing/appointment/index.ts +1 -1
- package/src/admin/mailing/appointment/templates/patient/appointment-confirmed.html +40 -40
- package/src/admin/mailing/base.mailing.service.ts +208 -208
- package/src/admin/mailing/index.ts +3 -3
- package/src/admin/mailing/practitionerInvite/existing-practitioner-invite.mailing.ts +611 -611
- package/src/admin/mailing/practitionerInvite/index.ts +2 -2
- package/src/admin/mailing/practitionerInvite/practitionerInvite.mailing.ts +395 -395
- package/src/admin/mailing/practitionerInvite/templates/existing-practitioner-invitation.template.ts +155 -155
- package/src/admin/mailing/practitionerInvite/templates/invitation.template.ts +101 -101
- package/src/admin/mailing/practitionerInvite/templates/invite-accepted-notification.template.ts +228 -228
- package/src/admin/mailing/practitionerInvite/templates/invite-rejected-notification.template.ts +242 -242
- package/src/admin/notifications/index.ts +1 -1
- package/src/admin/notifications/notifications.admin.ts +710 -710
- package/src/admin/requirements/README.md +128 -128
- package/src/admin/requirements/index.ts +1 -1
- package/src/admin/requirements/patient-requirements.admin.service.ts +475 -475
- package/src/admin/users/index.ts +1 -1
- package/src/admin/users/user-profile.admin.ts +405 -405
- package/src/backoffice/constants/certification.constants.ts +13 -13
- package/src/backoffice/constants/index.ts +1 -1
- package/src/backoffice/errors/backoffice.errors.ts +181 -181
- package/src/backoffice/errors/index.ts +1 -1
- package/src/backoffice/expo-safe/README.md +26 -26
- package/src/backoffice/expo-safe/index.ts +41 -41
- package/src/backoffice/index.ts +5 -5
- package/src/backoffice/services/FIXES_README.md +102 -102
- package/src/backoffice/services/README.md +57 -57
- package/src/backoffice/services/analytics.service.proposal.md +863 -863
- package/src/backoffice/services/analytics.service.summary.md +143 -143
- package/src/backoffice/services/brand.service.ts +256 -256
- package/src/backoffice/services/category.service.ts +384 -384
- package/src/backoffice/services/constants.service.ts +385 -385
- package/src/backoffice/services/documentation-template.service.ts +202 -202
- package/src/backoffice/services/index.ts +10 -10
- package/src/backoffice/services/migrate-products.ts +116 -116
- package/src/backoffice/services/product.service.ts +553 -553
- package/src/backoffice/services/requirement.service.ts +235 -235
- package/src/backoffice/services/subcategory.service.ts +461 -461
- package/src/backoffice/services/technology.service.ts +1151 -1151
- package/src/backoffice/types/README.md +12 -12
- package/src/backoffice/types/admin-constants.types.ts +69 -69
- package/src/backoffice/types/brand.types.ts +29 -29
- package/src/backoffice/types/category.types.ts +67 -67
- package/src/backoffice/types/documentation-templates.types.ts +28 -28
- package/src/backoffice/types/index.ts +10 -10
- package/src/backoffice/types/procedure-product.types.ts +38 -38
- package/src/backoffice/types/product.types.ts +240 -240
- package/src/backoffice/types/requirement.types.ts +63 -63
- package/src/backoffice/types/static/README.md +18 -18
- package/src/backoffice/types/static/blocking-condition.types.ts +21 -21
- package/src/backoffice/types/static/certification.types.ts +37 -37
- package/src/backoffice/types/static/contraindication.types.ts +19 -19
- package/src/backoffice/types/static/index.ts +6 -6
- package/src/backoffice/types/static/pricing.types.ts +16 -16
- package/src/backoffice/types/static/procedure-family.types.ts +14 -14
- package/src/backoffice/types/static/treatment-benefit.types.ts +22 -22
- package/src/backoffice/types/subcategory.types.ts +34 -34
- package/src/backoffice/types/technology.types.ts +168 -168
- package/src/backoffice/validations/index.ts +1 -1
- package/src/backoffice/validations/schemas.ts +164 -164
- package/src/config/__mocks__/firebase.ts +99 -99
- package/src/config/firebase.ts +78 -78
- package/src/config/index.ts +9 -9
- package/src/errors/auth.error.ts +6 -6
- package/src/errors/auth.errors.ts +211 -200
- package/src/errors/clinic.errors.ts +32 -32
- package/src/errors/firebase.errors.ts +47 -47
- package/src/errors/user.errors.ts +99 -99
- package/src/index.backup.ts +407 -407
- package/src/index.ts +6 -6
- package/src/locales/en.ts +31 -31
- package/src/recommender/admin/index.ts +1 -1
- package/src/recommender/admin/services/recommender.service.admin.ts +5 -5
- package/src/recommender/front/index.ts +1 -1
- package/src/recommender/front/services/onboarding.service.ts +5 -5
- package/src/recommender/front/services/recommender.service.ts +3 -3
- package/src/recommender/index.ts +1 -1
- package/src/services/PATIENTAUTH.MD +197 -197
- package/src/services/README.md +106 -106
- package/src/services/__tests__/auth/auth.mock.test.ts +17 -17
- package/src/services/__tests__/auth/auth.setup.ts +293 -293
- package/src/services/__tests__/auth.service.test.ts +346 -346
- package/src/services/__tests__/base.service.test.ts +77 -77
- package/src/services/__tests__/user.service.test.ts +528 -528
- package/src/services/analytics/ARCHITECTURE.md +199 -199
- package/src/services/analytics/CLOUD_FUNCTIONS.md +225 -225
- package/src/services/analytics/GROUPED_ANALYTICS.md +501 -501
- package/src/services/analytics/QUICK_START.md +393 -393
- package/src/services/analytics/README.md +304 -304
- package/src/services/analytics/SUMMARY.md +141 -141
- package/src/services/analytics/TRENDS.md +380 -380
- package/src/services/analytics/USAGE_GUIDE.md +518 -518
- package/src/services/analytics/analytics-cloud.service.ts +222 -222
- package/src/services/analytics/analytics.service.ts +2142 -2142
- package/src/services/analytics/index.ts +4 -4
- package/src/services/analytics/review-analytics.service.ts +941 -941
- package/src/services/analytics/utils/appointment-filtering.utils.ts +138 -138
- package/src/services/analytics/utils/cost-calculation.utils.ts +182 -182
- package/src/services/analytics/utils/grouping.utils.ts +434 -434
- package/src/services/analytics/utils/stored-analytics.utils.ts +347 -347
- package/src/services/analytics/utils/time-calculation.utils.ts +186 -186
- package/src/services/analytics/utils/trend-calculation.utils.ts +200 -200
- package/src/services/appointment/README.md +17 -17
- package/src/services/appointment/appointment.service.ts +2558 -2558
- package/src/services/appointment/index.ts +1 -1
- package/src/services/appointment/utils/appointment.utils.ts +552 -552
- package/src/services/appointment/utils/extended-procedure.utils.ts +314 -314
- package/src/services/appointment/utils/form-initialization.utils.ts +225 -225
- package/src/services/appointment/utils/recommended-procedure.utils.ts +195 -195
- package/src/services/appointment/utils/zone-management.utils.ts +353 -353
- package/src/services/appointment/utils/zone-photo.utils.ts +152 -152
- package/src/services/auth/auth.service.ts +1043 -989
- package/src/services/auth/auth.v2.service.ts +961 -961
- package/src/services/auth/index.ts +7 -7
- package/src/services/auth/utils/error.utils.ts +90 -90
- package/src/services/auth/utils/firebase.utils.ts +49 -49
- package/src/services/auth/utils/index.ts +21 -21
- package/src/services/auth/utils/practitioner.utils.ts +125 -125
- package/src/services/base.service.ts +41 -41
- package/src/services/calendar/calendar.service.ts +1077 -1077
- package/src/services/calendar/calendar.v2.service.ts +1683 -1683
- package/src/services/calendar/calendar.v3.service.ts +313 -313
- package/src/services/calendar/externalCalendar.service.ts +178 -178
- package/src/services/calendar/index.ts +5 -5
- package/src/services/calendar/synced-calendars.service.ts +743 -743
- package/src/services/calendar/utils/appointment.utils.ts +265 -265
- package/src/services/calendar/utils/calendar-event.utils.ts +646 -646
- package/src/services/calendar/utils/clinic.utils.ts +237 -237
- package/src/services/calendar/utils/docs.utils.ts +157 -157
- package/src/services/calendar/utils/google-calendar.utils.ts +697 -697
- package/src/services/calendar/utils/index.ts +8 -8
- package/src/services/calendar/utils/patient.utils.ts +198 -198
- package/src/services/calendar/utils/practitioner.utils.ts +221 -221
- package/src/services/calendar/utils/synced-calendar.utils.ts +472 -472
- package/src/services/clinic/README.md +204 -204
- package/src/services/clinic/__tests__/clinic-admin.service.test.ts +287 -287
- package/src/services/clinic/__tests__/clinic-group.service.test.ts +352 -352
- package/src/services/clinic/__tests__/clinic.service.test.ts +354 -354
- package/src/services/clinic/billing-transactions.service.ts +217 -217
- package/src/services/clinic/clinic-admin.service.ts +202 -202
- package/src/services/clinic/clinic-group.service.ts +310 -310
- package/src/services/clinic/clinic.service.ts +708 -708
- package/src/services/clinic/index.ts +5 -5
- package/src/services/clinic/practitioner-invite.service.ts +519 -519
- package/src/services/clinic/utils/admin.utils.ts +551 -551
- package/src/services/clinic/utils/clinic-group.utils.ts +646 -646
- package/src/services/clinic/utils/clinic.utils.ts +949 -949
- package/src/services/clinic/utils/filter.utils.d.ts +23 -23
- package/src/services/clinic/utils/filter.utils.ts +446 -446
- package/src/services/clinic/utils/index.ts +11 -11
- package/src/services/clinic/utils/photos.utils.ts +188 -188
- package/src/services/clinic/utils/search.utils.ts +84 -84
- package/src/services/clinic/utils/tag.utils.ts +124 -124
- package/src/services/documentation-templates/documentation-template.service.ts +537 -537
- package/src/services/documentation-templates/filled-document.service.ts +587 -587
- package/src/services/documentation-templates/index.ts +2 -2
- package/src/services/index.ts +14 -14
- package/src/services/media/index.ts +1 -1
- package/src/services/media/media.service.ts +418 -418
- package/src/services/notifications/__tests__/notification.service.test.ts +242 -242
- package/src/services/notifications/index.ts +1 -1
- package/src/services/notifications/notification.service.ts +215 -215
- package/src/services/patient/README.md +48 -48
- package/src/services/patient/To-Do.md +43 -43
- package/src/services/patient/__tests__/patient.service.test.ts +294 -294
- package/src/services/patient/index.ts +2 -2
- package/src/services/patient/patient.service.ts +883 -883
- package/src/services/patient/patientRequirements.service.ts +285 -285
- package/src/services/patient/utils/aesthetic-analysis.utils.ts +176 -176
- package/src/services/patient/utils/clinic.utils.ts +80 -80
- package/src/services/patient/utils/docs.utils.ts +142 -142
- package/src/services/patient/utils/index.ts +9 -9
- package/src/services/patient/utils/location.utils.ts +126 -126
- package/src/services/patient/utils/medical-stuff.utils.ts +143 -143
- package/src/services/patient/utils/medical.utils.ts +458 -458
- package/src/services/patient/utils/practitioner.utils.ts +260 -260
- package/src/services/patient/utils/profile.utils.ts +510 -510
- package/src/services/patient/utils/sensitive.utils.ts +260 -260
- package/src/services/patient/utils/token.utils.ts +211 -211
- package/src/services/practitioner/README.md +145 -145
- package/src/services/practitioner/index.ts +1 -1
- package/src/services/practitioner/practitioner.service.ts +1799 -1742
- package/src/services/procedure/README.md +163 -163
- package/src/services/procedure/index.ts +1 -1
- package/src/services/procedure/procedure.service.ts +2307 -2200
- package/src/services/reviews/index.ts +1 -1
- package/src/services/reviews/reviews.service.ts +734 -734
- package/src/services/user/index.ts +1 -1
- package/src/services/user/user.service.ts +489 -489
- package/src/services/user/user.v2.service.ts +466 -466
- package/src/types/analytics/analytics.types.ts +597 -597
- package/src/types/analytics/grouped-analytics.types.ts +173 -173
- package/src/types/analytics/index.ts +4 -4
- package/src/types/analytics/stored-analytics.types.ts +137 -137
- package/src/types/appointment/index.ts +480 -480
- package/src/types/calendar/index.ts +258 -258
- package/src/types/calendar/synced-calendar.types.ts +66 -66
- package/src/types/clinic/index.ts +498 -498
- package/src/types/clinic/practitioner-invite.types.ts +91 -91
- package/src/types/clinic/preferences.types.ts +159 -159
- package/src/types/clinic/to-do +3 -3
- package/src/types/documentation-templates/index.ts +308 -308
- package/src/types/index.ts +47 -47
- package/src/types/notifications/README.md +77 -77
- package/src/types/notifications/index.ts +286 -286
- package/src/types/patient/aesthetic-analysis.types.ts +66 -66
- package/src/types/patient/allergies.ts +58 -58
- package/src/types/patient/index.ts +275 -275
- package/src/types/patient/medical-info.types.ts +152 -152
- package/src/types/patient/patient-requirements.ts +92 -92
- package/src/types/patient/token.types.ts +61 -61
- package/src/types/practitioner/index.ts +206 -206
- package/src/types/procedure/index.ts +181 -181
- package/src/types/profile/index.ts +39 -39
- package/src/types/reviews/index.ts +132 -132
- package/src/types/tz-lookup.d.ts +4 -4
- package/src/types/user/index.ts +38 -38
- package/src/utils/TIMESTAMPS.md +176 -176
- package/src/utils/TimestampUtils.ts +241 -241
- package/src/utils/index.ts +1 -1
- package/src/validations/appointment.schema.ts +574 -574
- package/src/validations/calendar.schema.ts +225 -225
- package/src/validations/clinic.schema.ts +494 -494
- package/src/validations/common.schema.ts +25 -25
- package/src/validations/documentation-templates/index.ts +1 -1
- package/src/validations/documentation-templates/template.schema.ts +220 -220
- package/src/validations/documentation-templates.schema.ts +10 -10
- package/src/validations/index.ts +20 -20
- package/src/validations/media.schema.ts +10 -10
- package/src/validations/notification.schema.ts +90 -90
- package/src/validations/patient/aesthetic-analysis.schema.ts +55 -55
- package/src/validations/patient/medical-info.schema.ts +125 -125
- package/src/validations/patient/patient-requirements.schema.ts +84 -84
- package/src/validations/patient/token.schema.ts +29 -29
- package/src/validations/patient.schema.ts +217 -217
- package/src/validations/practitioner.schema.ts +222 -222
- package/src/validations/procedure-product.schema.ts +41 -41
- package/src/validations/procedure.schema.ts +124 -124
- package/src/validations/profile-info.schema.ts +41 -41
- package/src/validations/reviews.schema.ts +195 -195
- package/src/validations/schemas.ts +104 -104
- package/src/validations/shared.schema.ts +78 -78
|
@@ -1,2200 +1,2307 @@
|
|
|
1
|
-
import {
|
|
2
|
-
collection,
|
|
3
|
-
doc,
|
|
4
|
-
getDoc,
|
|
5
|
-
getDocs,
|
|
6
|
-
query,
|
|
7
|
-
where,
|
|
8
|
-
updateDoc,
|
|
9
|
-
setDoc,
|
|
10
|
-
deleteDoc,
|
|
11
|
-
Timestamp,
|
|
12
|
-
serverTimestamp,
|
|
13
|
-
DocumentData,
|
|
14
|
-
writeBatch,
|
|
15
|
-
arrayUnion,
|
|
16
|
-
arrayRemove,
|
|
17
|
-
FieldValue,
|
|
18
|
-
orderBy,
|
|
19
|
-
limit,
|
|
20
|
-
startAfter,
|
|
21
|
-
QueryConstraint,
|
|
22
|
-
documentId,
|
|
23
|
-
} from 'firebase/firestore';
|
|
24
|
-
import { BaseService } from '../base.service';
|
|
25
|
-
import {
|
|
26
|
-
Procedure,
|
|
27
|
-
CreateProcedureData,
|
|
28
|
-
UpdateProcedureData,
|
|
29
|
-
PROCEDURES_COLLECTION,
|
|
30
|
-
ProcedureSummaryInfo,
|
|
31
|
-
} from '../../types/procedure';
|
|
32
|
-
import { createProcedureSchema, updateProcedureSchema } from '../../validations/procedure.schema';
|
|
33
|
-
import { z } from 'zod';
|
|
34
|
-
import { Auth } from 'firebase/auth';
|
|
35
|
-
import { Firestore } from 'firebase/firestore';
|
|
36
|
-
import { FirebaseApp } from 'firebase/app';
|
|
37
|
-
import { Category, CATEGORIES_COLLECTION } from '../../backoffice/types/category.types';
|
|
38
|
-
import { Subcategory, SUBCATEGORIES_COLLECTION } from '../../backoffice/types/subcategory.types';
|
|
39
|
-
import { Technology, TECHNOLOGIES_COLLECTION } from '../../backoffice/types/technology.types';
|
|
40
|
-
import { Product, PRODUCTS_COLLECTION } from '../../backoffice/types/product.types';
|
|
41
|
-
import { CategoryService } from '../../backoffice/services/category.service';
|
|
42
|
-
import { SubcategoryService } from '../../backoffice/services/subcategory.service';
|
|
43
|
-
import { TechnologyService } from '../../backoffice/services/technology.service';
|
|
44
|
-
import { ProductService } from '../../backoffice/services/product.service';
|
|
45
|
-
import { Practitioner, PRACTITIONERS_COLLECTION } from '../../types/practitioner';
|
|
46
|
-
import {
|
|
47
|
-
CertificationLevel,
|
|
48
|
-
CertificationSpecialty,
|
|
49
|
-
ProcedureFamily,
|
|
50
|
-
type TreatmentBenefitDynamic,
|
|
51
|
-
} from '../../backoffice/types';
|
|
52
|
-
import { Currency, PricingMeasure } from '../../backoffice/types/static/pricing.types';
|
|
53
|
-
import { Clinic, CLINICS_COLLECTION } from '../../types/clinic';
|
|
54
|
-
import { ProcedureReviewInfo } from '../../types/reviews';
|
|
55
|
-
import { distanceBetween, geohashQueryBounds } from 'geofire-common';
|
|
56
|
-
import { MediaService, MediaAccessLevel } from '../media/media.service';
|
|
57
|
-
import type { ProcedureProduct } from '../../backoffice/types/procedure-product.types';
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
private
|
|
64
|
-
private
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
this.
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
}
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
*
|
|
191
|
-
* @param
|
|
192
|
-
* @returns
|
|
193
|
-
*/
|
|
194
|
-
async
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
const
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
const
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
//
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
const
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
// Create the procedure document
|
|
380
|
-
const
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
//
|
|
457
|
-
const
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
);
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
const
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
)
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
}
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
);
|
|
786
|
-
|
|
787
|
-
//
|
|
788
|
-
const
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
const
|
|
811
|
-
const
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
.
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
const
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
const
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
*
|
|
1040
|
-
* @
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
if (validatedData.
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
//
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
*
|
|
1352
|
-
* @param
|
|
1353
|
-
* @
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
if (
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
const
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
}
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
}
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
constraints.push(where('
|
|
1530
|
-
|
|
1531
|
-
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
constraints.push(
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
//
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
}
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1651
|
-
|
|
1652
|
-
|
|
1653
|
-
|
|
1654
|
-
|
|
1655
|
-
|
|
1656
|
-
|
|
1657
|
-
|
|
1658
|
-
|
|
1659
|
-
|
|
1660
|
-
|
|
1661
|
-
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
1676
|
-
|
|
1677
|
-
console.log(
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
];
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
1699
|
-
)
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
const
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
|
|
1777
|
-
|
|
1778
|
-
|
|
1779
|
-
|
|
1780
|
-
|
|
1781
|
-
|
|
1782
|
-
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
1786
|
-
|
|
1787
|
-
|
|
1788
|
-
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1793
|
-
|
|
1794
|
-
|
|
1795
|
-
|
|
1796
|
-
|
|
1797
|
-
|
|
1798
|
-
|
|
1799
|
-
|
|
1800
|
-
|
|
1801
|
-
|
|
1802
|
-
|
|
1803
|
-
|
|
1804
|
-
|
|
1805
|
-
|
|
1806
|
-
|
|
1807
|
-
|
|
1808
|
-
|
|
1809
|
-
|
|
1810
|
-
|
|
1811
|
-
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
|
|
1830
|
-
|
|
1831
|
-
|
|
1832
|
-
|
|
1833
|
-
|
|
1834
|
-
|
|
1835
|
-
|
|
1836
|
-
|
|
1837
|
-
|
|
1838
|
-
|
|
1839
|
-
|
|
1840
|
-
|
|
1841
|
-
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
|
|
1845
|
-
|
|
1846
|
-
|
|
1847
|
-
|
|
1848
|
-
)
|
|
1849
|
-
|
|
1850
|
-
|
|
1851
|
-
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
);
|
|
1859
|
-
console.log(
|
|
1860
|
-
|
|
1861
|
-
|
|
1862
|
-
|
|
1863
|
-
|
|
1864
|
-
|
|
1865
|
-
|
|
1866
|
-
|
|
1867
|
-
|
|
1868
|
-
|
|
1869
|
-
|
|
1870
|
-
|
|
1871
|
-
|
|
1872
|
-
|
|
1873
|
-
|
|
1874
|
-
|
|
1875
|
-
|
|
1876
|
-
|
|
1877
|
-
|
|
1878
|
-
|
|
1879
|
-
|
|
1880
|
-
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
1889
|
-
|
|
1890
|
-
|
|
1891
|
-
|
|
1892
|
-
|
|
1893
|
-
|
|
1894
|
-
|
|
1895
|
-
|
|
1896
|
-
|
|
1897
|
-
|
|
1898
|
-
|
|
1899
|
-
|
|
1900
|
-
|
|
1901
|
-
|
|
1902
|
-
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1908
|
-
|
|
1909
|
-
|
|
1910
|
-
|
|
1911
|
-
|
|
1912
|
-
|
|
1913
|
-
|
|
1914
|
-
|
|
1915
|
-
|
|
1916
|
-
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
1938
|
-
|
|
1939
|
-
|
|
1940
|
-
|
|
1941
|
-
|
|
1942
|
-
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
|
|
1949
|
-
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
|
|
1979
|
-
|
|
1980
|
-
|
|
1981
|
-
|
|
1982
|
-
|
|
1983
|
-
|
|
1984
|
-
|
|
1985
|
-
|
|
1986
|
-
|
|
1987
|
-
|
|
1988
|
-
|
|
1989
|
-
|
|
1990
|
-
|
|
1991
|
-
|
|
1992
|
-
|
|
1993
|
-
|
|
1994
|
-
|
|
1995
|
-
|
|
1996
|
-
|
|
1997
|
-
|
|
1998
|
-
|
|
1999
|
-
|
|
2000
|
-
|
|
2001
|
-
|
|
2002
|
-
|
|
2003
|
-
|
|
2004
|
-
|
|
2005
|
-
|
|
2006
|
-
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
2012
|
-
|
|
2013
|
-
|
|
2014
|
-
|
|
2015
|
-
|
|
2016
|
-
|
|
2017
|
-
|
|
2018
|
-
|
|
2019
|
-
|
|
2020
|
-
|
|
2021
|
-
|
|
2022
|
-
|
|
2023
|
-
|
|
2024
|
-
|
|
2025
|
-
|
|
2026
|
-
|
|
2027
|
-
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
|
|
2031
|
-
|
|
2032
|
-
|
|
2033
|
-
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
2059
|
-
|
|
2060
|
-
|
|
2061
|
-
|
|
2062
|
-
|
|
2063
|
-
|
|
2064
|
-
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
}
|
|
2100
|
-
|
|
2101
|
-
//
|
|
2102
|
-
const
|
|
2103
|
-
await
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2108
|
-
|
|
2109
|
-
|
|
2110
|
-
const
|
|
2111
|
-
|
|
2112
|
-
|
|
2113
|
-
|
|
2114
|
-
|
|
2115
|
-
|
|
2116
|
-
|
|
2117
|
-
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2124
|
-
|
|
2125
|
-
|
|
2126
|
-
|
|
2127
|
-
|
|
2128
|
-
|
|
2129
|
-
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
|
|
2134
|
-
|
|
2135
|
-
|
|
2136
|
-
|
|
2137
|
-
|
|
2138
|
-
|
|
2139
|
-
|
|
2140
|
-
|
|
2141
|
-
|
|
2142
|
-
|
|
2143
|
-
|
|
2144
|
-
|
|
2145
|
-
|
|
2146
|
-
|
|
2147
|
-
|
|
2148
|
-
|
|
2149
|
-
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
|
|
2156
|
-
|
|
2157
|
-
|
|
2158
|
-
|
|
2159
|
-
|
|
2160
|
-
|
|
2161
|
-
|
|
2162
|
-
|
|
2163
|
-
|
|
2164
|
-
|
|
2165
|
-
|
|
2166
|
-
|
|
2167
|
-
|
|
2168
|
-
|
|
2169
|
-
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
2174
|
-
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
|
|
2178
|
-
|
|
2179
|
-
|
|
2180
|
-
|
|
2181
|
-
|
|
2182
|
-
|
|
2183
|
-
|
|
2184
|
-
|
|
2185
|
-
|
|
2186
|
-
|
|
2187
|
-
|
|
2188
|
-
|
|
2189
|
-
|
|
2190
|
-
|
|
2191
|
-
|
|
2192
|
-
|
|
2193
|
-
|
|
2194
|
-
|
|
2195
|
-
|
|
2196
|
-
|
|
2197
|
-
|
|
2198
|
-
|
|
2199
|
-
|
|
2200
|
-
|
|
1
|
+
import {
|
|
2
|
+
collection,
|
|
3
|
+
doc,
|
|
4
|
+
getDoc,
|
|
5
|
+
getDocs,
|
|
6
|
+
query,
|
|
7
|
+
where,
|
|
8
|
+
updateDoc,
|
|
9
|
+
setDoc,
|
|
10
|
+
deleteDoc,
|
|
11
|
+
Timestamp,
|
|
12
|
+
serverTimestamp,
|
|
13
|
+
DocumentData,
|
|
14
|
+
writeBatch,
|
|
15
|
+
arrayUnion,
|
|
16
|
+
arrayRemove,
|
|
17
|
+
FieldValue,
|
|
18
|
+
orderBy,
|
|
19
|
+
limit,
|
|
20
|
+
startAfter,
|
|
21
|
+
QueryConstraint,
|
|
22
|
+
documentId,
|
|
23
|
+
} from 'firebase/firestore';
|
|
24
|
+
import { BaseService } from '../base.service';
|
|
25
|
+
import {
|
|
26
|
+
Procedure,
|
|
27
|
+
CreateProcedureData,
|
|
28
|
+
UpdateProcedureData,
|
|
29
|
+
PROCEDURES_COLLECTION,
|
|
30
|
+
ProcedureSummaryInfo,
|
|
31
|
+
} from '../../types/procedure';
|
|
32
|
+
import { createProcedureSchema, updateProcedureSchema } from '../../validations/procedure.schema';
|
|
33
|
+
import { z } from 'zod';
|
|
34
|
+
import { Auth } from 'firebase/auth';
|
|
35
|
+
import { Firestore } from 'firebase/firestore';
|
|
36
|
+
import { FirebaseApp } from 'firebase/app';
|
|
37
|
+
import { Category, CATEGORIES_COLLECTION } from '../../backoffice/types/category.types';
|
|
38
|
+
import { Subcategory, SUBCATEGORIES_COLLECTION } from '../../backoffice/types/subcategory.types';
|
|
39
|
+
import { Technology, TECHNOLOGIES_COLLECTION } from '../../backoffice/types/technology.types';
|
|
40
|
+
import { Product, PRODUCTS_COLLECTION } from '../../backoffice/types/product.types';
|
|
41
|
+
import { CategoryService } from '../../backoffice/services/category.service';
|
|
42
|
+
import { SubcategoryService } from '../../backoffice/services/subcategory.service';
|
|
43
|
+
import { TechnologyService } from '../../backoffice/services/technology.service';
|
|
44
|
+
import { ProductService } from '../../backoffice/services/product.service';
|
|
45
|
+
import { Practitioner, PRACTITIONERS_COLLECTION } from '../../types/practitioner';
|
|
46
|
+
import {
|
|
47
|
+
CertificationLevel,
|
|
48
|
+
CertificationSpecialty,
|
|
49
|
+
ProcedureFamily,
|
|
50
|
+
type TreatmentBenefitDynamic,
|
|
51
|
+
} from '../../backoffice/types';
|
|
52
|
+
import { Currency, PricingMeasure } from '../../backoffice/types/static/pricing.types';
|
|
53
|
+
import { Clinic, CLINICS_COLLECTION } from '../../types/clinic';
|
|
54
|
+
import { ProcedureReviewInfo } from '../../types/reviews';
|
|
55
|
+
import { distanceBetween, geohashQueryBounds } from 'geofire-common';
|
|
56
|
+
import { MediaService, MediaAccessLevel } from '../media/media.service';
|
|
57
|
+
import type { ProcedureProduct } from '../../backoffice/types/procedure-product.types';
|
|
58
|
+
|
|
59
|
+
import { PractitionerService } from '../practitioner/practitioner.service';
|
|
60
|
+
import { PractitionerStatus } from '../../types/practitioner';
|
|
61
|
+
|
|
62
|
+
export class ProcedureService extends BaseService {
|
|
63
|
+
private categoryService: CategoryService;
|
|
64
|
+
private subcategoryService: SubcategoryService;
|
|
65
|
+
private technologyService: TechnologyService;
|
|
66
|
+
private productService: ProductService;
|
|
67
|
+
private mediaService: MediaService;
|
|
68
|
+
private practitionerService?: PractitionerService;
|
|
69
|
+
|
|
70
|
+
constructor(
|
|
71
|
+
db: Firestore,
|
|
72
|
+
auth: Auth,
|
|
73
|
+
app: FirebaseApp,
|
|
74
|
+
categoryService: CategoryService,
|
|
75
|
+
subcategoryService: SubcategoryService,
|
|
76
|
+
technologyService: TechnologyService,
|
|
77
|
+
productService: ProductService,
|
|
78
|
+
mediaService: MediaService,
|
|
79
|
+
) {
|
|
80
|
+
super(db, auth, app);
|
|
81
|
+
this.categoryService = categoryService;
|
|
82
|
+
this.subcategoryService = subcategoryService;
|
|
83
|
+
this.technologyService = technologyService;
|
|
84
|
+
this.productService = productService;
|
|
85
|
+
this.mediaService = mediaService;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
setPractitionerService(practitionerService: PractitionerService) {
|
|
89
|
+
this.practitionerService = practitionerService;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Filters out procedures from draft practitioners
|
|
94
|
+
* @param procedures - Array of procedures to filter
|
|
95
|
+
* @returns Filtered array of procedures (excluding those from draft practitioners)
|
|
96
|
+
*/
|
|
97
|
+
private async filterDraftPractitionerProcedures(
|
|
98
|
+
procedures: Procedure[]
|
|
99
|
+
): Promise<Procedure[]> {
|
|
100
|
+
if (!this.practitionerService || procedures.length === 0) {
|
|
101
|
+
return procedures;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
try {
|
|
105
|
+
// Get unique practitioner IDs from procedures
|
|
106
|
+
const practitionerIds = Array.from(
|
|
107
|
+
new Set(procedures.map((p) => p.practitionerId).filter(Boolean))
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
if (practitionerIds.length === 0) {
|
|
111
|
+
return procedures;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Fetch all practitioners in parallel
|
|
115
|
+
const practitionerPromises = practitionerIds.map((id) =>
|
|
116
|
+
this.practitionerService!.getPractitioner(id).catch(() => null)
|
|
117
|
+
);
|
|
118
|
+
const practitioners = await Promise.all(practitionerPromises);
|
|
119
|
+
|
|
120
|
+
// Create a map of practitioner ID to status
|
|
121
|
+
const practitionerStatusMap = new Map<string, PractitionerStatus>();
|
|
122
|
+
practitioners.forEach((practitioner, index) => {
|
|
123
|
+
if (practitioner) {
|
|
124
|
+
practitionerStatusMap.set(practitionerIds[index], practitioner.status);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// Filter out procedures from draft practitioners
|
|
129
|
+
const filteredProcedures = procedures.filter((procedure) => {
|
|
130
|
+
const practitionerStatus = practitionerStatusMap.get(procedure.practitionerId);
|
|
131
|
+
return practitionerStatus !== PractitionerStatus.DRAFT;
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
if (filteredProcedures.length !== procedures.length) {
|
|
135
|
+
console.log(
|
|
136
|
+
`[ProcedureService] Filtered out ${
|
|
137
|
+
procedures.length - filteredProcedures.length
|
|
138
|
+
} procedures from draft practitioners`
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return filteredProcedures;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
console.error(
|
|
145
|
+
'[ProcedureService] Error filtering draft practitioner procedures:',
|
|
146
|
+
error
|
|
147
|
+
);
|
|
148
|
+
// On error, return original procedures to avoid breaking functionality
|
|
149
|
+
return procedures;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Process media resource (string URL or File object)
|
|
155
|
+
* @param media String URL or File object
|
|
156
|
+
* @param ownerId Owner ID for the media (usually procedureId)
|
|
157
|
+
* @param collectionName Collection name for organizing files
|
|
158
|
+
* @returns URL string after processing
|
|
159
|
+
*/
|
|
160
|
+
private async processMedia(
|
|
161
|
+
media: string | File | Blob | null | undefined,
|
|
162
|
+
ownerId: string,
|
|
163
|
+
collectionName: string,
|
|
164
|
+
): Promise<string | null> {
|
|
165
|
+
if (!media) return null;
|
|
166
|
+
|
|
167
|
+
// If already a string URL, return it directly
|
|
168
|
+
if (typeof media === 'string') {
|
|
169
|
+
return media;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// If it's a File, upload it using MediaService
|
|
173
|
+
if (media instanceof File || media instanceof Blob) {
|
|
174
|
+
console.log(`[ProcedureService] Uploading ${collectionName} media for ${ownerId}`);
|
|
175
|
+
const metadata = await this.mediaService.uploadMedia(
|
|
176
|
+
media,
|
|
177
|
+
ownerId,
|
|
178
|
+
MediaAccessLevel.PUBLIC,
|
|
179
|
+
collectionName,
|
|
180
|
+
);
|
|
181
|
+
return metadata.url;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Process array of media resources (strings or Files)
|
|
189
|
+
* @param mediaArray Array of string URLs or File objects
|
|
190
|
+
* @param ownerId Owner ID for the media
|
|
191
|
+
* @param collectionName Collection name for organizing files
|
|
192
|
+
* @returns Array of URL strings after processing
|
|
193
|
+
*/
|
|
194
|
+
private async processMediaArray(
|
|
195
|
+
mediaArray: (string | File | Blob)[] | undefined,
|
|
196
|
+
ownerId: string,
|
|
197
|
+
collectionName: string,
|
|
198
|
+
): Promise<string[]> {
|
|
199
|
+
if (!mediaArray || mediaArray.length === 0) return [];
|
|
200
|
+
|
|
201
|
+
const result: string[] = [];
|
|
202
|
+
|
|
203
|
+
for (const media of mediaArray) {
|
|
204
|
+
const processedUrl = await this.processMedia(media, ownerId, collectionName);
|
|
205
|
+
if (processedUrl) {
|
|
206
|
+
result.push(processedUrl);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
return result;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Transforms validated procedure product data (with productId) to ProcedureProduct objects (with full product)
|
|
215
|
+
* @param productsMetadata Array of validated procedure product data (optional)
|
|
216
|
+
* @param technologyId Technology ID to fetch products from
|
|
217
|
+
* @returns Array of ProcedureProduct objects with full product information
|
|
218
|
+
*/
|
|
219
|
+
private async transformProductsMetadata(
|
|
220
|
+
productsMetadata: {
|
|
221
|
+
productId: string;
|
|
222
|
+
price: number;
|
|
223
|
+
currency: Currency;
|
|
224
|
+
pricingMeasure: PricingMeasure;
|
|
225
|
+
isDefault?: boolean;
|
|
226
|
+
}[] | undefined,
|
|
227
|
+
technologyId: string,
|
|
228
|
+
): Promise<ProcedureProduct[]> {
|
|
229
|
+
// Return empty array if no products metadata provided (for product-free procedures like consultations)
|
|
230
|
+
if (!productsMetadata || productsMetadata.length === 0) {
|
|
231
|
+
return [];
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const transformedProducts: ProcedureProduct[] = [];
|
|
235
|
+
|
|
236
|
+
for (const productData of productsMetadata) {
|
|
237
|
+
// Fetch the full product object
|
|
238
|
+
const product = await this.productService.getById(technologyId, productData.productId);
|
|
239
|
+
if (!product) {
|
|
240
|
+
throw new Error(
|
|
241
|
+
`Product with ID ${productData.productId} not found for technology ${technologyId}`,
|
|
242
|
+
);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Transform to ProcedureProduct
|
|
246
|
+
transformedProducts.push({
|
|
247
|
+
product,
|
|
248
|
+
price: productData.price,
|
|
249
|
+
currency: productData.currency,
|
|
250
|
+
pricingMeasure: productData.pricingMeasure,
|
|
251
|
+
isDefault: productData.isDefault,
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
return transformedProducts;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Creates a new procedure
|
|
260
|
+
* @param data - The data for creating a new procedure
|
|
261
|
+
* @returns The created procedure
|
|
262
|
+
*/
|
|
263
|
+
async createProcedure(data: CreateProcedureData): Promise<Procedure> {
|
|
264
|
+
const validatedData = createProcedureSchema.parse(data);
|
|
265
|
+
|
|
266
|
+
// Check if this is a product-free procedure (e.g., free consultation)
|
|
267
|
+
const isProductFree = !validatedData.productId;
|
|
268
|
+
|
|
269
|
+
// Generate procedure ID first so we can use it for media uploads
|
|
270
|
+
const procedureId = this.generateId();
|
|
271
|
+
|
|
272
|
+
// Get references to related entities (Category, Subcategory, Technology, and optionally Product)
|
|
273
|
+
const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
|
|
274
|
+
this.categoryService.getById(validatedData.categoryId),
|
|
275
|
+
this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
|
|
276
|
+
this.technologyService.getById(validatedData.technologyId),
|
|
277
|
+
];
|
|
278
|
+
|
|
279
|
+
// Only fetch product if productId is provided
|
|
280
|
+
if (!isProductFree) {
|
|
281
|
+
baseEntitiesPromises.push(
|
|
282
|
+
this.productService.getById(validatedData.technologyId, validatedData.productId!)
|
|
283
|
+
);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const results = await Promise.all(baseEntitiesPromises);
|
|
287
|
+
const category = results[0] as Category | null;
|
|
288
|
+
const subcategory = results[1] as Subcategory | null;
|
|
289
|
+
const technology = results[2] as Technology | null;
|
|
290
|
+
const product = isProductFree ? undefined : ((results[3] as Product | null) || undefined);
|
|
291
|
+
|
|
292
|
+
if (!category || !subcategory || !technology) {
|
|
293
|
+
throw new Error('One or more required base entities not found');
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// For regular procedures, validate product exists
|
|
297
|
+
if (!isProductFree && !product) {
|
|
298
|
+
throw new Error('Product not found for regular procedure');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// Get clinic and practitioner information for aggregation
|
|
302
|
+
const clinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
|
|
303
|
+
const clinicSnapshot = await getDoc(clinicRef);
|
|
304
|
+
if (!clinicSnapshot.exists()) {
|
|
305
|
+
throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
|
|
306
|
+
}
|
|
307
|
+
const clinic = clinicSnapshot.data() as Clinic; // Assert type
|
|
308
|
+
|
|
309
|
+
const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, validatedData.practitionerId);
|
|
310
|
+
const practitionerSnapshot = await getDoc(practitionerRef);
|
|
311
|
+
if (!practitionerSnapshot.exists()) {
|
|
312
|
+
throw new Error(`Practitioner with ID ${validatedData.practitionerId} not found`);
|
|
313
|
+
}
|
|
314
|
+
const practitioner = practitionerSnapshot.data() as Practitioner; // Assert type
|
|
315
|
+
|
|
316
|
+
// Check if practitioner already has a procedure with the same technology ID in this clinic branch
|
|
317
|
+
const existingProceduresQuery = query(
|
|
318
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
319
|
+
where('practitionerId', '==', validatedData.practitionerId),
|
|
320
|
+
where('clinicBranchId', '==', validatedData.clinicBranchId),
|
|
321
|
+
where('isActive', '==', true)
|
|
322
|
+
);
|
|
323
|
+
const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
|
|
324
|
+
const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
|
|
325
|
+
|
|
326
|
+
const hasSameTechnology = existingProcedures.some(
|
|
327
|
+
proc => proc.technology?.id === validatedData.technologyId
|
|
328
|
+
);
|
|
329
|
+
if (hasSameTechnology) {
|
|
330
|
+
throw new Error(
|
|
331
|
+
`Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch`
|
|
332
|
+
);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Process photos if provided
|
|
336
|
+
let processedPhotos: string[] = [];
|
|
337
|
+
if (validatedData.photos && validatedData.photos.length > 0) {
|
|
338
|
+
processedPhotos = await this.processMediaArray(
|
|
339
|
+
validatedData.photos,
|
|
340
|
+
procedureId,
|
|
341
|
+
'procedure-photos',
|
|
342
|
+
);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// If no photos provided and technology has a photoTemplate, use it as default photo
|
|
346
|
+
if (processedPhotos.length === 0 && technology.photoTemplate) {
|
|
347
|
+
console.log(`[ProcedureService] Using technology photoTemplate as default photo: ${technology.photoTemplate}`);
|
|
348
|
+
const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
|
|
349
|
+
if (photoTemplateUrl) {
|
|
350
|
+
processedPhotos.push(photoTemplateUrl);
|
|
351
|
+
} else {
|
|
352
|
+
console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// Transform productsMetadata from validation format to ProcedureProduct format
|
|
357
|
+
const transformedProductsMetadata = await this.transformProductsMetadata(
|
|
358
|
+
validatedData.productsMetadata,
|
|
359
|
+
validatedData.technologyId,
|
|
360
|
+
);
|
|
361
|
+
|
|
362
|
+
// Create aggregated clinic info for the procedure document
|
|
363
|
+
const clinicInfo = {
|
|
364
|
+
id: clinicSnapshot.id,
|
|
365
|
+
name: clinic.name,
|
|
366
|
+
description: clinic.description || '',
|
|
367
|
+
featuredPhoto:
|
|
368
|
+
clinic.featuredPhotos && clinic.featuredPhotos.length > 0
|
|
369
|
+
? typeof clinic.featuredPhotos[0] === 'string'
|
|
370
|
+
? clinic.featuredPhotos[0]
|
|
371
|
+
: ''
|
|
372
|
+
: typeof clinic.coverPhoto === 'string'
|
|
373
|
+
? clinic.coverPhoto
|
|
374
|
+
: '',
|
|
375
|
+
location: clinic.location,
|
|
376
|
+
contactInfo: clinic.contactInfo,
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
// Create aggregated doctor info for the procedure document
|
|
380
|
+
const doctorInfo = {
|
|
381
|
+
id: practitionerSnapshot.id,
|
|
382
|
+
name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
|
|
383
|
+
description: practitioner.basicInfo.bio || '',
|
|
384
|
+
photo:
|
|
385
|
+
typeof practitioner.basicInfo.profileImageUrl === 'string'
|
|
386
|
+
? practitioner.basicInfo.profileImageUrl
|
|
387
|
+
: '', // Default to empty string if not a processed URL
|
|
388
|
+
rating: practitioner.reviewInfo?.averageRating || 0,
|
|
389
|
+
services: practitioner.procedures || [],
|
|
390
|
+
};
|
|
391
|
+
|
|
392
|
+
// Create the procedure object
|
|
393
|
+
const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
|
|
394
|
+
const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
|
|
395
|
+
id: procedureId,
|
|
396
|
+
...validatedDataWithoutProductsMetadata,
|
|
397
|
+
// Ensure nameLower is always set even if omitted by client
|
|
398
|
+
nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
|
|
399
|
+
photos: processedPhotos,
|
|
400
|
+
category, // Embed full objects
|
|
401
|
+
subcategory,
|
|
402
|
+
technology,
|
|
403
|
+
...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
|
|
404
|
+
productsMetadata: transformedProductsMetadata, // Use transformed data, not original
|
|
405
|
+
blockingConditions: technology.blockingConditions,
|
|
406
|
+
contraindications: technology.contraindications || [],
|
|
407
|
+
contraindicationIds: technology.contraindications?.map(c => c.id) || [],
|
|
408
|
+
treatmentBenefits: technology.benefits,
|
|
409
|
+
treatmentBenefitIds: Array.isArray(technology.benefits)
|
|
410
|
+
? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
|
|
411
|
+
: [],
|
|
412
|
+
preRequirements: technology.requirements.pre,
|
|
413
|
+
postRequirements: technology.requirements.post,
|
|
414
|
+
certificationRequirement: technology.certificationRequirement,
|
|
415
|
+
documentationTemplates: technology?.documentationTemplates || [],
|
|
416
|
+
clinicInfo, // Embed aggregated info
|
|
417
|
+
doctorInfo, // Embed aggregated info
|
|
418
|
+
reviewInfo: {
|
|
419
|
+
// Default empty reviews
|
|
420
|
+
totalReviews: 0,
|
|
421
|
+
averageRating: 0,
|
|
422
|
+
effectivenessOfTreatment: 0,
|
|
423
|
+
outcomeExplanation: 0,
|
|
424
|
+
painManagement: 0,
|
|
425
|
+
followUpCare: 0,
|
|
426
|
+
valueForMoney: 0,
|
|
427
|
+
recommendationPercentage: 0,
|
|
428
|
+
},
|
|
429
|
+
isActive: true, // Default to active
|
|
430
|
+
};
|
|
431
|
+
|
|
432
|
+
// 🔥 DEBUG: Find undefined fields before writing to Firestore
|
|
433
|
+
console.log('🔥🔥🔥 CREATE PROCEDURE - Processing procedure:', procedureId);
|
|
434
|
+
console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
|
|
435
|
+
|
|
436
|
+
const undefinedFields: string[] = [];
|
|
437
|
+
Object.entries(newProcedure).forEach(([key, value]) => {
|
|
438
|
+
if (value === undefined) {
|
|
439
|
+
undefinedFields.push(key);
|
|
440
|
+
}
|
|
441
|
+
});
|
|
442
|
+
if (undefinedFields.length > 0) {
|
|
443
|
+
console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
|
|
444
|
+
throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
|
|
445
|
+
}
|
|
446
|
+
console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with setDoc');
|
|
447
|
+
|
|
448
|
+
// Create the procedure document
|
|
449
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
|
|
450
|
+
await setDoc(procedureRef, {
|
|
451
|
+
...newProcedure,
|
|
452
|
+
createdAt: serverTimestamp(),
|
|
453
|
+
updatedAt: serverTimestamp(),
|
|
454
|
+
});
|
|
455
|
+
|
|
456
|
+
// Return the created procedure (fetch again to get server timestamps)
|
|
457
|
+
const savedDoc = await getDoc(procedureRef);
|
|
458
|
+
return savedDoc.data() as Procedure;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Validates if a practitioner can perform a procedure based on certification requirements.
|
|
463
|
+
*
|
|
464
|
+
* @param procedure - The procedure to check
|
|
465
|
+
* @param practitioner - The practitioner to validate
|
|
466
|
+
* @returns true if practitioner can perform the procedure, false otherwise
|
|
467
|
+
*/
|
|
468
|
+
canPractitionerPerformProcedure(procedure: Procedure, practitioner: Practitioner): boolean {
|
|
469
|
+
if (!practitioner.certification) {
|
|
470
|
+
return false;
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const requiredCert = procedure.certificationRequirement;
|
|
474
|
+
const practitionerCert = practitioner.certification;
|
|
475
|
+
|
|
476
|
+
// Check certification level
|
|
477
|
+
const levelOrder = [
|
|
478
|
+
'aesthetician',
|
|
479
|
+
'nurse_assistant',
|
|
480
|
+
'nurse',
|
|
481
|
+
'nurse_practitioner',
|
|
482
|
+
'physician_assistant',
|
|
483
|
+
'doctor',
|
|
484
|
+
'specialist',
|
|
485
|
+
'plastic_surgeon',
|
|
486
|
+
];
|
|
487
|
+
|
|
488
|
+
const practitionerLevelIndex = levelOrder.indexOf(practitionerCert.level);
|
|
489
|
+
const requiredLevelIndex = levelOrder.indexOf(requiredCert.minimumLevel);
|
|
490
|
+
|
|
491
|
+
if (practitionerLevelIndex < requiredLevelIndex) {
|
|
492
|
+
return false;
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
// Check required specialties
|
|
496
|
+
const requiredSpecialties = requiredCert.requiredSpecialties || [];
|
|
497
|
+
if (requiredSpecialties.length > 0) {
|
|
498
|
+
const practitionerSpecialties = practitionerCert.specialties || [];
|
|
499
|
+
const hasAllRequired = requiredSpecialties.every(specialty =>
|
|
500
|
+
practitionerSpecialties.includes(specialty)
|
|
501
|
+
);
|
|
502
|
+
if (!hasAllRequired) {
|
|
503
|
+
return false;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return true;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/**
|
|
511
|
+
* Clones an existing procedure for a target practitioner.
|
|
512
|
+
* This creates a new procedure document with the same data as the source procedure,
|
|
513
|
+
* but linked to the target practitioner.
|
|
514
|
+
*
|
|
515
|
+
* @param sourceProcedureId - The ID of the procedure to clone
|
|
516
|
+
* @param targetPractitionerId - The ID of the practitioner to assign the cloned procedure to
|
|
517
|
+
* @param overrides - Optional overrides for the new procedure (e.g. price, duration, isActive)
|
|
518
|
+
* @returns The newly created procedure
|
|
519
|
+
*/
|
|
520
|
+
async cloneProcedureForPractitioner(
|
|
521
|
+
sourceProcedureId: string,
|
|
522
|
+
targetPractitionerId: string,
|
|
523
|
+
overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
|
|
524
|
+
): Promise<Procedure> {
|
|
525
|
+
// 1. Fetch source procedure
|
|
526
|
+
const sourceProcedure = await this.getProcedure(sourceProcedureId);
|
|
527
|
+
if (!sourceProcedure) {
|
|
528
|
+
throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// 2. Fetch target practitioner
|
|
532
|
+
const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, targetPractitionerId);
|
|
533
|
+
const practitionerSnapshot = await getDoc(practitionerRef);
|
|
534
|
+
if (!practitionerSnapshot.exists()) {
|
|
535
|
+
throw new Error(`Target practitioner with ID ${targetPractitionerId} not found`);
|
|
536
|
+
}
|
|
537
|
+
const practitioner = practitionerSnapshot.data() as Practitioner;
|
|
538
|
+
|
|
539
|
+
// 3. Validate certification
|
|
540
|
+
if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
|
|
541
|
+
throw new Error(
|
|
542
|
+
`Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// 4. Check if practitioner already has a procedure with the same technology ID in this clinic branch
|
|
547
|
+
const existingProceduresQuery = query(
|
|
548
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
549
|
+
where('practitionerId', '==', targetPractitionerId),
|
|
550
|
+
where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
|
|
551
|
+
where('isActive', '==', true)
|
|
552
|
+
);
|
|
553
|
+
const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
|
|
554
|
+
const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
|
|
555
|
+
|
|
556
|
+
const hasSameTechnology = existingProcedures.some(
|
|
557
|
+
proc => proc.technology?.id === sourceProcedure.technology?.id
|
|
558
|
+
);
|
|
559
|
+
if (hasSameTechnology) {
|
|
560
|
+
throw new Error(
|
|
561
|
+
`Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceProcedure.technology?.id}" in this clinic branch`
|
|
562
|
+
);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
// 5. Prepare data for new procedure
|
|
566
|
+
const newProcedureId = this.generateId();
|
|
567
|
+
|
|
568
|
+
// Create aggregated doctor info for the new procedure
|
|
569
|
+
const doctorInfo = {
|
|
570
|
+
id: practitioner.id,
|
|
571
|
+
name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
|
|
572
|
+
description: practitioner.basicInfo.bio || '',
|
|
573
|
+
photo:
|
|
574
|
+
typeof practitioner.basicInfo.profileImageUrl === 'string'
|
|
575
|
+
? practitioner.basicInfo.profileImageUrl
|
|
576
|
+
: '',
|
|
577
|
+
rating: practitioner.reviewInfo?.averageRating || 0,
|
|
578
|
+
services: practitioner.procedures || [],
|
|
579
|
+
};
|
|
580
|
+
|
|
581
|
+
// Construct the new procedure object
|
|
582
|
+
// We copy everything from source, but override specific fields
|
|
583
|
+
const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
|
|
584
|
+
...sourceProcedure,
|
|
585
|
+
id: newProcedureId,
|
|
586
|
+
practitionerId: targetPractitionerId,
|
|
587
|
+
doctorInfo, // Link to new doctor
|
|
588
|
+
|
|
589
|
+
// Reset review info for the new procedure
|
|
590
|
+
reviewInfo: {
|
|
591
|
+
totalReviews: 0,
|
|
592
|
+
averageRating: 0,
|
|
593
|
+
effectivenessOfTreatment: 0,
|
|
594
|
+
outcomeExplanation: 0,
|
|
595
|
+
painManagement: 0,
|
|
596
|
+
followUpCare: 0,
|
|
597
|
+
valueForMoney: 0,
|
|
598
|
+
recommendationPercentage: 0,
|
|
599
|
+
},
|
|
600
|
+
|
|
601
|
+
// Apply any overrides if provided
|
|
602
|
+
...(overrides?.price !== undefined && { price: overrides.price }),
|
|
603
|
+
...(overrides?.duration !== undefined && { duration: overrides.duration }),
|
|
604
|
+
...(overrides?.description !== undefined && { description: overrides.description }),
|
|
605
|
+
|
|
606
|
+
// Ensure it's active by default unless specified otherwise
|
|
607
|
+
isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
|
|
608
|
+
};
|
|
609
|
+
|
|
610
|
+
// 6. Save to Firestore
|
|
611
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
|
|
612
|
+
await setDoc(procedureRef, {
|
|
613
|
+
...newProcedure,
|
|
614
|
+
createdAt: serverTimestamp(),
|
|
615
|
+
updatedAt: serverTimestamp(),
|
|
616
|
+
});
|
|
617
|
+
|
|
618
|
+
// 7. Return the new procedure
|
|
619
|
+
const savedDoc = await getDoc(procedureRef);
|
|
620
|
+
return savedDoc.data() as Procedure;
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
/**
|
|
624
|
+
* Clones an existing procedure for multiple target practitioners.
|
|
625
|
+
* This creates new procedure documents with the same data as the source procedure,
|
|
626
|
+
* but linked to each target practitioner.
|
|
627
|
+
*
|
|
628
|
+
* @param sourceProcedureId - The ID of the procedure to clone
|
|
629
|
+
* @param targetPractitionerIds - Array of practitioner IDs to assign the cloned procedure to
|
|
630
|
+
* @param overrides - Optional overrides for the new procedures (e.g. price, duration, isActive)
|
|
631
|
+
* @returns Array of newly created procedures
|
|
632
|
+
*/
|
|
633
|
+
async bulkCloneProcedureForPractitioners(
|
|
634
|
+
sourceProcedureId: string,
|
|
635
|
+
targetPractitionerIds: string[],
|
|
636
|
+
overrides?: Partial<CreateProcedureData> & { isActive?: boolean }
|
|
637
|
+
): Promise<Procedure[]> {
|
|
638
|
+
if (!targetPractitionerIds || targetPractitionerIds.length === 0) {
|
|
639
|
+
throw new Error('At least one target practitioner ID is required');
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// 1. Fetch source procedure
|
|
643
|
+
const sourceProcedure = await this.getProcedure(sourceProcedureId);
|
|
644
|
+
if (!sourceProcedure) {
|
|
645
|
+
throw new Error(`Source procedure with ID ${sourceProcedureId} not found`);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// 2. Fetch all target practitioners
|
|
649
|
+
const practitionerPromises = targetPractitionerIds.map(id =>
|
|
650
|
+
getDoc(doc(this.db, PRACTITIONERS_COLLECTION, id))
|
|
651
|
+
);
|
|
652
|
+
const practitionerSnapshots = await Promise.all(practitionerPromises);
|
|
653
|
+
|
|
654
|
+
// 3. Validate all practitioners exist, can perform the procedure, and don't already have the same technology
|
|
655
|
+
const practitioners: Practitioner[] = [];
|
|
656
|
+
const sourceTechnologyId = sourceProcedure.technology?.id;
|
|
657
|
+
|
|
658
|
+
for (let i = 0; i < practitionerSnapshots.length; i++) {
|
|
659
|
+
const snapshot = practitionerSnapshots[i];
|
|
660
|
+
if (!snapshot.exists()) {
|
|
661
|
+
throw new Error(`Target practitioner with ID ${targetPractitionerIds[i]} not found`);
|
|
662
|
+
}
|
|
663
|
+
const practitioner = snapshot.data() as Practitioner;
|
|
664
|
+
|
|
665
|
+
if (!this.canPractitionerPerformProcedure(sourceProcedure, practitioner)) {
|
|
666
|
+
throw new Error(
|
|
667
|
+
`Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} does not meet the certification requirements for this procedure`
|
|
668
|
+
);
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// Check if practitioner already has a procedure with the same technology ID in this clinic branch
|
|
672
|
+
const existingProceduresQuery = query(
|
|
673
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
674
|
+
where('practitionerId', '==', practitioner.id),
|
|
675
|
+
where('clinicBranchId', '==', sourceProcedure.clinicBranchId),
|
|
676
|
+
where('isActive', '==', true)
|
|
677
|
+
);
|
|
678
|
+
const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
|
|
679
|
+
const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
|
|
680
|
+
|
|
681
|
+
const hasSameTechnology = existingProcedures.some(
|
|
682
|
+
proc => proc.technology?.id === sourceTechnologyId
|
|
683
|
+
);
|
|
684
|
+
if (hasSameTechnology) {
|
|
685
|
+
throw new Error(
|
|
686
|
+
`Practitioner ${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName} already has a procedure with technology "${sourceProcedure.technology?.name || sourceTechnologyId}" in this clinic branch`
|
|
687
|
+
);
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
practitioners.push(practitioner);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
// 4. Create procedures in batch
|
|
694
|
+
const batch = writeBatch(this.db);
|
|
695
|
+
const newProcedures: Omit<Procedure, 'createdAt' | 'updatedAt'>[] = [];
|
|
696
|
+
|
|
697
|
+
for (const practitioner of practitioners) {
|
|
698
|
+
const newProcedureId = this.generateId();
|
|
699
|
+
|
|
700
|
+
// Create aggregated doctor info for the new procedure
|
|
701
|
+
const doctorInfo = {
|
|
702
|
+
id: practitioner.id,
|
|
703
|
+
name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
|
|
704
|
+
description: practitioner.basicInfo.bio || '',
|
|
705
|
+
photo:
|
|
706
|
+
typeof practitioner.basicInfo.profileImageUrl === 'string'
|
|
707
|
+
? practitioner.basicInfo.profileImageUrl
|
|
708
|
+
: '',
|
|
709
|
+
rating: practitioner.reviewInfo?.averageRating || 0,
|
|
710
|
+
services: practitioner.procedures || [],
|
|
711
|
+
};
|
|
712
|
+
|
|
713
|
+
// Construct the new procedure object
|
|
714
|
+
const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
|
|
715
|
+
...sourceProcedure,
|
|
716
|
+
id: newProcedureId,
|
|
717
|
+
practitionerId: practitioner.id,
|
|
718
|
+
doctorInfo,
|
|
719
|
+
|
|
720
|
+
// Reset review info for the new procedure
|
|
721
|
+
reviewInfo: {
|
|
722
|
+
totalReviews: 0,
|
|
723
|
+
averageRating: 0,
|
|
724
|
+
effectivenessOfTreatment: 0,
|
|
725
|
+
outcomeExplanation: 0,
|
|
726
|
+
painManagement: 0,
|
|
727
|
+
followUpCare: 0,
|
|
728
|
+
valueForMoney: 0,
|
|
729
|
+
recommendationPercentage: 0,
|
|
730
|
+
},
|
|
731
|
+
|
|
732
|
+
// Apply any overrides if provided
|
|
733
|
+
...(overrides?.price !== undefined && { price: overrides.price }),
|
|
734
|
+
...(overrides?.duration !== undefined && { duration: overrides.duration }),
|
|
735
|
+
...(overrides?.description !== undefined && { description: overrides.description }),
|
|
736
|
+
|
|
737
|
+
// Ensure it's active by default unless specified otherwise
|
|
738
|
+
isActive: overrides?.isActive !== undefined ? overrides.isActive : true,
|
|
739
|
+
};
|
|
740
|
+
|
|
741
|
+
newProcedures.push(newProcedure);
|
|
742
|
+
|
|
743
|
+
// Add to batch
|
|
744
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, newProcedureId);
|
|
745
|
+
batch.set(procedureRef, {
|
|
746
|
+
...newProcedure,
|
|
747
|
+
createdAt: serverTimestamp(),
|
|
748
|
+
updatedAt: serverTimestamp(),
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
// 5. Commit batch
|
|
753
|
+
await batch.commit();
|
|
754
|
+
|
|
755
|
+
// 6. Fetch and return the created procedures
|
|
756
|
+
const createdProcedures = await Promise.all(
|
|
757
|
+
newProcedures.map(p => this.getProcedure(p.id))
|
|
758
|
+
);
|
|
759
|
+
|
|
760
|
+
return createdProcedures.filter((p): p is Procedure => p !== null);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Creates multiple procedures for a list of practitioners based on common data.
|
|
765
|
+
* This method is optimized for bulk creation to reduce database reads and writes.
|
|
766
|
+
*
|
|
767
|
+
* @param baseData - The base data for the procedures to be created, omitting the practitionerId.
|
|
768
|
+
* @param practitionerIds - An array of practitioner IDs for whom the procedures will be created.
|
|
769
|
+
* @returns A promise that resolves to an array of the newly created procedures.
|
|
770
|
+
*/
|
|
771
|
+
async bulkCreateProcedures(
|
|
772
|
+
baseData: Omit<CreateProcedureData, 'practitionerId'>,
|
|
773
|
+
practitionerIds: string[],
|
|
774
|
+
): Promise<Procedure[]> {
|
|
775
|
+
// 1. Validation
|
|
776
|
+
if (!practitionerIds || practitionerIds.length === 0) {
|
|
777
|
+
throw new Error('Practitioner IDs array cannot be empty.');
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
// Check if this is a product-free procedure
|
|
781
|
+
const isProductFree = !baseData.productId;
|
|
782
|
+
|
|
783
|
+
// Add a dummy practitionerId for the validation schema to pass
|
|
784
|
+
const validationData = { ...baseData, practitionerId: practitionerIds[0] };
|
|
785
|
+
const validatedData = createProcedureSchema.parse(validationData);
|
|
786
|
+
|
|
787
|
+
// 2. Fetch common data once to avoid redundant reads
|
|
788
|
+
const baseEntitiesPromises: Promise<Category | Subcategory | Technology | Product | null>[] = [
|
|
789
|
+
this.categoryService.getById(validatedData.categoryId),
|
|
790
|
+
this.subcategoryService.getById(validatedData.categoryId, validatedData.subcategoryId),
|
|
791
|
+
this.technologyService.getById(validatedData.technologyId),
|
|
792
|
+
];
|
|
793
|
+
|
|
794
|
+
// Only fetch product if productId is provided
|
|
795
|
+
if (!isProductFree) {
|
|
796
|
+
baseEntitiesPromises.push(
|
|
797
|
+
this.productService.getById(validatedData.technologyId, validatedData.productId!)
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// Fetch clinic separately to maintain type safety
|
|
802
|
+
const clinicSnapshotPromise = getDoc(doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId));
|
|
803
|
+
|
|
804
|
+
const [baseResults, clinicSnapshot] = await Promise.all([
|
|
805
|
+
Promise.all(baseEntitiesPromises),
|
|
806
|
+
clinicSnapshotPromise
|
|
807
|
+
]);
|
|
808
|
+
|
|
809
|
+
const category = baseResults[0] as Category | null;
|
|
810
|
+
const subcategory = baseResults[1] as Subcategory | null;
|
|
811
|
+
const technology = baseResults[2] as Technology | null;
|
|
812
|
+
const product = isProductFree ? undefined : ((baseResults[3] as Product | null) || undefined);
|
|
813
|
+
|
|
814
|
+
if (!category || !subcategory || !technology) {
|
|
815
|
+
throw new Error('One or more required base entities not found');
|
|
816
|
+
}
|
|
817
|
+
|
|
818
|
+
// For regular procedures, validate product exists
|
|
819
|
+
if (!isProductFree && !product) {
|
|
820
|
+
throw new Error('Product not found for regular procedure');
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
if (!clinicSnapshot || !clinicSnapshot.exists()) {
|
|
824
|
+
throw new Error(`Clinic with ID ${validatedData.clinicBranchId} not found`);
|
|
825
|
+
}
|
|
826
|
+
const clinic = clinicSnapshot.data() as Clinic;
|
|
827
|
+
|
|
828
|
+
// 3. Handle media uploads once for efficiency
|
|
829
|
+
let processedPhotos: string[] = [];
|
|
830
|
+
if (validatedData.photos && validatedData.photos.length > 0) {
|
|
831
|
+
const batchId = this.generateId(); // Use a single ID for all media in this batch
|
|
832
|
+
processedPhotos = await this.processMediaArray(
|
|
833
|
+
validatedData.photos,
|
|
834
|
+
batchId,
|
|
835
|
+
'procedure-photos-batch',
|
|
836
|
+
);
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// If no photos provided and technology has a photoTemplate, use it as default photo
|
|
840
|
+
if (processedPhotos.length === 0 && technology.photoTemplate) {
|
|
841
|
+
console.log(`[ProcedureService] Using technology photoTemplate as default photo for bulk create: ${technology.photoTemplate}`);
|
|
842
|
+
const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
|
|
843
|
+
if (photoTemplateUrl) {
|
|
844
|
+
processedPhotos.push(photoTemplateUrl);
|
|
845
|
+
} else {
|
|
846
|
+
console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
// Transform productsMetadata from validation format to ProcedureProduct format
|
|
851
|
+
const transformedProductsMetadata = await this.transformProductsMetadata(
|
|
852
|
+
validatedData.productsMetadata,
|
|
853
|
+
validatedData.technologyId,
|
|
854
|
+
);
|
|
855
|
+
|
|
856
|
+
// 4. Fetch all practitioner data efficiently
|
|
857
|
+
const practitionersMap = new Map<string, Practitioner>();
|
|
858
|
+
// Use 'in' query in chunks of 30, as this is the Firestore limit
|
|
859
|
+
for (let i = 0; i < practitionerIds.length; i += 30) {
|
|
860
|
+
const chunk = practitionerIds.slice(i, i + 30);
|
|
861
|
+
const practitionersQuery = query(
|
|
862
|
+
collection(this.db, PRACTITIONERS_COLLECTION),
|
|
863
|
+
where(documentId(), 'in', chunk),
|
|
864
|
+
);
|
|
865
|
+
const practitionersSnapshot = await getDocs(practitionersQuery);
|
|
866
|
+
practitionersSnapshot.docs.forEach(doc => {
|
|
867
|
+
practitionersMap.set(doc.id, doc.data() as Practitioner);
|
|
868
|
+
});
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
// Verify all practitioners were found
|
|
872
|
+
if (practitionersMap.size !== practitionerIds.length) {
|
|
873
|
+
const foundIds = Array.from(practitionersMap.keys());
|
|
874
|
+
const notFoundIds = practitionerIds.filter(id => !foundIds.includes(id));
|
|
875
|
+
throw new Error(`The following practitioners were not found: ${notFoundIds.join(', ')}`);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// 5. Check for duplicates across all practitioners before creating any procedures
|
|
879
|
+
const duplicatePractitioners: string[] = [];
|
|
880
|
+
const duplicateChecks = await Promise.all(
|
|
881
|
+
practitionerIds.map(async (practitionerId) => {
|
|
882
|
+
const existingProceduresQuery = query(
|
|
883
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
884
|
+
where('practitionerId', '==', practitionerId),
|
|
885
|
+
where('clinicBranchId', '==', validatedData.clinicBranchId),
|
|
886
|
+
where('isActive', '==', true)
|
|
887
|
+
);
|
|
888
|
+
const existingProceduresSnapshot = await getDocs(existingProceduresQuery);
|
|
889
|
+
const existingProcedures = existingProceduresSnapshot.docs.map(doc => doc.data() as Procedure);
|
|
890
|
+
|
|
891
|
+
const hasSameTechnology = existingProcedures.some(
|
|
892
|
+
proc => proc.technology?.id === validatedData.technologyId
|
|
893
|
+
);
|
|
894
|
+
|
|
895
|
+
return { practitionerId, hasSameTechnology };
|
|
896
|
+
})
|
|
897
|
+
);
|
|
898
|
+
|
|
899
|
+
// Collect all practitioners with duplicates
|
|
900
|
+
duplicateChecks.forEach(({ practitionerId, hasSameTechnology }) => {
|
|
901
|
+
if (hasSameTechnology) {
|
|
902
|
+
duplicatePractitioners.push(practitionerId);
|
|
903
|
+
}
|
|
904
|
+
});
|
|
905
|
+
|
|
906
|
+
// If any duplicates found, throw error listing all of them
|
|
907
|
+
if (duplicatePractitioners.length > 0) {
|
|
908
|
+
const duplicateNames = duplicatePractitioners
|
|
909
|
+
.map(id => {
|
|
910
|
+
const practitioner = practitionersMap.get(id)!;
|
|
911
|
+
return `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`;
|
|
912
|
+
})
|
|
913
|
+
.join(', ');
|
|
914
|
+
|
|
915
|
+
throw new Error(
|
|
916
|
+
`The following practitioner(s) already have a procedure with technology "${technology?.name || validatedData.technologyId}" in this clinic branch: ${duplicateNames}. Please remove them from the selection and try again.`
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// 6. Use a Firestore batch for atomic creation
|
|
921
|
+
const batch = writeBatch(this.db);
|
|
922
|
+
const createdProcedureIds: string[] = [];
|
|
923
|
+
const clinicInfo = {
|
|
924
|
+
id: clinicSnapshot.id,
|
|
925
|
+
name: clinic.name,
|
|
926
|
+
description: clinic.description || '',
|
|
927
|
+
featuredPhoto:
|
|
928
|
+
clinic.featuredPhotos && clinic.featuredPhotos.length > 0
|
|
929
|
+
? typeof clinic.featuredPhotos[0] === 'string'
|
|
930
|
+
? clinic.featuredPhotos[0]
|
|
931
|
+
: ''
|
|
932
|
+
: typeof clinic.coverPhoto === 'string'
|
|
933
|
+
? clinic.coverPhoto
|
|
934
|
+
: '',
|
|
935
|
+
location: clinic.location,
|
|
936
|
+
contactInfo: clinic.contactInfo,
|
|
937
|
+
};
|
|
938
|
+
|
|
939
|
+
for (const practitionerId of practitionerIds) {
|
|
940
|
+
const practitioner = practitionersMap.get(practitionerId)!;
|
|
941
|
+
|
|
942
|
+
const doctorInfo = {
|
|
943
|
+
id: practitioner.id,
|
|
944
|
+
name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
|
|
945
|
+
description: practitioner.basicInfo.bio || '',
|
|
946
|
+
photo:
|
|
947
|
+
typeof practitioner.basicInfo.profileImageUrl === 'string'
|
|
948
|
+
? practitioner.basicInfo.profileImageUrl
|
|
949
|
+
: '',
|
|
950
|
+
rating: practitioner.reviewInfo?.averageRating || 0,
|
|
951
|
+
services: practitioner.procedures || [],
|
|
952
|
+
};
|
|
953
|
+
|
|
954
|
+
const procedureId = this.generateId();
|
|
955
|
+
createdProcedureIds.push(procedureId);
|
|
956
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
|
|
957
|
+
|
|
958
|
+
// Construct the new procedure, reusing common data
|
|
959
|
+
const { productsMetadata: _, productId: __, photos: ___, ...validatedDataWithoutProductsMetadata } = validatedData;
|
|
960
|
+
const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
|
|
961
|
+
id: procedureId,
|
|
962
|
+
...validatedDataWithoutProductsMetadata,
|
|
963
|
+
nameLower: (validatedData as any).nameLower || validatedData.name.toLowerCase(),
|
|
964
|
+
practitionerId: practitionerId, // Override practitionerId with the correct one
|
|
965
|
+
photos: processedPhotos,
|
|
966
|
+
category,
|
|
967
|
+
subcategory,
|
|
968
|
+
technology,
|
|
969
|
+
...(product && { product }), // Only include product field if it exists (Firestore doesn't allow undefined)
|
|
970
|
+
productsMetadata: transformedProductsMetadata, // Use transformed data, not original
|
|
971
|
+
blockingConditions: technology.blockingConditions,
|
|
972
|
+
contraindications: technology.contraindications || [],
|
|
973
|
+
contraindicationIds: technology.contraindications?.map(c => c.id) || [],
|
|
974
|
+
treatmentBenefits: technology.benefits,
|
|
975
|
+
treatmentBenefitIds: Array.isArray(technology.benefits)
|
|
976
|
+
? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
|
|
977
|
+
: [],
|
|
978
|
+
preRequirements: technology.requirements.pre,
|
|
979
|
+
postRequirements: technology.requirements.post,
|
|
980
|
+
certificationRequirement: technology.certificationRequirement,
|
|
981
|
+
documentationTemplates: technology?.documentationTemplates || [],
|
|
982
|
+
clinicInfo,
|
|
983
|
+
doctorInfo, // Set specific doctor info
|
|
984
|
+
reviewInfo: {
|
|
985
|
+
totalReviews: 0,
|
|
986
|
+
averageRating: 0,
|
|
987
|
+
effectivenessOfTreatment: 0,
|
|
988
|
+
outcomeExplanation: 0,
|
|
989
|
+
painManagement: 0,
|
|
990
|
+
followUpCare: 0,
|
|
991
|
+
valueForMoney: 0,
|
|
992
|
+
recommendationPercentage: 0,
|
|
993
|
+
},
|
|
994
|
+
isActive: true,
|
|
995
|
+
};
|
|
996
|
+
|
|
997
|
+
// 🔥 DEBUG: Find undefined fields before writing to Firestore
|
|
998
|
+
console.log('🔥🔥🔥 BULK CREATE - Processing procedure:', procedureId, 'for practitioner:', practitionerId);
|
|
999
|
+
console.log('🔥🔥🔥 FULL PROCEDURE OBJECT:', JSON.stringify(newProcedure, null, 2));
|
|
1000
|
+
|
|
1001
|
+
const undefinedFields: string[] = [];
|
|
1002
|
+
Object.entries(newProcedure).forEach(([key, value]) => {
|
|
1003
|
+
if (value === undefined) {
|
|
1004
|
+
undefinedFields.push(key);
|
|
1005
|
+
}
|
|
1006
|
+
});
|
|
1007
|
+
if (undefinedFields.length > 0) {
|
|
1008
|
+
console.error('🔥🔥🔥 UNDEFINED FIELDS DETECTED:', undefinedFields);
|
|
1009
|
+
throw new Error(`Cannot write procedure with undefined fields: ${undefinedFields.join(', ')}`);
|
|
1010
|
+
}
|
|
1011
|
+
console.log('🔥🔥🔥 NO UNDEFINED FIELDS - Proceeding with batch.set');
|
|
1012
|
+
|
|
1013
|
+
batch.set(procedureRef, {
|
|
1014
|
+
...newProcedure,
|
|
1015
|
+
createdAt: serverTimestamp(),
|
|
1016
|
+
updatedAt: serverTimestamp(),
|
|
1017
|
+
});
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
// 7. Commit the atomic batch write
|
|
1021
|
+
await batch.commit();
|
|
1022
|
+
|
|
1023
|
+
// 8. Fetch and return the newly created procedures
|
|
1024
|
+
const fetchedProcedures: Procedure[] = [];
|
|
1025
|
+
for (let i = 0; i < createdProcedureIds.length; i += 30) {
|
|
1026
|
+
const chunk = createdProcedureIds.slice(i, i + 30);
|
|
1027
|
+
const q = query(collection(this.db, PROCEDURES_COLLECTION), where(documentId(), 'in', chunk));
|
|
1028
|
+
const snapshot = await getDocs(q);
|
|
1029
|
+
snapshot.forEach(doc => {
|
|
1030
|
+
fetchedProcedures.push(doc.data() as Procedure);
|
|
1031
|
+
});
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
return fetchedProcedures;
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
/**
|
|
1038
|
+
* Gets a procedure by ID
|
|
1039
|
+
* @param id - The ID of the procedure to get
|
|
1040
|
+
* @returns The procedure if found, null otherwise
|
|
1041
|
+
*/
|
|
1042
|
+
async getProcedure(id: string): Promise<Procedure | null> {
|
|
1043
|
+
const docRef = doc(this.db, PROCEDURES_COLLECTION, id);
|
|
1044
|
+
const docSnap = await getDoc(docRef);
|
|
1045
|
+
|
|
1046
|
+
if (!docSnap.exists()) {
|
|
1047
|
+
return null;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
return docSnap.data() as Procedure;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/**
|
|
1054
|
+
* Gets all procedures for a clinic branch
|
|
1055
|
+
* @param clinicBranchId - The ID of the clinic branch
|
|
1056
|
+
* @returns List of procedures
|
|
1057
|
+
*/
|
|
1058
|
+
async getProceduresByClinicBranch(clinicBranchId: string): Promise<Procedure[]> {
|
|
1059
|
+
const q = query(
|
|
1060
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
1061
|
+
where('clinicBranchId', '==', clinicBranchId),
|
|
1062
|
+
where('isActive', '==', true),
|
|
1063
|
+
);
|
|
1064
|
+
const snapshot = await getDocs(q);
|
|
1065
|
+
return snapshot.docs.map(doc => doc.data() as Procedure);
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Gets all procedures for a practitioner
|
|
1070
|
+
* @param practitionerId - The ID of the practitioner
|
|
1071
|
+
* @param clinicBranchId - Optional clinic branch ID to filter by
|
|
1072
|
+
* @param excludeDraftPractitioners - Whether to exclude procedures if the practitioner is in DRAFT status
|
|
1073
|
+
* @returns List of procedures
|
|
1074
|
+
*/
|
|
1075
|
+
async getProceduresByPractitioner(
|
|
1076
|
+
practitionerId: string,
|
|
1077
|
+
clinicBranchId?: string,
|
|
1078
|
+
excludeDraftPractitioners: boolean = true
|
|
1079
|
+
): Promise<Procedure[]> {
|
|
1080
|
+
const constraints: QueryConstraint[] = [
|
|
1081
|
+
where('practitionerId', '==', practitionerId),
|
|
1082
|
+
where('isActive', '==', true),
|
|
1083
|
+
];
|
|
1084
|
+
|
|
1085
|
+
if (clinicBranchId) {
|
|
1086
|
+
constraints.push(where('clinicBranchId', '==', clinicBranchId));
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
const q = query(
|
|
1090
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
1091
|
+
...constraints
|
|
1092
|
+
);
|
|
1093
|
+
const snapshot = await getDocs(q);
|
|
1094
|
+
const procedures = snapshot.docs.map(doc => doc.data() as Procedure);
|
|
1095
|
+
|
|
1096
|
+
// If we need to exclude draft practitioners and have the service available
|
|
1097
|
+
if (excludeDraftPractitioners && this.practitionerService) {
|
|
1098
|
+
try {
|
|
1099
|
+
const practitioner = await this.practitionerService.getPractitioner(practitionerId);
|
|
1100
|
+
if (practitioner && practitioner.status === PractitionerStatus.DRAFT) {
|
|
1101
|
+
console.log(`[ProcedureService] Excluding procedures for draft practitioner ${practitionerId}`);
|
|
1102
|
+
return [];
|
|
1103
|
+
}
|
|
1104
|
+
} catch (error) {
|
|
1105
|
+
console.error(`[ProcedureService] Error checking practitioner status for ${practitionerId}:`, error);
|
|
1106
|
+
// On error, default to returning procedures to avoid breaking UI
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
return procedures;
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
/**
|
|
1114
|
+
* Gets all inactive procedures for a practitioner
|
|
1115
|
+
* @param practitionerId - The ID of the practitioner
|
|
1116
|
+
* @returns List of inactive procedures
|
|
1117
|
+
*/
|
|
1118
|
+
async getInactiveProceduresByPractitioner(practitionerId: string): Promise<Procedure[]> {
|
|
1119
|
+
const q = query(
|
|
1120
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
1121
|
+
where('practitionerId', '==', practitionerId),
|
|
1122
|
+
where('isActive', '==', false),
|
|
1123
|
+
);
|
|
1124
|
+
const snapshot = await getDocs(q);
|
|
1125
|
+
return snapshot.docs.map(doc => doc.data() as Procedure);
|
|
1126
|
+
}
|
|
1127
|
+
|
|
1128
|
+
/**
|
|
1129
|
+
* Updates a procedure
|
|
1130
|
+
* @param id - The ID of the procedure to update
|
|
1131
|
+
* @param data - The data to update the procedure with
|
|
1132
|
+
* @returns The updated procedure
|
|
1133
|
+
*/
|
|
1134
|
+
async updateProcedure(id: string, data: UpdateProcedureData): Promise<Procedure> {
|
|
1135
|
+
const validatedData = updateProcedureSchema.parse(data);
|
|
1136
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
|
|
1137
|
+
const procedureSnapshot = await getDoc(procedureRef);
|
|
1138
|
+
|
|
1139
|
+
if (!procedureSnapshot.exists()) {
|
|
1140
|
+
throw new Error(`Procedure with ID ${id} not found`);
|
|
1141
|
+
}
|
|
1142
|
+
|
|
1143
|
+
const existingProcedure = procedureSnapshot.data() as Procedure;
|
|
1144
|
+
let updatedProcedureData: Partial<Procedure> = {};
|
|
1145
|
+
|
|
1146
|
+
// Copy validated simple fields
|
|
1147
|
+
if (validatedData.name !== undefined) updatedProcedureData.name = validatedData.name;
|
|
1148
|
+
if (validatedData.description !== undefined)
|
|
1149
|
+
updatedProcedureData.description = validatedData.description;
|
|
1150
|
+
if (validatedData.price !== undefined) updatedProcedureData.price = validatedData.price;
|
|
1151
|
+
if (validatedData.currency !== undefined)
|
|
1152
|
+
updatedProcedureData.currency = validatedData.currency;
|
|
1153
|
+
if (validatedData.pricingMeasure !== undefined)
|
|
1154
|
+
updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
|
|
1155
|
+
if (validatedData.duration !== undefined)
|
|
1156
|
+
updatedProcedureData.duration = validatedData.duration;
|
|
1157
|
+
if (validatedData.isActive !== undefined)
|
|
1158
|
+
updatedProcedureData.isActive = validatedData.isActive;
|
|
1159
|
+
|
|
1160
|
+
let practitionerChanged = false;
|
|
1161
|
+
let clinicChanged = false;
|
|
1162
|
+
const oldPractitionerId = existingProcedure.practitionerId;
|
|
1163
|
+
const oldClinicId = existingProcedure.clinicBranchId;
|
|
1164
|
+
let newPractitioner: Practitioner | null = null;
|
|
1165
|
+
let newClinic: Clinic | null = null;
|
|
1166
|
+
|
|
1167
|
+
// Process photos if provided
|
|
1168
|
+
if (validatedData.photos !== undefined) {
|
|
1169
|
+
updatedProcedureData.photos = await this.processMediaArray(
|
|
1170
|
+
validatedData.photos,
|
|
1171
|
+
id,
|
|
1172
|
+
'procedure-photos',
|
|
1173
|
+
);
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
// Transform productsMetadata if provided
|
|
1177
|
+
if (validatedData.productsMetadata !== undefined) {
|
|
1178
|
+
const technologyId = validatedData.technologyId ?? existingProcedure.technology.id;
|
|
1179
|
+
if (!technologyId) {
|
|
1180
|
+
throw new Error('Technology ID is required for updating products metadata');
|
|
1181
|
+
}
|
|
1182
|
+
updatedProcedureData.productsMetadata = await this.transformProductsMetadata(
|
|
1183
|
+
validatedData.productsMetadata,
|
|
1184
|
+
technologyId,
|
|
1185
|
+
);
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
// --- Prepare updates and fetch new related data if IDs change ---
|
|
1189
|
+
|
|
1190
|
+
// Handle Practitioner Change
|
|
1191
|
+
if (validatedData.practitionerId && validatedData.practitionerId !== oldPractitionerId) {
|
|
1192
|
+
practitionerChanged = true;
|
|
1193
|
+
const newPractitionerRef = doc(
|
|
1194
|
+
this.db,
|
|
1195
|
+
PRACTITIONERS_COLLECTION,
|
|
1196
|
+
validatedData.practitionerId,
|
|
1197
|
+
);
|
|
1198
|
+
const newPractitionerSnap = await getDoc(newPractitionerRef);
|
|
1199
|
+
if (!newPractitionerSnap.exists())
|
|
1200
|
+
throw new Error(`New Practitioner ${validatedData.practitionerId} not found`);
|
|
1201
|
+
newPractitioner = newPractitionerSnap.data() as Practitioner;
|
|
1202
|
+
// Update doctorInfo within the procedure document
|
|
1203
|
+
updatedProcedureData.doctorInfo = {
|
|
1204
|
+
id: newPractitioner.id,
|
|
1205
|
+
name: `${newPractitioner.basicInfo.firstName} ${newPractitioner.basicInfo.lastName}`,
|
|
1206
|
+
description: newPractitioner.basicInfo.bio || '',
|
|
1207
|
+
photo:
|
|
1208
|
+
typeof newPractitioner.basicInfo.profileImageUrl === 'string'
|
|
1209
|
+
? newPractitioner.basicInfo.profileImageUrl
|
|
1210
|
+
: '', // Default to empty string if not a processed URL
|
|
1211
|
+
rating: newPractitioner.reviewInfo?.averageRating || 0,
|
|
1212
|
+
services: newPractitioner.procedures || [],
|
|
1213
|
+
};
|
|
1214
|
+
}
|
|
1215
|
+
|
|
1216
|
+
// Handle Clinic Change
|
|
1217
|
+
if (validatedData.clinicBranchId && validatedData.clinicBranchId !== oldClinicId) {
|
|
1218
|
+
clinicChanged = true;
|
|
1219
|
+
const newClinicRef = doc(this.db, CLINICS_COLLECTION, validatedData.clinicBranchId);
|
|
1220
|
+
const newClinicSnap = await getDoc(newClinicRef);
|
|
1221
|
+
if (!newClinicSnap.exists())
|
|
1222
|
+
throw new Error(`New Clinic ${validatedData.clinicBranchId} not found`);
|
|
1223
|
+
newClinic = newClinicSnap.data() as Clinic;
|
|
1224
|
+
// Update clinicInfo within the procedure document
|
|
1225
|
+
updatedProcedureData.clinicInfo = {
|
|
1226
|
+
id: newClinic.id,
|
|
1227
|
+
name: newClinic.name,
|
|
1228
|
+
description: newClinic.description || '',
|
|
1229
|
+
featuredPhoto:
|
|
1230
|
+
newClinic.featuredPhotos && newClinic.featuredPhotos.length > 0
|
|
1231
|
+
? typeof newClinic.featuredPhotos[0] === 'string'
|
|
1232
|
+
? newClinic.featuredPhotos[0]
|
|
1233
|
+
: ''
|
|
1234
|
+
: typeof newClinic.coverPhoto === 'string'
|
|
1235
|
+
? newClinic.coverPhoto
|
|
1236
|
+
: '',
|
|
1237
|
+
location: newClinic.location,
|
|
1238
|
+
contactInfo: newClinic.contactInfo,
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1242
|
+
// Handle Category/Subcategory/Technology/Product Changes
|
|
1243
|
+
let finalCategoryId = existingProcedure.category.id;
|
|
1244
|
+
if (validatedData.name) {
|
|
1245
|
+
updatedProcedureData.nameLower = validatedData.name.toLowerCase();
|
|
1246
|
+
}
|
|
1247
|
+
if (validatedData.categoryId) {
|
|
1248
|
+
const category = await this.categoryService.getById(validatedData.categoryId);
|
|
1249
|
+
if (!category) throw new Error(`Category ${validatedData.categoryId} not found`);
|
|
1250
|
+
updatedProcedureData.category = category;
|
|
1251
|
+
finalCategoryId = category.id; // Update finalCategoryId if category changed
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
// Only fetch subcategory if its ID is provided AND we have a valid finalCategoryId
|
|
1255
|
+
if (validatedData.subcategoryId && finalCategoryId) {
|
|
1256
|
+
const subcategory = await this.subcategoryService.getById(
|
|
1257
|
+
finalCategoryId,
|
|
1258
|
+
validatedData.subcategoryId,
|
|
1259
|
+
);
|
|
1260
|
+
if (!subcategory)
|
|
1261
|
+
throw new Error(
|
|
1262
|
+
`Subcategory ${validatedData.subcategoryId} not found for category ${finalCategoryId}`,
|
|
1263
|
+
);
|
|
1264
|
+
updatedProcedureData.subcategory = subcategory;
|
|
1265
|
+
} else if (validatedData.subcategoryId) {
|
|
1266
|
+
console.warn('Attempted to update subcategory without a valid categoryId');
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
let finalTechnologyId = existingProcedure.technology.id;
|
|
1270
|
+
if (validatedData.technologyId) {
|
|
1271
|
+
const technology = await this.technologyService.getById(validatedData.technologyId);
|
|
1272
|
+
if (!technology) throw new Error(`Technology ${validatedData.technologyId} not found`);
|
|
1273
|
+
updatedProcedureData.technology = technology;
|
|
1274
|
+
finalTechnologyId = technology.id; // Update finalTechnologyId if technology changed
|
|
1275
|
+
// Update related fields derived from technology
|
|
1276
|
+
updatedProcedureData.blockingConditions = technology.blockingConditions;
|
|
1277
|
+
updatedProcedureData.contraindications = technology.contraindications || [];
|
|
1278
|
+
updatedProcedureData.contraindicationIds = technology.contraindications?.map(c => c.id) || [];
|
|
1279
|
+
updatedProcedureData.treatmentBenefits = technology.benefits;
|
|
1280
|
+
updatedProcedureData.treatmentBenefitIds = Array.isArray(technology.benefits)
|
|
1281
|
+
? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
|
|
1282
|
+
: [];
|
|
1283
|
+
updatedProcedureData.preRequirements = technology.requirements.pre;
|
|
1284
|
+
updatedProcedureData.postRequirements = technology.requirements.post;
|
|
1285
|
+
updatedProcedureData.certificationRequirement = technology.certificationRequirement;
|
|
1286
|
+
updatedProcedureData.documentationTemplates = technology.documentationTemplates || [];
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
// Only fetch product if its ID is provided AND we have a valid finalTechnologyId
|
|
1290
|
+
if (validatedData.productId && finalTechnologyId) {
|
|
1291
|
+
const product = await this.productService.getById(finalTechnologyId, validatedData.productId);
|
|
1292
|
+
if (!product)
|
|
1293
|
+
throw new Error(
|
|
1294
|
+
`Product ${validatedData.productId} not found for technology ${finalTechnologyId}`,
|
|
1295
|
+
);
|
|
1296
|
+
updatedProcedureData.product = product;
|
|
1297
|
+
} else if (validatedData.productId) {
|
|
1298
|
+
console.warn('Attempted to update product without a valid technologyId');
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
// Update the procedure document
|
|
1302
|
+
await updateDoc(procedureRef, {
|
|
1303
|
+
...updatedProcedureData,
|
|
1304
|
+
updatedAt: serverTimestamp(),
|
|
1305
|
+
});
|
|
1306
|
+
|
|
1307
|
+
// Return the updated procedure
|
|
1308
|
+
const updatedSnapshot = await getDoc(procedureRef);
|
|
1309
|
+
return updatedSnapshot.data() as Procedure;
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/**
|
|
1313
|
+
* Deactivates a procedure (soft delete)
|
|
1314
|
+
* @param id - The ID of the procedure to deactivate
|
|
1315
|
+
*/
|
|
1316
|
+
async deactivateProcedure(id: string): Promise<void> {
|
|
1317
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
|
|
1318
|
+
const procedureSnap = await getDoc(procedureRef);
|
|
1319
|
+
if (!procedureSnap.exists()) {
|
|
1320
|
+
console.warn(`Procedure ${id} not found for deactivation.`);
|
|
1321
|
+
return;
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// Mark procedure as inactive
|
|
1325
|
+
await updateDoc(procedureRef, {
|
|
1326
|
+
isActive: false,
|
|
1327
|
+
updatedAt: serverTimestamp(),
|
|
1328
|
+
});
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
/**
|
|
1332
|
+
* Deletes a procedure permanently
|
|
1333
|
+
* @param id - The ID of the procedure to delete
|
|
1334
|
+
* @returns A boolean indicating if the deletion was successful
|
|
1335
|
+
*/
|
|
1336
|
+
async deleteProcedure(id: string): Promise<boolean> {
|
|
1337
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, id);
|
|
1338
|
+
const procedureSnapshot = await getDoc(procedureRef);
|
|
1339
|
+
|
|
1340
|
+
if (!procedureSnapshot.exists()) {
|
|
1341
|
+
// Already deleted or never existed
|
|
1342
|
+
return false;
|
|
1343
|
+
}
|
|
1344
|
+
|
|
1345
|
+
// Delete the procedure document
|
|
1346
|
+
await deleteDoc(procedureRef);
|
|
1347
|
+
return true;
|
|
1348
|
+
}
|
|
1349
|
+
|
|
1350
|
+
/**
|
|
1351
|
+
* Gets all procedures that a practitioner is certified to perform
|
|
1352
|
+
* @param practitioner - The practitioner's profile
|
|
1353
|
+
* @returns Object containing allowed technologies, families, categories, subcategories
|
|
1354
|
+
*/
|
|
1355
|
+
async getAllowedTechnologies(practitioner: Practitioner): Promise<{
|
|
1356
|
+
technologies: Technology[];
|
|
1357
|
+
families: ProcedureFamily[];
|
|
1358
|
+
categories: string[];
|
|
1359
|
+
subcategories: string[];
|
|
1360
|
+
}> {
|
|
1361
|
+
// This logic depends on TechnologyService and remains valid
|
|
1362
|
+
const { technologies, families, categories, subcategories } =
|
|
1363
|
+
await this.technologyService.getAllowedTechnologies(practitioner);
|
|
1364
|
+
|
|
1365
|
+
return {
|
|
1366
|
+
technologies,
|
|
1367
|
+
families,
|
|
1368
|
+
categories,
|
|
1369
|
+
subcategories,
|
|
1370
|
+
};
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
/**
|
|
1374
|
+
* Gets all procedures with optional pagination
|
|
1375
|
+
*
|
|
1376
|
+
* @param pagination - Optional number of procedures per page (0 or undefined returns all)
|
|
1377
|
+
* @param lastDoc - Optional last document for pagination (if continuing from a previous page)
|
|
1378
|
+
* @param excludeDraftPractitioners - Whether to exclude procedures from draft practitioners (default: true)
|
|
1379
|
+
* @returns Object containing procedures array and the last document for pagination
|
|
1380
|
+
*/
|
|
1381
|
+
async getAllProcedures(
|
|
1382
|
+
pagination?: number,
|
|
1383
|
+
lastDoc?: any,
|
|
1384
|
+
excludeDraftPractitioners: boolean = true,
|
|
1385
|
+
): Promise<{ procedures: Procedure[]; lastDoc: any }> {
|
|
1386
|
+
try {
|
|
1387
|
+
const proceduresCollection = collection(this.db, PROCEDURES_COLLECTION);
|
|
1388
|
+
let proceduresQuery = query(proceduresCollection);
|
|
1389
|
+
|
|
1390
|
+
// Apply pagination if specified
|
|
1391
|
+
if (pagination && pagination > 0) {
|
|
1392
|
+
const { limit, startAfter } = await import('firebase/firestore'); // Use dynamic import if needed top-level
|
|
1393
|
+
|
|
1394
|
+
if (lastDoc) {
|
|
1395
|
+
proceduresQuery = query(
|
|
1396
|
+
proceduresCollection,
|
|
1397
|
+
orderBy('name'), // Use imported orderBy
|
|
1398
|
+
startAfter(lastDoc),
|
|
1399
|
+
limit(pagination),
|
|
1400
|
+
);
|
|
1401
|
+
} else {
|
|
1402
|
+
proceduresQuery = query(proceduresCollection, orderBy('name'), limit(pagination)); // Use imported orderBy
|
|
1403
|
+
}
|
|
1404
|
+
} else {
|
|
1405
|
+
proceduresQuery = query(proceduresCollection, orderBy('name')); // Use imported orderBy
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
const proceduresSnapshot = await getDocs(proceduresQuery);
|
|
1409
|
+
const lastVisible = proceduresSnapshot.docs[proceduresSnapshot.docs.length - 1];
|
|
1410
|
+
|
|
1411
|
+
let procedures = proceduresSnapshot.docs.map(doc => {
|
|
1412
|
+
const data = doc.data() as Procedure;
|
|
1413
|
+
return {
|
|
1414
|
+
...data,
|
|
1415
|
+
id: doc.id, // Ensure ID is present
|
|
1416
|
+
};
|
|
1417
|
+
});
|
|
1418
|
+
|
|
1419
|
+
// Filter out procedures from draft practitioners if requested
|
|
1420
|
+
if (excludeDraftPractitioners) {
|
|
1421
|
+
procedures = await this.filterDraftPractitionerProcedures(procedures);
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
return {
|
|
1425
|
+
procedures,
|
|
1426
|
+
lastDoc: lastVisible,
|
|
1427
|
+
};
|
|
1428
|
+
} catch (error) {
|
|
1429
|
+
console.error('[PROCEDURE_SERVICE] Error getting all procedures:', error);
|
|
1430
|
+
throw error;
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
/**
|
|
1435
|
+
* Searches and filters procedures based on multiple criteria
|
|
1436
|
+
*
|
|
1437
|
+
* @note Frontend MORA da šalje ceo snapshot (ili barem sva polja po kojima sortiraš, npr. nameLower) kao lastDoc za paginaciju, a ne samo id!
|
|
1438
|
+
*
|
|
1439
|
+
* @param filters - Various filters to apply
|
|
1440
|
+
* @param filters.nameSearch - Optional search text for procedure name
|
|
1441
|
+
* @param filters.treatmentBenefitIds - Optional array of treatment benefits to filter by
|
|
1442
|
+
* @param filters.procedureFamily - Optional procedure family to filter by
|
|
1443
|
+
* @param filters.procedureCategory - Optional procedure category to filter by
|
|
1444
|
+
* @param filters.procedureSubcategory - Optional procedure subcategory to filter by
|
|
1445
|
+
* @param filters.procedureTechnology - Optional procedure technology to filter by
|
|
1446
|
+
* @param filters.location - Optional location for distance-based search
|
|
1447
|
+
* @param filters.radiusInKm - Optional radius in kilometers (required if location is provided)
|
|
1448
|
+
* @param filters.minPrice - Optional minimum price
|
|
1449
|
+
* @param filters.maxPrice - Optional maximum price
|
|
1450
|
+
* @param filters.minRating - Optional minimum rating (0-5)
|
|
1451
|
+
* @param filters.maxRating - Optional maximum rating (0-5)
|
|
1452
|
+
* @param filters.pagination - Optional number of results per page
|
|
1453
|
+
* @param filters.lastDoc - Optional last document for pagination
|
|
1454
|
+
* @param filters.isActive - Optional filter for active procedures only
|
|
1455
|
+
* @returns Filtered procedures and the last document for pagination
|
|
1456
|
+
*/
|
|
1457
|
+
async getProceduresByFilters(filters: {
|
|
1458
|
+
nameSearch?: string;
|
|
1459
|
+
treatmentBenefits?: string[];
|
|
1460
|
+
procedureFamily?: ProcedureFamily;
|
|
1461
|
+
procedureCategory?: string;
|
|
1462
|
+
procedureSubcategory?: string;
|
|
1463
|
+
procedureTechnology?: string;
|
|
1464
|
+
location?: { latitude: number; longitude: number };
|
|
1465
|
+
radiusInKm?: number;
|
|
1466
|
+
minPrice?: number;
|
|
1467
|
+
maxPrice?: number;
|
|
1468
|
+
minRating?: number;
|
|
1469
|
+
maxRating?: number;
|
|
1470
|
+
pagination?: number;
|
|
1471
|
+
lastDoc?: any;
|
|
1472
|
+
isActive?: boolean;
|
|
1473
|
+
practitionerId?: string;
|
|
1474
|
+
clinicId?: string;
|
|
1475
|
+
}): Promise<{
|
|
1476
|
+
procedures: (Procedure & { distance?: number })[];
|
|
1477
|
+
lastDoc: any;
|
|
1478
|
+
}> {
|
|
1479
|
+
try {
|
|
1480
|
+
console.log('[PROCEDURE_SERVICE] Starting procedure filtering with multiple strategies');
|
|
1481
|
+
|
|
1482
|
+
// Geo query debug i validacija
|
|
1483
|
+
if (filters.location && filters.radiusInKm) {
|
|
1484
|
+
console.log('[PROCEDURE_SERVICE] Executing geo query:', {
|
|
1485
|
+
location: filters.location,
|
|
1486
|
+
radius: filters.radiusInKm,
|
|
1487
|
+
serviceName: 'ProcedureService',
|
|
1488
|
+
});
|
|
1489
|
+
|
|
1490
|
+
// Validacija location podataka
|
|
1491
|
+
if (!filters.location.latitude || !filters.location.longitude) {
|
|
1492
|
+
console.warn('[PROCEDURE_SERVICE] Invalid location data:', filters.location);
|
|
1493
|
+
filters.location = undefined;
|
|
1494
|
+
filters.radiusInKm = undefined;
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
// Handle geo queries separately (they work differently)
|
|
1499
|
+
const isGeoQuery = filters.location && filters.radiusInKm && filters.radiusInKm > 0;
|
|
1500
|
+
if (isGeoQuery) {
|
|
1501
|
+
return this.handleGeoQuery(filters);
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
// Base constraints (used in all strategies)
|
|
1505
|
+
const getBaseConstraints = () => {
|
|
1506
|
+
const constraints: QueryConstraint[] = [];
|
|
1507
|
+
|
|
1508
|
+
// Active status filter
|
|
1509
|
+
if (filters.isActive !== undefined) {
|
|
1510
|
+
constraints.push(where('isActive', '==', filters.isActive));
|
|
1511
|
+
} else {
|
|
1512
|
+
constraints.push(where('isActive', '==', true));
|
|
1513
|
+
}
|
|
1514
|
+
|
|
1515
|
+
// Filter constraints
|
|
1516
|
+
if (filters.procedureFamily) {
|
|
1517
|
+
constraints.push(where('family', '==', filters.procedureFamily));
|
|
1518
|
+
}
|
|
1519
|
+
if (filters.procedureCategory) {
|
|
1520
|
+
constraints.push(where('category.id', '==', filters.procedureCategory));
|
|
1521
|
+
}
|
|
1522
|
+
if (filters.procedureSubcategory) {
|
|
1523
|
+
constraints.push(where('subcategory.id', '==', filters.procedureSubcategory));
|
|
1524
|
+
}
|
|
1525
|
+
if (filters.procedureTechnology) {
|
|
1526
|
+
constraints.push(where('technology.id', '==', filters.procedureTechnology));
|
|
1527
|
+
}
|
|
1528
|
+
if (filters.practitionerId) {
|
|
1529
|
+
constraints.push(where('practitionerId', '==', filters.practitionerId));
|
|
1530
|
+
}
|
|
1531
|
+
if (filters.clinicId) {
|
|
1532
|
+
constraints.push(where('clinicBranchId', '==', filters.clinicId));
|
|
1533
|
+
}
|
|
1534
|
+
if (filters.minPrice !== undefined) {
|
|
1535
|
+
constraints.push(where('price', '>=', filters.minPrice));
|
|
1536
|
+
}
|
|
1537
|
+
if (filters.maxPrice !== undefined) {
|
|
1538
|
+
constraints.push(where('price', '<=', filters.maxPrice));
|
|
1539
|
+
}
|
|
1540
|
+
if (filters.minRating !== undefined) {
|
|
1541
|
+
constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
|
|
1542
|
+
}
|
|
1543
|
+
if (filters.maxRating !== undefined) {
|
|
1544
|
+
constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
|
|
1545
|
+
}
|
|
1546
|
+
if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
|
|
1547
|
+
const benefitIdsToMatch = filters.treatmentBenefits;
|
|
1548
|
+
constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
return constraints;
|
|
1552
|
+
};
|
|
1553
|
+
|
|
1554
|
+
// Strategy 1: Try nameLower search if nameSearch exists
|
|
1555
|
+
if (filters.nameSearch && filters.nameSearch.trim()) {
|
|
1556
|
+
try {
|
|
1557
|
+
console.log('[PROCEDURE_SERVICE] Strategy 1: Trying nameLower search');
|
|
1558
|
+
const searchTerm = filters.nameSearch.trim().toLowerCase();
|
|
1559
|
+
const constraints = getBaseConstraints();
|
|
1560
|
+
|
|
1561
|
+
// Check if we have nested field filters that might conflict with orderBy
|
|
1562
|
+
const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
|
|
1563
|
+
|
|
1564
|
+
if (hasNestedFilters) {
|
|
1565
|
+
console.log('[PROCEDURE_SERVICE] Strategy 1: Has nested filters, will apply client-side after query');
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
constraints.push(where('nameLower', '>=', searchTerm));
|
|
1569
|
+
constraints.push(where('nameLower', '<=', searchTerm + '\uf8ff'));
|
|
1570
|
+
constraints.push(orderBy('nameLower'));
|
|
1571
|
+
|
|
1572
|
+
if (filters.lastDoc) {
|
|
1573
|
+
if (typeof filters.lastDoc.data === 'function') {
|
|
1574
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1575
|
+
} else if (Array.isArray(filters.lastDoc)) {
|
|
1576
|
+
constraints.push(startAfter(...filters.lastDoc));
|
|
1577
|
+
} else {
|
|
1578
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1579
|
+
}
|
|
1580
|
+
}
|
|
1581
|
+
constraints.push(limit(filters.pagination || 10));
|
|
1582
|
+
|
|
1583
|
+
const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
|
|
1584
|
+
const querySnapshot = await getDocs(q);
|
|
1585
|
+
let procedures = querySnapshot.docs.map(
|
|
1586
|
+
doc => ({ ...doc.data(), id: doc.id } as Procedure),
|
|
1587
|
+
);
|
|
1588
|
+
|
|
1589
|
+
// Apply client-side filters for nested fields if needed
|
|
1590
|
+
if (hasNestedFilters) {
|
|
1591
|
+
procedures = this.applyInMemoryFilters(procedures, filters);
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
const lastDoc =
|
|
1595
|
+
querySnapshot.docs.length > 0
|
|
1596
|
+
? querySnapshot.docs[querySnapshot.docs.length - 1]
|
|
1597
|
+
: null;
|
|
1598
|
+
|
|
1599
|
+
console.log(`[PROCEDURE_SERVICE] Strategy 1 success: ${procedures.length} procedures`);
|
|
1600
|
+
|
|
1601
|
+
// Fix Load More - ako je broj rezultata manji od pagination, nema više
|
|
1602
|
+
if (procedures.length < (filters.pagination || 10)) {
|
|
1603
|
+
return { procedures, lastDoc: null };
|
|
1604
|
+
}
|
|
1605
|
+
return { procedures, lastDoc };
|
|
1606
|
+
} catch (error) {
|
|
1607
|
+
console.log('[PROCEDURE_SERVICE] Strategy 1 failed:', error);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
// Strategy 2: Try name field search as fallback
|
|
1612
|
+
if (filters.nameSearch && filters.nameSearch.trim()) {
|
|
1613
|
+
try {
|
|
1614
|
+
console.log('[PROCEDURE_SERVICE] Strategy 2: Trying name field search');
|
|
1615
|
+
const searchTerm = filters.nameSearch.trim().toLowerCase();
|
|
1616
|
+
const constraints = getBaseConstraints();
|
|
1617
|
+
|
|
1618
|
+
// Check if we have nested field filters that might conflict with orderBy
|
|
1619
|
+
const hasNestedFilters = !!(filters.procedureTechnology || filters.procedureCategory || filters.procedureSubcategory);
|
|
1620
|
+
|
|
1621
|
+
if (hasNestedFilters) {
|
|
1622
|
+
console.log('[PROCEDURE_SERVICE] Strategy 2: Has nested filters, will apply client-side after query');
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
constraints.push(where('name', '>=', searchTerm));
|
|
1626
|
+
constraints.push(where('name', '<=', searchTerm + '\uf8ff'));
|
|
1627
|
+
constraints.push(orderBy('name'));
|
|
1628
|
+
|
|
1629
|
+
if (filters.lastDoc) {
|
|
1630
|
+
if (typeof filters.lastDoc.data === 'function') {
|
|
1631
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1632
|
+
} else if (Array.isArray(filters.lastDoc)) {
|
|
1633
|
+
constraints.push(startAfter(...filters.lastDoc));
|
|
1634
|
+
} else {
|
|
1635
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
constraints.push(limit(filters.pagination || 10));
|
|
1639
|
+
|
|
1640
|
+
const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
|
|
1641
|
+
const querySnapshot = await getDocs(q);
|
|
1642
|
+
let procedures = querySnapshot.docs.map(
|
|
1643
|
+
doc => ({ ...doc.data(), id: doc.id } as Procedure),
|
|
1644
|
+
);
|
|
1645
|
+
|
|
1646
|
+
// Apply client-side filters for nested fields if needed
|
|
1647
|
+
if (hasNestedFilters) {
|
|
1648
|
+
procedures = this.applyInMemoryFilters(procedures, filters);
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
// Filter out procedures from draft practitioners
|
|
1652
|
+
procedures = await this.filterDraftPractitionerProcedures(procedures);
|
|
1653
|
+
|
|
1654
|
+
const lastDoc =
|
|
1655
|
+
querySnapshot.docs.length > 0
|
|
1656
|
+
? querySnapshot.docs[querySnapshot.docs.length - 1]
|
|
1657
|
+
: null;
|
|
1658
|
+
|
|
1659
|
+
console.log(`[PROCEDURE_SERVICE] Strategy 2 success: ${procedures.length} procedures`);
|
|
1660
|
+
|
|
1661
|
+
// Fix Load More - ako je broj rezultata manji od pagination, nema više
|
|
1662
|
+
if (procedures.length < (filters.pagination || 10)) {
|
|
1663
|
+
return { procedures, lastDoc: null };
|
|
1664
|
+
}
|
|
1665
|
+
return { procedures, lastDoc };
|
|
1666
|
+
} catch (error) {
|
|
1667
|
+
console.log('[PROCEDURE_SERVICE] Strategy 2 failed:', error);
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
// Strategy 3: orderBy createdAt with client-side filtering
|
|
1672
|
+
// NOTE: This strategy excludes nested field filters (technology.id, category.id, subcategory.id)
|
|
1673
|
+
// from Firestore query because Firestore doesn't support orderBy on different field
|
|
1674
|
+
// when using where on nested fields without a composite index.
|
|
1675
|
+
// These filters are applied client-side instead.
|
|
1676
|
+
try {
|
|
1677
|
+
console.log(
|
|
1678
|
+
'[PROCEDURE_SERVICE] Strategy 3: Using createdAt orderBy with client-side filtering',
|
|
1679
|
+
{
|
|
1680
|
+
procedureTechnology: filters.procedureTechnology,
|
|
1681
|
+
hasTechnologyFilter: !!filters.procedureTechnology,
|
|
1682
|
+
},
|
|
1683
|
+
);
|
|
1684
|
+
|
|
1685
|
+
// Build constraints WITHOUT nested field filters (these will be applied client-side)
|
|
1686
|
+
const constraints: QueryConstraint[] = [];
|
|
1687
|
+
|
|
1688
|
+
// Active status filter
|
|
1689
|
+
if (filters.isActive !== undefined) {
|
|
1690
|
+
constraints.push(where('isActive', '==', filters.isActive));
|
|
1691
|
+
} else {
|
|
1692
|
+
constraints.push(where('isActive', '==', true));
|
|
1693
|
+
}
|
|
1694
|
+
|
|
1695
|
+
// Only include non-nested field filters in Firestore query
|
|
1696
|
+
if (filters.procedureFamily) {
|
|
1697
|
+
constraints.push(where('family', '==', filters.procedureFamily));
|
|
1698
|
+
}
|
|
1699
|
+
if (filters.practitionerId) {
|
|
1700
|
+
constraints.push(where('practitionerId', '==', filters.practitionerId));
|
|
1701
|
+
}
|
|
1702
|
+
if (filters.clinicId) {
|
|
1703
|
+
constraints.push(where('clinicBranchId', '==', filters.clinicId));
|
|
1704
|
+
}
|
|
1705
|
+
if (filters.minPrice !== undefined) {
|
|
1706
|
+
constraints.push(where('price', '>=', filters.minPrice));
|
|
1707
|
+
}
|
|
1708
|
+
if (filters.maxPrice !== undefined) {
|
|
1709
|
+
constraints.push(where('price', '<=', filters.maxPrice));
|
|
1710
|
+
}
|
|
1711
|
+
if (filters.minRating !== undefined) {
|
|
1712
|
+
constraints.push(where('reviewInfo.averageRating', '>=', filters.minRating));
|
|
1713
|
+
}
|
|
1714
|
+
if (filters.maxRating !== undefined) {
|
|
1715
|
+
constraints.push(where('reviewInfo.averageRating', '<=', filters.maxRating));
|
|
1716
|
+
}
|
|
1717
|
+
if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
|
|
1718
|
+
const benefitIdsToMatch = filters.treatmentBenefits;
|
|
1719
|
+
constraints.push(where('treatmentBenefitIds', 'array-contains-any', benefitIdsToMatch));
|
|
1720
|
+
}
|
|
1721
|
+
|
|
1722
|
+
// NOTE: We intentionally EXCLUDE these nested field filters from Firestore query:
|
|
1723
|
+
// - filters.procedureTechnology (technology.id)
|
|
1724
|
+
// - filters.procedureCategory (category.id)
|
|
1725
|
+
// - filters.procedureSubcategory (subcategory.id)
|
|
1726
|
+
// These will be applied client-side in applyInMemoryFilters
|
|
1727
|
+
|
|
1728
|
+
console.log(
|
|
1729
|
+
'[PROCEDURE_SERVICE] Strategy 3 Firestore constraints (nested filters excluded):',
|
|
1730
|
+
constraints.map(c => (c as any).fieldPath || 'unknown'),
|
|
1731
|
+
);
|
|
1732
|
+
constraints.push(orderBy('createdAt', 'desc'));
|
|
1733
|
+
|
|
1734
|
+
if (filters.lastDoc) {
|
|
1735
|
+
if (typeof filters.lastDoc.data === 'function') {
|
|
1736
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1737
|
+
} else if (Array.isArray(filters.lastDoc)) {
|
|
1738
|
+
constraints.push(startAfter(...filters.lastDoc));
|
|
1739
|
+
} else {
|
|
1740
|
+
constraints.push(startAfter(filters.lastDoc));
|
|
1741
|
+
}
|
|
1742
|
+
}
|
|
1743
|
+
constraints.push(limit(filters.pagination || 10));
|
|
1744
|
+
|
|
1745
|
+
const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
|
|
1746
|
+
const querySnapshot = await getDocs(q);
|
|
1747
|
+
let procedures = querySnapshot.docs.map(
|
|
1748
|
+
doc => ({ ...doc.data(), id: doc.id } as Procedure),
|
|
1749
|
+
);
|
|
1750
|
+
|
|
1751
|
+
// Apply all client-side filters using centralized function
|
|
1752
|
+
console.log('[PROCEDURE_SERVICE] Before applyInMemoryFilters (Strategy 3):', {
|
|
1753
|
+
procedureCount: procedures.length,
|
|
1754
|
+
procedureTechnology: filters.procedureTechnology,
|
|
1755
|
+
filtersObject: {
|
|
1756
|
+
procedureTechnology: filters.procedureTechnology,
|
|
1757
|
+
procedureFamily: filters.procedureFamily,
|
|
1758
|
+
procedureCategory: filters.procedureCategory,
|
|
1759
|
+
procedureSubcategory: filters.procedureSubcategory,
|
|
1760
|
+
},
|
|
1761
|
+
});
|
|
1762
|
+
procedures = this.applyInMemoryFilters(procedures, filters);
|
|
1763
|
+
|
|
1764
|
+
// Filter out procedures from draft practitioners
|
|
1765
|
+
procedures = await this.filterDraftPractitionerProcedures(procedures);
|
|
1766
|
+
|
|
1767
|
+
console.log('[PROCEDURE_SERVICE] After applyInMemoryFilters (Strategy 3):', {
|
|
1768
|
+
procedureCount: procedures.length,
|
|
1769
|
+
});
|
|
1770
|
+
|
|
1771
|
+
const lastDoc =
|
|
1772
|
+
querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
|
|
1773
|
+
console.log(`[PROCEDURE_SERVICE] Strategy 3 success: ${procedures.length} procedures`);
|
|
1774
|
+
|
|
1775
|
+
// Fix Load More - ako je broj rezultata manji od pagination, nema više
|
|
1776
|
+
if (procedures.length < (filters.pagination || 10)) {
|
|
1777
|
+
return { procedures, lastDoc: null };
|
|
1778
|
+
}
|
|
1779
|
+
return { procedures, lastDoc };
|
|
1780
|
+
} catch (error) {
|
|
1781
|
+
console.log('[PROCEDURE_SERVICE] Strategy 3 failed:', error);
|
|
1782
|
+
}
|
|
1783
|
+
|
|
1784
|
+
// Strategy 4: Minimal query fallback
|
|
1785
|
+
try {
|
|
1786
|
+
console.log('[PROCEDURE_SERVICE] Strategy 4: Minimal query fallback');
|
|
1787
|
+
const constraints: QueryConstraint[] = [
|
|
1788
|
+
where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
|
|
1789
|
+
orderBy('createdAt', 'desc'),
|
|
1790
|
+
];
|
|
1791
|
+
if (filters.practitionerId) {
|
|
1792
|
+
constraints.push(where('practitionerId', '==', filters.practitionerId));
|
|
1793
|
+
}
|
|
1794
|
+
if (filters.clinicId) {
|
|
1795
|
+
constraints.push(where('clinicBranchId', '==', filters.clinicId));
|
|
1796
|
+
}
|
|
1797
|
+
constraints.push(limit(filters.pagination || 10));
|
|
1798
|
+
|
|
1799
|
+
const q = query(collection(this.db, PROCEDURES_COLLECTION), ...constraints);
|
|
1800
|
+
const querySnapshot = await getDocs(q);
|
|
1801
|
+
let procedures = querySnapshot.docs.map(
|
|
1802
|
+
doc => ({ ...doc.data(), id: doc.id } as Procedure),
|
|
1803
|
+
);
|
|
1804
|
+
|
|
1805
|
+
// Apply all client-side filters using centralized function
|
|
1806
|
+
procedures = this.applyInMemoryFilters(procedures, filters);
|
|
1807
|
+
|
|
1808
|
+
// Filter out procedures from draft practitioners
|
|
1809
|
+
procedures = await this.filterDraftPractitionerProcedures(procedures);
|
|
1810
|
+
|
|
1811
|
+
const lastDoc =
|
|
1812
|
+
querySnapshot.docs.length > 0 ? querySnapshot.docs[querySnapshot.docs.length - 1] : null;
|
|
1813
|
+
console.log(`[PROCEDURE_SERVICE] Strategy 4 success: ${procedures.length} procedures`);
|
|
1814
|
+
|
|
1815
|
+
// Fix Load More - ako je broj rezultata manji od pagination, nema više
|
|
1816
|
+
if (procedures.length < (filters.pagination || 10)) {
|
|
1817
|
+
return { procedures, lastDoc: null };
|
|
1818
|
+
}
|
|
1819
|
+
return { procedures, lastDoc };
|
|
1820
|
+
} catch (error) {
|
|
1821
|
+
console.log('[PROCEDURE_SERVICE] Strategy 4 failed:', error);
|
|
1822
|
+
}
|
|
1823
|
+
|
|
1824
|
+
// All strategies failed
|
|
1825
|
+
console.log('[PROCEDURE_SERVICE] All strategies failed, returning empty result');
|
|
1826
|
+
return { procedures: [], lastDoc: null };
|
|
1827
|
+
} catch (error) {
|
|
1828
|
+
console.error('[PROCEDURE_SERVICE] Error filtering procedures:', error);
|
|
1829
|
+
return { procedures: [], lastDoc: null };
|
|
1830
|
+
}
|
|
1831
|
+
}
|
|
1832
|
+
|
|
1833
|
+
/**
|
|
1834
|
+
* Applies in-memory filters to procedures array
|
|
1835
|
+
* Used when Firestore queries fail or for complex filtering
|
|
1836
|
+
*/
|
|
1837
|
+
private applyInMemoryFilters(
|
|
1838
|
+
procedures: Procedure[],
|
|
1839
|
+
filters: any,
|
|
1840
|
+
): (Procedure & { distance?: number })[] {
|
|
1841
|
+
let filteredProcedures = [...procedures]; // Create copy to avoid mutating original
|
|
1842
|
+
|
|
1843
|
+
// Debug: Log what filters we received
|
|
1844
|
+
console.log('[PROCEDURE_SERVICE] applyInMemoryFilters called:', {
|
|
1845
|
+
procedureCount: procedures.length,
|
|
1846
|
+
procedureTechnology: filters.procedureTechnology,
|
|
1847
|
+
hasTechnologyFilter: !!filters.procedureTechnology,
|
|
1848
|
+
allFilterKeys: Object.keys(filters).filter(k => filters[k] !== undefined && filters[k] !== null),
|
|
1849
|
+
});
|
|
1850
|
+
|
|
1851
|
+
// Name search filter
|
|
1852
|
+
if (filters.nameSearch && filters.nameSearch.trim()) {
|
|
1853
|
+
const searchTerm = filters.nameSearch.trim().toLowerCase();
|
|
1854
|
+
filteredProcedures = filteredProcedures.filter(procedure => {
|
|
1855
|
+
const name = (procedure.name || '').toLowerCase();
|
|
1856
|
+
const nameLower = procedure.nameLower || '';
|
|
1857
|
+
return name.includes(searchTerm) || nameLower.includes(searchTerm);
|
|
1858
|
+
});
|
|
1859
|
+
console.log(`[PROCEDURE_SERVICE] Applied name filter, results: ${filteredProcedures.length}`);
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
// Price filtering
|
|
1863
|
+
if (filters.minPrice !== undefined || filters.maxPrice !== undefined) {
|
|
1864
|
+
filteredProcedures = filteredProcedures.filter(procedure => {
|
|
1865
|
+
const price = procedure.price || 0;
|
|
1866
|
+
if (filters.minPrice !== undefined && price < filters.minPrice) return false;
|
|
1867
|
+
if (filters.maxPrice !== undefined && price > filters.maxPrice) return false;
|
|
1868
|
+
return true;
|
|
1869
|
+
});
|
|
1870
|
+
console.log(
|
|
1871
|
+
`[PROCEDURE_SERVICE] Applied price filter (${filters.minPrice}-${filters.maxPrice}), results: ${filteredProcedures.length}`,
|
|
1872
|
+
);
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
// Rating filtering
|
|
1876
|
+
if (filters.minRating !== undefined || filters.maxRating !== undefined) {
|
|
1877
|
+
filteredProcedures = filteredProcedures.filter(procedure => {
|
|
1878
|
+
const rating = procedure.reviewInfo?.averageRating || 0;
|
|
1879
|
+
if (filters.minRating !== undefined && rating < filters.minRating) return false;
|
|
1880
|
+
if (filters.maxRating !== undefined && rating > filters.maxRating) return false;
|
|
1881
|
+
return true;
|
|
1882
|
+
});
|
|
1883
|
+
console.log(
|
|
1884
|
+
`[PROCEDURE_SERVICE] Applied rating filter, results: ${filteredProcedures.length}`,
|
|
1885
|
+
);
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
// Treatment benefits filtering
|
|
1889
|
+
if (filters.treatmentBenefits && filters.treatmentBenefits.length > 0) {
|
|
1890
|
+
const benefitIdsToMatch = filters.treatmentBenefits;
|
|
1891
|
+
filteredProcedures = filteredProcedures.filter(procedure => {
|
|
1892
|
+
const procedureBenefitIds = procedure.treatmentBenefitIds || [];
|
|
1893
|
+
return benefitIdsToMatch.some((benefitId: string) =>
|
|
1894
|
+
procedureBenefitIds.includes(benefitId),
|
|
1895
|
+
);
|
|
1896
|
+
});
|
|
1897
|
+
console.log(
|
|
1898
|
+
`[PROCEDURE_SERVICE] Applied benefits filter, results: ${filteredProcedures.length}`,
|
|
1899
|
+
);
|
|
1900
|
+
}
|
|
1901
|
+
|
|
1902
|
+
// Procedure family filtering
|
|
1903
|
+
if (filters.procedureFamily) {
|
|
1904
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1905
|
+
procedure => procedure.family === filters.procedureFamily,
|
|
1906
|
+
);
|
|
1907
|
+
console.log(
|
|
1908
|
+
`[PROCEDURE_SERVICE] Applied family filter, results: ${filteredProcedures.length}`,
|
|
1909
|
+
);
|
|
1910
|
+
}
|
|
1911
|
+
|
|
1912
|
+
// Category filtering
|
|
1913
|
+
if (filters.procedureCategory) {
|
|
1914
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1915
|
+
procedure => procedure.category?.id === filters.procedureCategory,
|
|
1916
|
+
);
|
|
1917
|
+
console.log(
|
|
1918
|
+
`[PROCEDURE_SERVICE] Applied category filter, results: ${filteredProcedures.length}`,
|
|
1919
|
+
);
|
|
1920
|
+
}
|
|
1921
|
+
|
|
1922
|
+
// Subcategory filtering
|
|
1923
|
+
if (filters.procedureSubcategory) {
|
|
1924
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1925
|
+
procedure => procedure.subcategory?.id === filters.procedureSubcategory,
|
|
1926
|
+
);
|
|
1927
|
+
console.log(
|
|
1928
|
+
`[PROCEDURE_SERVICE] Applied subcategory filter, results: ${filteredProcedures.length}`,
|
|
1929
|
+
);
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// Technology filtering
|
|
1933
|
+
if (filters.procedureTechnology) {
|
|
1934
|
+
const beforeCount = filteredProcedures.length;
|
|
1935
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1936
|
+
procedure => procedure.technology?.id === filters.procedureTechnology,
|
|
1937
|
+
);
|
|
1938
|
+
console.log(
|
|
1939
|
+
`[PROCEDURE_SERVICE] Applied technology filter (${filters.procedureTechnology}), before: ${beforeCount}, after: ${filteredProcedures.length}`,
|
|
1940
|
+
);
|
|
1941
|
+
// Log sample technology IDs for debugging
|
|
1942
|
+
if (beforeCount > filteredProcedures.length) {
|
|
1943
|
+
const filteredOut = procedures
|
|
1944
|
+
.filter(p => p.technology?.id !== filters.procedureTechnology)
|
|
1945
|
+
.slice(0, 3)
|
|
1946
|
+
.map(p => ({ id: p.id, techId: p.technology?.id, name: p.name }));
|
|
1947
|
+
console.log('[PROCEDURE_SERVICE] Filtered out sample procedures:', filteredOut);
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
|
|
1951
|
+
// Practitioner filtering
|
|
1952
|
+
if (filters.practitionerId) {
|
|
1953
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1954
|
+
procedure => procedure.practitionerId === filters.practitionerId,
|
|
1955
|
+
);
|
|
1956
|
+
console.log(
|
|
1957
|
+
`[PROCEDURE_SERVICE] Applied practitioner filter, results: ${filteredProcedures.length}`,
|
|
1958
|
+
);
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
// Clinic filtering
|
|
1962
|
+
if (filters.clinicId) {
|
|
1963
|
+
filteredProcedures = filteredProcedures.filter(
|
|
1964
|
+
procedure => procedure.clinicBranchId === filters.clinicId,
|
|
1965
|
+
);
|
|
1966
|
+
console.log(
|
|
1967
|
+
`[PROCEDURE_SERVICE] Applied clinic filter, results: ${filteredProcedures.length}`,
|
|
1968
|
+
);
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
// Geo-radius filter
|
|
1972
|
+
if (filters.location && filters.radiusInKm && filters.radiusInKm > 0) {
|
|
1973
|
+
const location = filters.location;
|
|
1974
|
+
const radiusInKm = filters.radiusInKm;
|
|
1975
|
+
filteredProcedures = filteredProcedures.filter(procedure => {
|
|
1976
|
+
const clinicLocation = procedure.clinicInfo?.location;
|
|
1977
|
+
if (!clinicLocation?.latitude || !clinicLocation?.longitude) {
|
|
1978
|
+
return false;
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
const distance =
|
|
1982
|
+
distanceBetween(
|
|
1983
|
+
[location.latitude, location.longitude],
|
|
1984
|
+
[clinicLocation.latitude, clinicLocation.longitude],
|
|
1985
|
+
) / 1000; // Convert to km
|
|
1986
|
+
|
|
1987
|
+
// Attach distance for frontend sorting/display
|
|
1988
|
+
(procedure as any).distance = distance;
|
|
1989
|
+
|
|
1990
|
+
return distance <= radiusInKm;
|
|
1991
|
+
});
|
|
1992
|
+
console.log(`[PROCEDURE_SERVICE] Applied geo filter, results: ${filteredProcedures.length}`);
|
|
1993
|
+
|
|
1994
|
+
// Sort by distance when geo filtering is applied
|
|
1995
|
+
filteredProcedures.sort((a, b) => ((a as any).distance || 0) - ((b as any).distance || 0));
|
|
1996
|
+
}
|
|
1997
|
+
|
|
1998
|
+
return filteredProcedures as (Procedure & { distance?: number })[];
|
|
1999
|
+
}
|
|
2000
|
+
|
|
2001
|
+
private handleGeoQuery(filters: any): Promise<{
|
|
2002
|
+
procedures: (Procedure & { distance?: number })[];
|
|
2003
|
+
lastDoc: any;
|
|
2004
|
+
}> {
|
|
2005
|
+
console.log('[PROCEDURE_SERVICE] Executing geo query with geohash bounds');
|
|
2006
|
+
try {
|
|
2007
|
+
const location = filters.location;
|
|
2008
|
+
const radiusInKm = filters.radiusInKm;
|
|
2009
|
+
|
|
2010
|
+
if (!location || !radiusInKm) {
|
|
2011
|
+
return Promise.resolve({ procedures: [], lastDoc: null });
|
|
2012
|
+
}
|
|
2013
|
+
|
|
2014
|
+
const bounds = geohashQueryBounds([location.latitude, location.longitude], radiusInKm * 1000);
|
|
2015
|
+
|
|
2016
|
+
const fetches = bounds.map(b => {
|
|
2017
|
+
const constraints: QueryConstraint[] = [
|
|
2018
|
+
where('clinicInfo.location.geohash', '>=', b[0]),
|
|
2019
|
+
where('clinicInfo.location.geohash', '<=', b[1]),
|
|
2020
|
+
where('isActive', '==', filters.isActive !== undefined ? filters.isActive : true),
|
|
2021
|
+
];
|
|
2022
|
+
if (filters.practitionerId) {
|
|
2023
|
+
constraints.push(where('practitionerId', '==', filters.practitionerId));
|
|
2024
|
+
}
|
|
2025
|
+
if (filters.clinicId) {
|
|
2026
|
+
constraints.push(where('clinicBranchId', '==', filters.clinicId));
|
|
2027
|
+
}
|
|
2028
|
+
return getDocs(query(collection(this.db, PROCEDURES_COLLECTION), ...constraints));
|
|
2029
|
+
});
|
|
2030
|
+
|
|
2031
|
+
return Promise.all(fetches)
|
|
2032
|
+
.then(snaps => {
|
|
2033
|
+
const collected: Procedure[] = [];
|
|
2034
|
+
snaps.forEach(snap => {
|
|
2035
|
+
snap.docs.forEach(d => collected.push({ ...(d.data() as Procedure), id: d.id }));
|
|
2036
|
+
});
|
|
2037
|
+
|
|
2038
|
+
// Deduplicate by id
|
|
2039
|
+
const uniqueMap = new Map<string, Procedure>();
|
|
2040
|
+
for (const p of collected) {
|
|
2041
|
+
uniqueMap.set(p.id, p);
|
|
2042
|
+
}
|
|
2043
|
+
let procedures = Array.from(uniqueMap.values());
|
|
2044
|
+
|
|
2045
|
+
// Apply remaining filters including precise distance and sorting
|
|
2046
|
+
procedures = this.applyInMemoryFilters(procedures, filters);
|
|
2047
|
+
|
|
2048
|
+
// Manual pagination
|
|
2049
|
+
const pageSize = filters.pagination || 10;
|
|
2050
|
+
let startIndex = 0;
|
|
2051
|
+
if (
|
|
2052
|
+
filters.lastDoc &&
|
|
2053
|
+
typeof filters.lastDoc === 'object' &&
|
|
2054
|
+
(filters.lastDoc as any).id
|
|
2055
|
+
) {
|
|
2056
|
+
const idx = procedures.findIndex(p => p.id === (filters.lastDoc as any).id);
|
|
2057
|
+
if (idx >= 0) startIndex = idx + 1;
|
|
2058
|
+
}
|
|
2059
|
+
const page = procedures.slice(startIndex, startIndex + pageSize);
|
|
2060
|
+
const newLastDoc = page.length === pageSize ? page[page.length - 1] : null;
|
|
2061
|
+
|
|
2062
|
+
console.log(
|
|
2063
|
+
`[PROCEDURE_SERVICE] Geo query success: ${page.length} (of ${procedures.length}) within ${radiusInKm}km`,
|
|
2064
|
+
);
|
|
2065
|
+
return { procedures: page, lastDoc: newLastDoc };
|
|
2066
|
+
})
|
|
2067
|
+
.catch(err => {
|
|
2068
|
+
console.error('[PROCEDURE_SERVICE] Geo bounds fetch failed:', err);
|
|
2069
|
+
return { procedures: [], lastDoc: null };
|
|
2070
|
+
});
|
|
2071
|
+
} catch (error) {
|
|
2072
|
+
console.error('[PROCEDURE_SERVICE] Geo query failed:', error);
|
|
2073
|
+
return Promise.resolve({ procedures: [], lastDoc: null });
|
|
2074
|
+
}
|
|
2075
|
+
}
|
|
2076
|
+
|
|
2077
|
+
/**
|
|
2078
|
+
* Creates a consultation procedure without requiring a product
|
|
2079
|
+
* This is a special method for consultation procedures that don't use products
|
|
2080
|
+
* @param data - The data for creating a consultation procedure (without productId)
|
|
2081
|
+
* @returns The created procedure
|
|
2082
|
+
*/
|
|
2083
|
+
async createConsultationProcedure(
|
|
2084
|
+
data: Omit<CreateProcedureData, 'productId'>,
|
|
2085
|
+
): Promise<Procedure> {
|
|
2086
|
+
// Generate procedure ID first so we can use it for media uploads
|
|
2087
|
+
const procedureId = this.generateId();
|
|
2088
|
+
|
|
2089
|
+
// Get references to related entities (Category, Subcategory, Technology)
|
|
2090
|
+
// For consultation, we don't need a product
|
|
2091
|
+
const [category, subcategory, technology] = await Promise.all([
|
|
2092
|
+
this.categoryService.getByIdInternal(data.categoryId),
|
|
2093
|
+
this.subcategoryService.getByIdInternal(data.categoryId, data.subcategoryId),
|
|
2094
|
+
this.technologyService.getByIdInternal(data.technologyId),
|
|
2095
|
+
]);
|
|
2096
|
+
|
|
2097
|
+
if (!category || !subcategory || !technology) {
|
|
2098
|
+
throw new Error('One or more required base entities not found');
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
// Get clinic and practitioner information for aggregation
|
|
2102
|
+
const clinicRef = doc(this.db, CLINICS_COLLECTION, data.clinicBranchId);
|
|
2103
|
+
const clinicSnapshot = await getDoc(clinicRef);
|
|
2104
|
+
if (!clinicSnapshot.exists()) {
|
|
2105
|
+
throw new Error(`Clinic with ID ${data.clinicBranchId} not found`);
|
|
2106
|
+
}
|
|
2107
|
+
const clinic = clinicSnapshot.data() as Clinic;
|
|
2108
|
+
|
|
2109
|
+
const practitionerRef = doc(this.db, PRACTITIONERS_COLLECTION, data.practitionerId);
|
|
2110
|
+
const practitionerSnapshot = await getDoc(practitionerRef);
|
|
2111
|
+
if (!practitionerSnapshot.exists()) {
|
|
2112
|
+
throw new Error(`Practitioner with ID ${data.practitionerId} not found`);
|
|
2113
|
+
}
|
|
2114
|
+
const practitioner = practitionerSnapshot.data() as Practitioner;
|
|
2115
|
+
|
|
2116
|
+
// Process photos if provided
|
|
2117
|
+
let processedPhotos: string[] = [];
|
|
2118
|
+
if (data.photos && data.photos.length > 0) {
|
|
2119
|
+
processedPhotos = await this.processMediaArray(data.photos, procedureId, 'procedure-photos');
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
// If no photos provided and technology has a photoTemplate, use it as default photo
|
|
2123
|
+
if (processedPhotos.length === 0 && technology.photoTemplate) {
|
|
2124
|
+
console.log(`[ProcedureService] Using technology photoTemplate as default photo for consultation: ${technology.photoTemplate}`);
|
|
2125
|
+
const photoTemplateUrl = await this.mediaService.getMediaDownloadUrl(technology.photoTemplate);
|
|
2126
|
+
if (photoTemplateUrl) {
|
|
2127
|
+
processedPhotos.push(photoTemplateUrl);
|
|
2128
|
+
} else {
|
|
2129
|
+
console.warn(`[ProcedureService] Could not fetch photoTemplate URL for media ID: ${technology.photoTemplate}`);
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
// Transform productsMetadata from validation format to ProcedureProduct format
|
|
2134
|
+
// For consultations, this will return empty array since no products are provided
|
|
2135
|
+
const transformedProductsMetadata = await this.transformProductsMetadata(
|
|
2136
|
+
data.productsMetadata,
|
|
2137
|
+
data.technologyId,
|
|
2138
|
+
);
|
|
2139
|
+
|
|
2140
|
+
// Create aggregated clinic info for the procedure document
|
|
2141
|
+
const clinicInfo = {
|
|
2142
|
+
id: clinicSnapshot.id,
|
|
2143
|
+
name: clinic.name,
|
|
2144
|
+
description: clinic.description || '',
|
|
2145
|
+
featuredPhoto:
|
|
2146
|
+
clinic.featuredPhotos && clinic.featuredPhotos.length > 0
|
|
2147
|
+
? typeof clinic.featuredPhotos[0] === 'string'
|
|
2148
|
+
? clinic.featuredPhotos[0]
|
|
2149
|
+
: ''
|
|
2150
|
+
: typeof clinic.coverPhoto === 'string'
|
|
2151
|
+
? clinic.coverPhoto
|
|
2152
|
+
: '',
|
|
2153
|
+
location: clinic.location,
|
|
2154
|
+
contactInfo: clinic.contactInfo,
|
|
2155
|
+
};
|
|
2156
|
+
|
|
2157
|
+
// Create aggregated doctor info for the procedure document
|
|
2158
|
+
const doctorInfo = {
|
|
2159
|
+
id: practitionerSnapshot.id,
|
|
2160
|
+
name: `${practitioner.basicInfo.firstName} ${practitioner.basicInfo.lastName}`,
|
|
2161
|
+
description: practitioner.basicInfo.bio || '',
|
|
2162
|
+
photo:
|
|
2163
|
+
typeof practitioner.basicInfo.profileImageUrl === 'string'
|
|
2164
|
+
? practitioner.basicInfo.profileImageUrl
|
|
2165
|
+
: '',
|
|
2166
|
+
rating: practitioner.reviewInfo?.averageRating || 0,
|
|
2167
|
+
services: practitioner.procedures || [],
|
|
2168
|
+
};
|
|
2169
|
+
|
|
2170
|
+
// Create the procedure object
|
|
2171
|
+
const { productsMetadata: _, ...dataWithoutProductsMetadata } = data;
|
|
2172
|
+
const newProcedure: Omit<Procedure, 'createdAt' | 'updatedAt'> = {
|
|
2173
|
+
id: procedureId,
|
|
2174
|
+
...dataWithoutProductsMetadata,
|
|
2175
|
+
nameLower: (data as any).nameLower || data.name.toLowerCase(),
|
|
2176
|
+
photos: processedPhotos,
|
|
2177
|
+
category,
|
|
2178
|
+
subcategory,
|
|
2179
|
+
technology,
|
|
2180
|
+
// No product field for consultations (Firestore doesn't allow undefined, so we omit it entirely)
|
|
2181
|
+
productsMetadata: transformedProductsMetadata, // Empty array for consultations
|
|
2182
|
+
blockingConditions: technology.blockingConditions,
|
|
2183
|
+
contraindications: technology.contraindications || [],
|
|
2184
|
+
contraindicationIds: technology.contraindications?.map(c => c.id) || [],
|
|
2185
|
+
treatmentBenefits: technology.benefits,
|
|
2186
|
+
treatmentBenefitIds: Array.isArray(technology.benefits)
|
|
2187
|
+
? technology.benefits.map(b => typeof b === 'string' ? b : b.id)
|
|
2188
|
+
: [],
|
|
2189
|
+
preRequirements: technology.requirements.pre,
|
|
2190
|
+
postRequirements: technology.requirements.post,
|
|
2191
|
+
certificationRequirement: technology.certificationRequirement,
|
|
2192
|
+
documentationTemplates: technology?.documentationTemplates || [],
|
|
2193
|
+
clinicInfo,
|
|
2194
|
+
doctorInfo,
|
|
2195
|
+
reviewInfo: {
|
|
2196
|
+
totalReviews: 0,
|
|
2197
|
+
averageRating: 0,
|
|
2198
|
+
effectivenessOfTreatment: 0,
|
|
2199
|
+
outcomeExplanation: 0,
|
|
2200
|
+
painManagement: 0,
|
|
2201
|
+
followUpCare: 0,
|
|
2202
|
+
valueForMoney: 0,
|
|
2203
|
+
recommendationPercentage: 0,
|
|
2204
|
+
},
|
|
2205
|
+
isActive: true,
|
|
2206
|
+
};
|
|
2207
|
+
|
|
2208
|
+
// Create the procedure document
|
|
2209
|
+
const procedureRef = doc(this.db, PROCEDURES_COLLECTION, procedureId);
|
|
2210
|
+
await setDoc(procedureRef, {
|
|
2211
|
+
...newProcedure,
|
|
2212
|
+
createdAt: serverTimestamp(),
|
|
2213
|
+
updatedAt: serverTimestamp(),
|
|
2214
|
+
});
|
|
2215
|
+
|
|
2216
|
+
// Return the created procedure (fetch again to get server timestamps)
|
|
2217
|
+
const savedDoc = await getDoc(procedureRef);
|
|
2218
|
+
return savedDoc.data() as Procedure;
|
|
2219
|
+
}
|
|
2220
|
+
|
|
2221
|
+
/**
|
|
2222
|
+
* Gets all procedures with minimal info for map display (id, name, clinicId, clinicName, address, latitude, longitude)
|
|
2223
|
+
* This is optimized for mobile map usage to reduce payload size.
|
|
2224
|
+
* @returns Array of minimal procedure info for map
|
|
2225
|
+
*/
|
|
2226
|
+
async getProceduresForMap(): Promise<
|
|
2227
|
+
{
|
|
2228
|
+
id: string;
|
|
2229
|
+
name: string;
|
|
2230
|
+
clinicId: string | undefined;
|
|
2231
|
+
clinicName: string | undefined;
|
|
2232
|
+
address: string;
|
|
2233
|
+
latitude: number | undefined;
|
|
2234
|
+
longitude: number | undefined;
|
|
2235
|
+
}[]
|
|
2236
|
+
> {
|
|
2237
|
+
const proceduresRef = collection(this.db, PROCEDURES_COLLECTION);
|
|
2238
|
+
const snapshot = await getDocs(proceduresRef);
|
|
2239
|
+
const proceduresForMap = snapshot.docs.map(doc => {
|
|
2240
|
+
const data = doc.data();
|
|
2241
|
+
return {
|
|
2242
|
+
id: doc.id,
|
|
2243
|
+
name: data.name,
|
|
2244
|
+
clinicId: data.clinicInfo?.id,
|
|
2245
|
+
clinicName: data.clinicInfo?.name,
|
|
2246
|
+
address: data.clinicInfo?.location?.address || '',
|
|
2247
|
+
latitude: data.clinicInfo?.location?.latitude,
|
|
2248
|
+
longitude: data.clinicInfo?.location?.longitude,
|
|
2249
|
+
};
|
|
2250
|
+
});
|
|
2251
|
+
return proceduresForMap;
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
/**
|
|
2255
|
+
* Gets procedures filtered by clinic and practitioner with optional family filter
|
|
2256
|
+
* @param clinicBranchId Clinic branch ID to filter by
|
|
2257
|
+
* @param practitionerId Practitioner ID to filter by
|
|
2258
|
+
* @param filterByFamily If true, shows only procedures of the same family as the default procedure
|
|
2259
|
+
* @param defaultProcedureId Optional default procedure ID to determine the family
|
|
2260
|
+
* @returns Array of procedures
|
|
2261
|
+
*/
|
|
2262
|
+
async getProceduresForConsultation(
|
|
2263
|
+
clinicBranchId: string,
|
|
2264
|
+
practitionerId: string,
|
|
2265
|
+
filterByFamily: boolean = true,
|
|
2266
|
+
defaultProcedureId?: string
|
|
2267
|
+
): Promise<Procedure[]> {
|
|
2268
|
+
let familyToFilter: ProcedureFamily | null = null;
|
|
2269
|
+
|
|
2270
|
+
// If family filtering is enabled and we have a default procedure, get its family
|
|
2271
|
+
if (filterByFamily && defaultProcedureId) {
|
|
2272
|
+
const defaultProcedureRef = doc(this.db, PROCEDURES_COLLECTION, defaultProcedureId);
|
|
2273
|
+
const defaultProcedureSnap = await getDoc(defaultProcedureRef);
|
|
2274
|
+
|
|
2275
|
+
if (defaultProcedureSnap.exists()) {
|
|
2276
|
+
const defaultProcedure = defaultProcedureSnap.data() as Procedure;
|
|
2277
|
+
familyToFilter = defaultProcedure.family;
|
|
2278
|
+
}
|
|
2279
|
+
}
|
|
2280
|
+
|
|
2281
|
+
// Build query constraints
|
|
2282
|
+
const constraints: QueryConstraint[] = [
|
|
2283
|
+
where('clinicBranchId', '==', clinicBranchId),
|
|
2284
|
+
where('practitionerId', '==', practitionerId),
|
|
2285
|
+
where('isActive', '==', true),
|
|
2286
|
+
];
|
|
2287
|
+
|
|
2288
|
+
// Add family filter if applicable
|
|
2289
|
+
if (filterByFamily && familyToFilter) {
|
|
2290
|
+
constraints.push(where('family', '==', familyToFilter));
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
// Execute query
|
|
2294
|
+
const proceduresQuery = query(
|
|
2295
|
+
collection(this.db, PROCEDURES_COLLECTION),
|
|
2296
|
+
...constraints,
|
|
2297
|
+
orderBy('name', 'asc')
|
|
2298
|
+
);
|
|
2299
|
+
|
|
2300
|
+
const querySnapshot = await getDocs(proceduresQuery);
|
|
2301
|
+
|
|
2302
|
+
return querySnapshot.docs.map(doc => ({
|
|
2303
|
+
id: doc.id,
|
|
2304
|
+
...doc.data(),
|
|
2305
|
+
} as Procedure));
|
|
2306
|
+
}
|
|
2307
|
+
}
|