@blackcode_sa/metaestetics-api 1.12.0 → 1.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,7 +18,8 @@ constructor(
18
18
  categoryService: CategoryService,
19
19
  subcategoryService: SubcategoryService,
20
20
  technologyService: TechnologyService,
21
- productService: ProductService
21
+ productService: ProductService,
22
+ mediaService: MediaService
22
23
  )
23
24
  ```
24
25
 
@@ -31,7 +32,9 @@ Initializes the service with Firestore, Auth, App instances, and required depend
31
32
  - Creates a new procedure document in Firestore.
32
33
  - Validates input data using `createProcedureSchema`.
33
34
  - Fetches full Category, Subcategory, Technology, and Product documents using injected services.
35
+ - **Products Metadata:** Transforms `productsMetadata` from validation format (with `productId` strings) to full `ProcedureProduct` objects (with complete `product` objects).
34
36
  - Retrieves associated Clinic and Practitioner documents to embed `clinicInfo` and `doctorInfo`.
37
+ - Processes and uploads media files using the MediaService.
35
38
  - Embeds treatment details from the technology (blocking conditions, benefits, requirements).
36
39
  - Initializes default `reviewInfo` with zero values.
37
40
  - Sets `isActive` to `true` by default.
@@ -56,11 +59,13 @@ Initializes the service with Firestore, Auth, App instances, and required depend
56
59
 
57
60
  - Updates an existing procedure document with partial data.
58
61
  - Validates input data using `updateProcedureSchema`.
62
+ - **Products Metadata:** If `productsMetadata` is provided, transforms from validation format to full `ProcedureProduct` objects.
59
63
  - Handles complex updates of related entities:
60
64
  - If practitioner changes: Fetches new practitioner data and updates embedded `doctorInfo`.
61
65
  - If clinic changes: Fetches new clinic data and updates embedded `clinicInfo`.
62
66
  - If category/subcategory changes: Fetches and updates embedded objects.
63
67
  - If technology/product changes: Fetches and updates embedded objects plus derived fields.
68
+ - Processes and uploads media files if photos are provided.
64
69
  - Updates the `updatedAt` timestamp.
65
70
  - **Aggregation Note:** Updating aggregated data in related entities is handled by Cloud Functions.
66
71
 
@@ -83,6 +88,76 @@ Initializes the service with Firestore, Auth, App instances, and required depend
83
88
  - Returns an object containing arrays of allowed technologies, families, categories, and subcategories.
84
89
 
85
90
  - **`getAllProcedures(pagination?: number, lastDoc?: any): Promise<{ procedures: Procedure[]; lastDoc: any }>`**
91
+
86
92
  - Retrieves all procedures, ordered by name.
87
93
  - Supports optional pagination with `limit` and `startAfter`.
88
94
  - Returns both the procedures array and the last document for cursor-based pagination.
95
+
96
+ - **`bulkCreateProcedures(baseData: Omit<CreateProcedureData, "practitionerId">, practitionerIds: string[]): Promise<Procedure[]>`**
97
+
98
+ - Creates multiple procedures for different practitioners using common base data.
99
+ - Optimized for bulk creation to reduce database reads and writes.
100
+ - Uses Firestore batch writes for atomic creation.
101
+ - Transforms `productsMetadata` once and reuses for all procedures.
102
+
103
+ - **`createConsultationProcedure(data: Omit<CreateProcedureData, "productId">): Promise<Procedure>`**
104
+ - Special method for consultation procedures that don't require specific products.
105
+ - Creates a placeholder product for consultation procedures.
106
+ - Transforms `productsMetadata` from validation format to full objects.
107
+
108
+ ### Private Helper Methods
109
+
110
+ - **`transformProductsMetadata(productsMetadata, technologyId): Promise<ProcedureProduct[]>`**
111
+
112
+ - Converts validation format (with `productId` strings) to full `ProcedureProduct` objects.
113
+ - Fetches complete product objects for each product ID.
114
+ - Essential for maintaining type safety between validation and storage formats.
115
+
116
+ - **`processMedia(media, ownerId, collectionName): Promise<string | null>`**
117
+
118
+ - Handles media file uploads using MediaService.
119
+ - Supports string URLs, File objects, and Blob objects.
120
+
121
+ - **`processMediaArray(mediaArray, ownerId, collectionName): Promise<string[]>`**
122
+ - Processes arrays of media resources.
123
+ - Used for handling procedure photos.
124
+
125
+ ## Data Transformation
126
+
127
+ The service handles a critical data transformation between input and storage:
128
+
129
+ - **Input (`CreateProcedureData`/`UpdateProcedureData`):** `productsMetadata` contains objects with `productId: string`
130
+
131
+ ```typescript
132
+ productsMetadata: {
133
+ productId: string;
134
+ price: number;
135
+ currency: Currency;
136
+ pricingMeasure: PricingMeasure;
137
+ isDefault?: boolean;
138
+ }[]
139
+ ```
140
+
141
+ - **Storage (Firestore `Procedure`):** `productsMetadata` contains objects with `product: Product` (full object)
142
+ ```typescript
143
+ productsMetadata: ProcedureProduct[] // where ProcedureProduct contains full Product object
144
+ ```
145
+
146
+ This transformation ensures:
147
+
148
+ 1. **Type safety** throughout the application
149
+ 2. **Denormalized data** for efficient queries (no need to fetch products separately)
150
+ 3. **Consistent API contract** for clients (input uses IDs, storage uses full objects)
151
+ 4. **Performance optimization** (embedded product data in procedures)
152
+
153
+ ## Validation Schemas
154
+
155
+ The service uses different validation schemas for different stages:
156
+
157
+ - **`procedureProductDataSchema`**: Validates input data with `productId` strings (used in `createProcedureSchema`/`updateProcedureSchema`)
158
+ - **`storedProcedureProductSchema`**: Validates stored data with full `Product` objects (used in `procedureSchema`)
159
+ - **`createProcedureSchema`**: Validates procedure creation data (input format)
160
+ - **`updateProcedureSchema`**: Validates procedure update data (input format)
161
+ - **`procedureSchema`**: Validates complete stored procedure documents (storage format)
162
+
163
+ This ensures validation matches the actual data format at each stage of the process.
@@ -67,10 +67,15 @@ import {
67
67
  ProcedureFamily,
68
68
  type TreatmentBenefitDynamic,
69
69
  } from "../../backoffice/types";
70
+ import {
71
+ Currency,
72
+ PricingMeasure,
73
+ } from "../../backoffice/types/static/pricing.types";
70
74
  import { Clinic, CLINICS_COLLECTION } from "../../types/clinic";
71
75
  import { ProcedureReviewInfo } from "../../types/reviews";
72
76
  import { distanceBetween, geohashQueryBounds } from "geofire-common";
73
77
  import { MediaService, MediaAccessLevel } from "../media/media.service";
78
+ import type { ProcedureProduct } from "../../backoffice/types/procedure-product.types";
74
79
 
75
80
  export class ProcedureService extends BaseService {
76
81
  private categoryService: CategoryService;
@@ -163,6 +168,49 @@ export class ProcedureService extends BaseService {
163
168
  return result;
164
169
  }
165
170
 
171
+ /**
172
+ * Transforms validated procedure product data (with productId) to ProcedureProduct objects (with full product)
173
+ * @param productsMetadata Array of validated procedure product data
174
+ * @param technologyId Technology ID to fetch products from
175
+ * @returns Array of ProcedureProduct objects with full product information
176
+ */
177
+ private async transformProductsMetadata(
178
+ productsMetadata: {
179
+ productId: string;
180
+ price: number;
181
+ currency: Currency;
182
+ pricingMeasure: PricingMeasure;
183
+ isDefault?: boolean;
184
+ }[],
185
+ technologyId: string
186
+ ): Promise<ProcedureProduct[]> {
187
+ const transformedProducts: ProcedureProduct[] = [];
188
+
189
+ for (const productData of productsMetadata) {
190
+ // Fetch the full product object
191
+ const product = await this.productService.getById(
192
+ technologyId,
193
+ productData.productId
194
+ );
195
+ if (!product) {
196
+ throw new Error(
197
+ `Product with ID ${productData.productId} not found for technology ${technologyId}`
198
+ );
199
+ }
200
+
201
+ // Transform to ProcedureProduct
202
+ transformedProducts.push({
203
+ product,
204
+ price: productData.price,
205
+ currency: productData.currency,
206
+ pricingMeasure: productData.pricingMeasure,
207
+ isDefault: productData.isDefault,
208
+ });
209
+ }
210
+
211
+ return transformedProducts;
212
+ }
213
+
166
214
  /**
167
215
  * Creates a new procedure
168
216
  * @param data - The data for creating a new procedure
@@ -229,6 +277,12 @@ export class ProcedureService extends BaseService {
229
277
  );
230
278
  }
231
279
 
280
+ // Transform productsMetadata from validation format to ProcedureProduct format
281
+ const transformedProductsMetadata = await this.transformProductsMetadata(
282
+ validatedData.productsMetadata,
283
+ validatedData.technologyId
284
+ );
285
+
232
286
  // Create aggregated clinic info for the procedure document
233
287
  const clinicInfo = {
234
288
  id: clinicSnapshot.id,
@@ -271,6 +325,7 @@ export class ProcedureService extends BaseService {
271
325
  subcategory,
272
326
  technology,
273
327
  product,
328
+ productsMetadata: transformedProductsMetadata,
274
329
  blockingConditions: technology.blockingConditions,
275
330
  contraindications: technology.contraindications || [],
276
331
  contraindicationIds: technology.contraindications?.map((c) => c.id) || [],
@@ -367,6 +422,12 @@ export class ProcedureService extends BaseService {
367
422
  );
368
423
  }
369
424
 
425
+ // Transform productsMetadata from validation format to ProcedureProduct format
426
+ const transformedProductsMetadata = await this.transformProductsMetadata(
427
+ validatedData.productsMetadata,
428
+ validatedData.technologyId
429
+ );
430
+
370
431
  // 4. Fetch all practitioner data efficiently
371
432
  const practitionersMap = new Map<string, Practitioner>();
372
433
  // Use 'in' query in chunks of 30, as this is the Firestore limit
@@ -443,6 +504,7 @@ export class ProcedureService extends BaseService {
443
504
  subcategory,
444
505
  technology,
445
506
  product,
507
+ productsMetadata: transformedProductsMetadata,
446
508
  blockingConditions: technology.blockingConditions,
447
509
  contraindications: technology.contraindications || [],
448
510
  contraindicationIds:
@@ -581,7 +643,23 @@ export class ProcedureService extends BaseService {
581
643
  }
582
644
 
583
645
  const existingProcedure = procedureSnapshot.data() as Procedure;
584
- let updatedProcedureData: Partial<Procedure> = { ...validatedData };
646
+ let updatedProcedureData: Partial<Procedure> = {};
647
+
648
+ // Copy validated simple fields
649
+ if (validatedData.name !== undefined)
650
+ updatedProcedureData.name = validatedData.name;
651
+ if (validatedData.description !== undefined)
652
+ updatedProcedureData.description = validatedData.description;
653
+ if (validatedData.price !== undefined)
654
+ updatedProcedureData.price = validatedData.price;
655
+ if (validatedData.currency !== undefined)
656
+ updatedProcedureData.currency = validatedData.currency;
657
+ if (validatedData.pricingMeasure !== undefined)
658
+ updatedProcedureData.pricingMeasure = validatedData.pricingMeasure;
659
+ if (validatedData.duration !== undefined)
660
+ updatedProcedureData.duration = validatedData.duration;
661
+ if (validatedData.isActive !== undefined)
662
+ updatedProcedureData.isActive = validatedData.isActive;
585
663
 
586
664
  let practitionerChanged = false;
587
665
  let clinicChanged = false;
@@ -599,6 +677,22 @@ export class ProcedureService extends BaseService {
599
677
  );
600
678
  }
601
679
 
680
+ // Transform productsMetadata if provided
681
+ if (validatedData.productsMetadata !== undefined) {
682
+ const technologyId =
683
+ validatedData.technologyId ?? existingProcedure.technology.id;
684
+ if (!technologyId) {
685
+ throw new Error(
686
+ "Technology ID is required for updating products metadata"
687
+ );
688
+ }
689
+ updatedProcedureData.productsMetadata =
690
+ await this.transformProductsMetadata(
691
+ validatedData.productsMetadata,
692
+ technologyId
693
+ );
694
+ }
695
+
602
696
  // --- Prepare updates and fetch new related data if IDs change ---
603
697
 
604
698
  // Handle Practitioner Change
@@ -1479,6 +1573,12 @@ export class ProcedureService extends BaseService {
1479
1573
  );
1480
1574
  }
1481
1575
 
1576
+ // Transform productsMetadata from validation format to ProcedureProduct format
1577
+ const transformedProductsMetadata = await this.transformProductsMetadata(
1578
+ data.productsMetadata,
1579
+ data.technologyId
1580
+ );
1581
+
1482
1582
  // Create aggregated clinic info for the procedure document
1483
1583
  const clinicInfo = {
1484
1584
  id: clinicSnapshot.id,
@@ -1535,6 +1635,7 @@ export class ProcedureService extends BaseService {
1535
1635
  subcategory,
1536
1636
  technology,
1537
1637
  product: consultationProduct, // Use placeholder product
1638
+ productsMetadata: transformedProductsMetadata,
1538
1639
  blockingConditions: technology.blockingConditions,
1539
1640
  contraindications: technology.contraindications || [],
1540
1641
  contraindicationIds: technology.contraindications?.map((c) => c.id) || [],
@@ -20,6 +20,7 @@ import {
20
20
  Currency,
21
21
  } from "../../backoffice/types/static/pricing.types";
22
22
  import { MediaResource } from "../../services/media/media.service";
23
+ import type { ProcedureProduct } from "../../backoffice/types/procedure-product.types";
23
24
 
24
25
  /**
25
26
  * Procedure represents a specific medical procedure that can be performed by a practitioner in a clinic
@@ -44,15 +45,16 @@ export interface Procedure {
44
45
  subcategory: Subcategory;
45
46
  /** Technology used in this procedure */
46
47
  technology: Technology;
47
- /** Product used in this procedure */
48
+ /** Default product used in this procedure */
48
49
  product: Product;
49
- /** Price of the procedure */
50
+ /** Default price of the procedure */
50
51
  price: number;
51
52
  /** Currency for the price */
52
53
  currency: Currency;
53
- /** How the price is measured (per ml, per zone, etc.) */
54
+ /** How the price is measured (per ml, per zone, etc.) - for default product*/
54
55
  pricingMeasure: PricingMeasure;
55
56
  /** Duration of the procedure in minutes */
57
+ productsMetadata: ProcedureProduct[];
56
58
  duration: number;
57
59
  /** Blocking conditions that prevent this procedure */
58
60
  blockingConditions: BlockingCondition[];
@@ -104,6 +106,13 @@ export interface CreateProcedureData {
104
106
  technologyId: string;
105
107
  productId: string;
106
108
  price: number;
109
+ productsMetadata: {
110
+ productId: string;
111
+ price: number;
112
+ currency: Currency;
113
+ pricingMeasure: PricingMeasure;
114
+ isDefault?: boolean;
115
+ }[];
107
116
  currency: Currency;
108
117
  pricingMeasure: PricingMeasure;
109
118
  duration: number;
@@ -123,6 +132,13 @@ export interface UpdateProcedureData {
123
132
  price?: number;
124
133
  currency?: Currency;
125
134
  pricingMeasure?: PricingMeasure;
135
+ productsMetadata?: {
136
+ productId: string;
137
+ price: number;
138
+ currency: Currency;
139
+ pricingMeasure: PricingMeasure;
140
+ isDefault?: boolean;
141
+ }[];
126
142
  duration?: number;
127
143
  isActive?: boolean;
128
144
  practitionerId?: string;
@@ -0,0 +1,41 @@
1
+ import { z } from "zod";
2
+ import {
3
+ Currency,
4
+ PricingMeasure,
5
+ } from "../backoffice/types/static/pricing.types";
6
+
7
+ /**
8
+ * Schema for validating procedure product data.
9
+ * This is used when creating or updating a procedure to validate the products associated with it.
10
+ */
11
+ export const procedureProductDataSchema = z.object({
12
+ /**
13
+ * The ID of the product. Must be a non-empty string.
14
+ * @validation
15
+ */
16
+ productId: z.string().min(1, "Product ID is required"),
17
+
18
+ /**
19
+ * The price of the product. Must be a non-negative number.
20
+ * @validation
21
+ */
22
+ price: z.number().min(0, "Price must be a non-negative number"),
23
+
24
+ /**
25
+ * The currency for the price. Must be one of the values from the Currency enum.
26
+ * @validation
27
+ */
28
+ currency: z.nativeEnum(Currency),
29
+
30
+ /**
31
+ * The pricing measure for the product. Must be one of the values from the PricingMeasure enum.
32
+ * @validation
33
+ */
34
+ pricingMeasure: z.nativeEnum(PricingMeasure),
35
+
36
+ /**
37
+ * Whether this is the default product for the procedure.
38
+ * @validation
39
+ */
40
+ isDefault: z.boolean().optional(),
41
+ });
@@ -1,9 +1,45 @@
1
- import { z } from 'zod';
2
- import { ProcedureFamily } from '../backoffice/types/static/procedure-family.types';
3
- import { Currency, PricingMeasure } from '../backoffice/types/static/pricing.types';
4
- import { clinicInfoSchema, doctorInfoSchema } from './shared.schema';
5
- import { procedureReviewInfoSchema } from './reviews.schema';
6
- import { mediaResourceSchema } from './media.schema';
1
+ import { z } from "zod";
2
+ import { ProcedureFamily } from "../backoffice/types/static/procedure-family.types";
3
+ import {
4
+ Currency,
5
+ PricingMeasure,
6
+ } from "../backoffice/types/static/pricing.types";
7
+ import { clinicInfoSchema, doctorInfoSchema } from "./shared.schema";
8
+ import { procedureReviewInfoSchema } from "./reviews.schema";
9
+ import { mediaResourceSchema } from "./media.schema";
10
+ import { procedureProductDataSchema } from "./procedure-product.schema";
11
+
12
+ /**
13
+ * Schema for validating stored procedure product data (with full product objects).
14
+ * This is used when validating complete procedure documents from Firestore.
15
+ */
16
+ export const storedProcedureProductSchema = z.object({
17
+ /**
18
+ * The full product object used in the procedure.
19
+ */
20
+ product: z.any(), // We'll validate the full product object separately
21
+
22
+ /**
23
+ * The price of the procedure when using this specific product.
24
+ */
25
+ price: z.number().min(0, "Price must be a non-negative number"),
26
+
27
+ /**
28
+ * The currency for the price of this product.
29
+ */
30
+ currency: z.nativeEnum(Currency),
31
+
32
+ /**
33
+ * How the price is measured (e.g., per ml, per zone).
34
+ */
35
+ pricingMeasure: z.nativeEnum(PricingMeasure),
36
+
37
+ /**
38
+ * Whether this is the default product for the procedure.
39
+ */
40
+ isDefault: z.boolean().optional(),
41
+ });
42
+
7
43
  /**
8
44
  * Schema for creating a new procedure
9
45
  */
@@ -20,6 +56,7 @@ export const createProcedureSchema = z.object({
20
56
  price: z.number().min(0),
21
57
  currency: z.nativeEnum(Currency),
22
58
  pricingMeasure: z.nativeEnum(PricingMeasure),
59
+ productsMetadata: z.array(procedureProductDataSchema).min(1),
23
60
  duration: z.number().min(1).max(480), // Max 8 hours
24
61
  practitionerId: z.string().min(1),
25
62
  clinicBranchId: z.string().min(1),
@@ -36,6 +73,7 @@ export const updateProcedureSchema = z.object({
36
73
  price: z.number().min(0).optional(),
37
74
  currency: z.nativeEnum(Currency).optional(),
38
75
  pricingMeasure: z.nativeEnum(PricingMeasure).optional(),
76
+ productsMetadata: z.array(procedureProductDataSchema).min(1).optional(),
39
77
  duration: z.number().min(0).optional(),
40
78
  isActive: z.boolean().optional(),
41
79
  practitionerId: z.string().optional(),
@@ -48,18 +86,31 @@ export const updateProcedureSchema = z.object({
48
86
  });
49
87
 
50
88
  /**
51
- * Schema for validating a complete procedure object
89
+ * Schema for validating a complete procedure object (as stored in Firestore)
52
90
  */
53
- export const procedureSchema = createProcedureSchema.extend({
91
+ export const procedureSchema = z.object({
54
92
  id: z.string().min(1),
93
+ name: z.string().min(1).max(200),
55
94
  nameLower: z.string().min(1).max(200),
95
+ description: z.string().min(1).max(2000),
96
+ family: z.nativeEnum(ProcedureFamily),
56
97
  category: z.any(), // We'll validate the full category object separately
57
98
  subcategory: z.any(), // We'll validate the full subcategory object separately
58
99
  technology: z.any(), // We'll validate the full technology object separately
59
100
  product: z.any(), // We'll validate the full product object separately
101
+ productsMetadata: z.array(storedProcedureProductSchema).min(1), // Use stored format schema
102
+ price: z.number().min(0),
103
+ currency: z.nativeEnum(Currency),
104
+ pricingMeasure: z.nativeEnum(PricingMeasure),
105
+ duration: z.number().min(1).max(480),
106
+ practitionerId: z.string().min(1),
107
+ clinicBranchId: z.string().min(1),
108
+ photos: z.array(z.string()).optional(), // Stored as URL strings
60
109
  blockingConditions: z.array(z.any()), // We'll validate blocking conditions separately
61
110
  contraindications: z.array(z.any()), // We'll validate contraindications separately
111
+ contraindicationIds: z.array(z.string()), // Array of IDs for efficient querying
62
112
  treatmentBenefits: z.array(z.any()), // We'll validate treatment benefits separately
113
+ treatmentBenefitIds: z.array(z.string()), // Array of IDs for efficient querying
63
114
  preRequirements: z.array(z.any()), // We'll validate requirements separately
64
115
  postRequirements: z.array(z.any()), // We'll validate requirements separately
65
116
  certificationRequirement: z.any(), // We'll validate certification requirement separately