@clidey/dory 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +1 -1
  2. package/docs/api-playground-demo.mdx +119 -0
  3. package/docs/api-reference/openapi.json +366 -0
  4. package/docs/api-reference/operations/create.mdx +5 -0
  5. package/docs/api-reference/operations/delete.mdx +5 -0
  6. package/docs/api-reference/operations/get.mdx +5 -0
  7. package/docs/api-reference/operations/update.mdx +5 -0
  8. package/docs/assets/dory.jpeg +0 -0
  9. package/docs/dory.json +12 -131
  10. package/docs/favicon.svg +75 -0
  11. package/docs/features.mdx +440 -0
  12. package/docs/introduction.mdx +44 -0
  13. package/docs/logo/logo.png +0 -0
  14. package/package.json +3 -2
  15. package/src/mdx/source.tsx +15 -4
  16. package/docs/README.md +0 -2
  17. package/docs/configuration/app-settings/feature-flags.mdx +0 -157
  18. package/docs/configuration/app-settings/user-settings.mdx +0 -201
  19. package/docs/configuration/installation-setup/env-vars.mdx +0 -198
  20. package/docs/configuration/installation-setup/installation.mdx +0 -127
  21. package/docs/integrations/analytics-monitoring/error-tracking.mdx +0 -199
  22. package/docs/integrations/analytics-monitoring/notifications.mdx +0 -189
  23. package/docs/integrations/analytics-monitoring/user-analytics.mdx +0 -182
  24. package/docs/integrations/shopify-integration/shopify-setup.mdx +0 -226
  25. package/docs/integrations/shopify-integration/shopify-webhooks.mdx +0 -207
  26. package/docs/overview/developer-overview/dev-architecture.mdx +0 -292
  27. package/docs/overview/product-intro/app-overview.mdx +0 -167
  28. package/docs/overview/product-intro/architecture.mdx +0 -203
  29. package/docs/overview/product-intro/core-concepts.mdx +0 -267
  30. package/docs/platform-admin/billing-subscriptions/billing.mdx +0 -176
  31. package/docs/platform-admin/system-maintenance/db-migrations.mdx +0 -184
  32. package/docs/platform-admin/system-maintenance/health-monitoring.mdx +0 -222
  33. package/docs/platform-admin/system-maintenance/queue-management.mdx +0 -234
  34. package/docs/platform-admin/user-team-management/teams.mdx +0 -170
  35. package/docs/platform-admin/user-team-management/users.mdx +0 -185
  36. package/docs/support/legal/dependency-analysis.mdx +0 -132
  37. package/docs/support/legal/privacy-terms.mdx +0 -73
  38. package/docs/support/troubleshooting/common-issues.mdx +0 -159
  39. package/docs/usage/api-usage/api-inventory.mdx +0 -213
  40. package/docs/usage/api-usage/api-products.mdx +0 -249
  41. package/docs/usage/api-usage/api-purchase-orders.mdx +0 -289
  42. package/docs/usage/api-usage/api-reports.mdx +0 -227
  43. package/docs/usage/api-usage/api-suppliers.mdx +0 -171
  44. package/docs/usage/api-usage/api-user-management.mdx +0 -171
  45. package/docs/usage/ui-workflows/bundles.mdx +0 -157
  46. package/docs/usage/ui-workflows/demand-planning.mdx +0 -210
  47. package/docs/usage/ui-workflows/favorites.mdx +0 -167
  48. package/docs/usage/ui-workflows/inventory-management.mdx +0 -179
  49. package/docs/usage/ui-workflows/onboarding.mdx +0 -215
  50. package/docs/usage/ui-workflows/purchase-orders.mdx +0 -200
  51. package/docs/usage/ui-workflows/reports.mdx +0 -257
@@ -1,171 +0,0 @@
1
- ---
2
- title: 'Suppliers API'
3
- description: 'Management of suppliers and vendor import/export functionalities.'
4
- ---
5
-
6
- ## Suppliers API - Internal Developer Documentation
7
-
8
- ### 1. Purpose and Scope
9
-
10
- The Suppliers API is a core backend service within the Genie application responsible for managing supplier entities and their relationships to products and product variants. It enables operations such as creating, retrieving, updating, deleting suppliers, importing suppliers from CSV files, managing associations between suppliers and products, and handling supplier payment terms.
11
-
12
- This service directly supports the procurement workflow by maintaining up-to-date supplier data, ensuring synchronisation with products, and facilitating bulk operations via CSV imports. It operates within the team scope, ensuring data isolation per team.
13
-
14
- **System boundaries:**
15
- - Acts as an internal REST API controller exposing suppliers-related endpoints.
16
- - Interfaces with the database through TypeORM repositories for Supplier, Product, and related entities.
17
- - Integrates with the asset management service for handling attachments.
18
-
19
- **Architectural context:**
20
- - Part of the Supplier Module within the backend API service.
21
- - Leverages shared DTOs and schemas from the `@genie/shared` package for data validation.
22
-
23
- ### 2. Technical Overview
24
-
25
- The core of the Suppliers API is implemented via two classes:
26
- - `SuppliersController`: Exposes REST endpoints following NestJS controller patterns.
27
- - `SuppliersService`: Contains business logic and database interactions.
28
-
29
- #### Architecture and Integration
30
-
31
- ```mermaid
32
- flowchart TD
33
- subgraph "Backend API Service"
34
- SuppliersController["SuppliersController (REST Endpoints)"]:::controller
35
- SuppliersService["SuppliersService (Business Logic)"]:::service
36
- SupplierRepository["Supplier Repository (TypeORM)"]:::db
37
- ProductRepository["Product Repository (TypeORM)"]:::db
38
- ProductSupplierRepository["ProductSupplier Repository (TypeORM)"]:::db
39
- AssetsService["AssetsService (Asset Cleanup & Management)"]:::service
40
- end
41
-
42
- SuppliersController -->|"calls"| SuppliersService
43
- SuppliersService -->|"uses"| SupplierRepository
44
- SuppliersService -->|"uses"| ProductRepository
45
- SuppliersService -->|"uses"| ProductSupplierRepository
46
- SuppliersService -->|"calls"| AssetsService
47
-
48
- classDef controller fill:#74c0fc,stroke:#1c7ed6,color:#fff,stroke-width:1px;
49
- classDef service fill:#63e6be,stroke:#20c997,color:#044f1e,stroke-width:1px;
50
- classDef db fill:#ffa94d,stroke:#d9480f,color:#661a00,stroke-width:1px;
51
- ```
52
-
53
- #### Key technologies and frameworks
54
- - NestJS for API structure and dependency injection
55
- - TypeORM for database access with repository pattern
56
- - Zod for runtime schema validation
57
- - node-fetch and csv-parser for remote CSV import and parsing
58
- - Lodash for utility functions
59
-
60
- ### 3. Core Concepts and Responsibilities
61
-
62
- - **Team Boundary:** All supplier data belongs and is scoped to a `teamId` ensuring multi-tenancy.
63
- - **Supplier Entity:** Stores supplier data including contact info, address, lead time, minimum order quantity (MOQ), and payment terms.
64
- - **Product-Supplier Relationships:** Supports binding products and their variants to suppliers, including primary and secondary suppliers.
65
- - **Payment Terms:** Three types supported: Upfront, Net Days, and Installments. Payment terms are stored in separate entities linked to suppliers.
66
- - **CSV Import and Mapping:** The service supports importing suppliers and mapping supplier-product-variant relations via CSV files fetched over HTTP.
67
-
68
- ### 4. Code Structure
69
-
70
- Relevant files:
71
- - [SuppliersService](apps/api/src/supplier/services/suppliers.service.ts): Main service class implementing business logic.
72
- - [SuppliersController](apps/api/src/supplier/controllers/suppliers.controllers.ts): REST API endpoints.
73
-
74
- #### Key Files and Responsibilities
75
- | File | Responsibility |
76
- |---|---|
77
- | apps/api/src/supplier/services/suppliers.service.ts | Core supplier logic: CRUD, imports, product associations.
78
- | apps/api/src/supplier/controllers/suppliers.controllers.ts | HTTP endpoint handlers with validation and response formatting.
79
-
80
- #### Example: Creating a Supplier
81
- ```ts
82
- async createSupplier(teamId: string, data: CreateOrUpdateSupplierRequestDto) {
83
- const supplier = this.supplierRepository.create({
84
- ...data,
85
- teamId,
86
- });
87
- return await this.supplierRepository.save(supplier);
88
- }
89
- ```
90
-
91
- #### Example: Importing Suppliers from CSV
92
- ```ts
93
- private async parseSuppliersImportCSV(url: string) {
94
- const response = await fetch(url);
95
- if (!response.ok) throw new Error(`Failed to fetch file: ${response.statusText}`);
96
-
97
- return new Promise((resolve, reject) => {
98
- const results: SupplierDto[] = [];
99
- response.body.pipe(csvParser({ separator: ",", quote: '"' }))
100
- .on("data", (row) => {
101
- // map CSV rows to supplier data with contacts parsing
102
- })
103
- .on("end", () => resolve(results))
104
- .on("error", reject);
105
- });
106
- }
107
- ```
108
-
109
- ### 5. API and Interfaces
110
-
111
- Supported endpoints (via `SuppliersController`):
112
-
113
- | HTTP Method & Path | Purpose | Input Schema | Response Schema |
114
- |-------------------------------|---------------------------------------|-----------------------------------------------|-----------------------------|
115
- | POST `/suppliers` | List suppliers with filters/pagination | `GetSuppliersRequestDto` | `GetSuppliersResponseDto` |
116
- | GET `/suppliers/import-suppliers-template` | Download CSV template for import | None | CSV text |
117
- | GET `/suppliers/:id` | Get supplier detail by ID | Path param: supplier ID | `SupplierDto` |
118
- | POST `/suppliers/create` | Create a new supplier | `CreateOrUpdateSupplierRequestDto` | `SupplierDto` |
119
- | PUT `/suppliers/:id` | Update supplier details | `CreateOrUpdateSupplierRequestDto` | None (204 No Content) |
120
- | DELETE `/suppliers/:id` | Delete supplier | Path param: supplier ID | None (204 No Content) |
121
- | PUT `/suppliers/:id/attachmentUrls` | Update attachment URLs for supplier | `UpdateSupplierAttachmentUrlsRequestDto` | None (204 No Content) |
122
- | POST `/suppliers/get-importable-vendors` | Get vendors (not yet linked as suppliers) | None | array of vendor names |
123
- | POST `/suppliers/import-vendors` | Import vendors as suppliers | `ImportVendorsRequestDto` | None |
124
- | POST `/suppliers/:id/add-products` | Add products to supplier | `AddProductsRequestDto` | None (204 No Content) |
125
- | POST `/suppliers/:id/remove-products` | Remove products from supplier | `RemoveProductsRequestDto` | None (204 No Content) |
126
- | POST `/suppliers/import-suppliers` | Bulk import suppliers CSV | `ImportSuppliersRequestDto` | None |
127
- | POST `/suppliers/import-suppliers-products-mapping` | Bulk import supplier-product mappings | `ImportSuppliersProductsMappingRequestDto` | None |
128
-
129
- #### Validation
130
- All inputs are validated with Zod schemas imported from `@genie/shared`. Invalid data results in thrown exceptions with error details.
131
-
132
- #### Failure Modes
133
- - Not found errors throw `GenieException` with codes like `SupplierNotFound`, caught in controllers and return 404.
134
- - CSV parsing failures throw `GenieException` with validation error details.
135
-
136
- ### 6. Environment & Configuration
137
-
138
- No explicit environment variables or external config referenced within the Suppliers API service itself beyond the general backend API setup.
139
-
140
- Uses shared libraries such as `node-fetch` and `csv-parser` for CSV imports.
141
-
142
- ### 7. Testing, Monitoring, and Deployment
143
-
144
- Testing strategy details are not included in the provided context.
145
-
146
- The service uses structured exceptions (`GenieException`) for consistent error handling.
147
-
148
- Logging and error details are captured via exceptions but precise monitoring and alerting configurations are not specified.
149
-
150
- ### 8. Troubleshooting & Known Issues
151
-
152
- - Searching suppliers by country name is currently not supported since the entity stores only country codes.
153
-
154
- - Import CSV files must match strict schema validation or import operations fail.
155
-
156
- - When updating payment terms, only one payment term type is supported per supplier at a time and existing payment term records are deleted within a database transaction.
157
-
158
- ### 9. Style and Tone Guidelines
159
-
160
- - Code uses async/await for asynchronous operations.
161
- - Transactions are used for complex updates to maintain data consistency.
162
- - Clear separation of concerns between controller (HTTP) and service (logic).
163
-
164
- ---
165
-
166
- ### References
167
- - [SuppliersService](apps/api/src/supplier/services/suppliers.service.ts)
168
- - [SuppliersController](apps/api/src/supplier/controllers/suppliers.controllers.ts)
169
- - [Shared DTOs and Schemas](@genie/shared)
170
-
171
- ---
@@ -1,171 +0,0 @@
1
- ---
2
- title: 'User & Teams API'
3
- description: 'User context, team management, invitations, and user-related configuration.'
4
- ---
5
-
6
- ## User & Teams API - Developer Documentation
7
-
8
- ### 1. Purpose and Scope
9
-
10
- The **User & Teams API** module manages all aspects of user and team management within the Genie application. It handles team settings, user invitations, membership, notifications, and related configurations. The API ensures that users belong to teams, administrators manage memberships and invitations, and teams' settings and insights configurations are maintained.
11
-
12
- This component serves as a foundational building block for user management workflows, offering RESTful endpoints primarily through the `TeamsController` and backend logic encapsulated in the `TeamsService`. It supports administrative operations, user onboarding, and team lifecycle management.
13
-
14
- **System Boundaries:** This API interacts closely with other subsystems such as SettingsService (for team configurations), EmailService (sending invitations), JWT authentication (auth tokens on invitation acceptance), and Shopify integration (via team Shopify stores). It is a backend component used by frontend UI workflows and other backend processes.
15
-
16
- ### 2. Technical Overview
17
-
18
- The User & Teams API is implemented using the NestJS framework, leveraging decorators for routing and validation. The main controller is `TeamsController`, defined in `apps/api/src/user-management/controllers/teams.controller.ts`. Business logic is centralized in the `TeamsService` located at `apps/api/src/user-management/services/teams.service.ts`.
19
-
20
- Key technology and framework usage:
21
- - **NestJS**: For modular MVC structure and dependency injection.
22
- - **TypeORM**: For database interactions related to users, teams, and invitations.
23
- - **Zod**: For robust schema validation of request payloads and response transformations.
24
- - **JWT**: For token generation when a user accepts an invitation.
25
-
26
- The module enforces strict team membership checks before processing requests and uses structured exception handling (e.g., `GenieException`) for business logic errors.
27
-
28
- ### Mermaid Diagram
29
-
30
- ```mermaid
31
- flowchart TD
32
- subgraph API Layer
33
- direction TB
34
- TeamsController["TeamsController\n(apps/api/src/user-management/controllers/teams.controller.ts)"]:::service
35
- end
36
-
37
- subgraph Service Layer
38
- direction TB
39
- TeamsService["TeamsService\n(apps/api/src/user-management/services/teams.service.ts)"]:::service
40
- SettingsService["SettingsService"]
41
- EmailService["EmailService"]
42
- JwtService["JwtService"]
43
- end
44
-
45
- subgraph Data Layer
46
- direction TB
47
- UserEntity["UserEntity (DB)"]:::database
48
- TeamEntity["TeamEntity (DB)"]:::database
49
- MemberInvitationEntity["MemberInvitationEntity (DB)"]:::database
50
- end
51
-
52
- TeamsController -->|calls| TeamsService
53
- TeamsController -->|calls| SettingsService
54
- TeamsService -->|reads/writes| UserEntity
55
- TeamsService -->|reads/writes| TeamEntity
56
- TeamsService -->|reads/writes| MemberInvitationEntity
57
- TeamsService -->|sends email| EmailService
58
- TeamsService -->|generates token| JwtService
59
-
60
- classDef service fill:#def,stroke:#333,stroke-width:1px,color:#000
61
- classDef database fill:#ffd,stroke:#b28,stroke-width:1px,color:#000
62
-
63
- click TeamsController "apps/api/src/user-management/controllers/teams.controller.ts"
64
- click TeamsService "apps/api/src/user-management/services/teams.service.ts"
65
- ```
66
-
67
- ### 3. Core Concepts and Responsibilities
68
-
69
- - **Team Membership Enforcement:** Every endpoint validates that the acting user belongs to a team; otherwise, a `GenieException` is thrown.
70
- - **Invitation Lifecycle:** Invitations can be sent, verified (validated against existing users and teams), accepted (with token issuance), or removed.
71
- - **Role-Based Access:** Certain actions, such as deactivating users, require the acting user to be a Team Admin. This is explicitly checked via `UserRole.Admin`.
72
- - **Settings Management:** The module allows updating and retrieving team-related settings (general, insights, shop).
73
- - **Invitation Expiry and Validation:** Invitations are expired if older than a predefined age constant (`MAX_MEMBER_INVITE_AGE_DAYS`).
74
- - **Soft Deactivation of Users:** Deactivating a user anonymizes their email and clears sensitive fields, allowing reuse of the original email.
75
-
76
- **Ownership**: Maintained by the User Management Team.
77
-
78
- ### 4. Code Structure
79
-
80
- - **Controllers**
81
- - `TeamsController` handles HTTP routes under `/teams`, validating inputs using `ZodValidationPipe` and delegating logic to services.
82
-
83
- - **Services**
84
- - `TeamsService` performs user/team data operations, invitation management, and integration with Email and JWT.
85
-
86
- - **Entities**
87
- - Database entities (`UserEntity`, `TeamEntity`, `MemberInvitationEntity`) connect ORM to Postgres.
88
-
89
- - **DTOs and Validation Schemas**
90
- - Located under shared DTOs, e.g., `TeamSettingsDto`, `SendInvitationsRequestDto`.
91
-
92
- **Example Key Method:** Sending Team Invitations
93
-
94
- ```ts
95
- async sendInvitations({ teamId, userId, invitations }) {
96
- // Validate all invitations
97
- const errors = [];
98
- for (const inv of invitations) {
99
- const err = await this.validateInvitation(teamId, inv);
100
- if (err) errors.push({ email: inv.email, error: err });
101
- }
102
- if (errors.length) return { successful: false, invitationErrors: errors };
103
-
104
- // Expire existing invitations if any
105
- for (const inv of invitations) {
106
- const existing = await this.memberInvitationRepository.findOne({
107
- where: { teamId, email: inv.email, status: MemberInvitationStatus.Pending },
108
- });
109
- if (existing) {
110
- await this.memberInvitationRepository.update(existing.id, { status: MemberInvitationStatus.Expired });
111
- }
112
-
113
- // Create and save new invitation
114
- await this.memberInvitationRepository.save({
115
- teamId, inviterUserId: userId, email: inv.email, role: inv.role, status: MemberInvitationStatus.Pending
116
- });
117
-
118
- // Send invitation email
119
- await this.emailService.sendInvitationEmail(inv.email, existing.id || newInvitation.id, user.firstName);
120
- }
121
-
122
- return { successful: true };
123
- }
124
- ```
125
-
126
- ### 5. API and Interfaces
127
-
128
- The API exposes the following key endpoints in `TeamsController`:
129
-
130
- | HTTP Method | Endpoint | Description | Request Validation Schema | Requires team membership |
131
- |-------------|-------------------------|------------------------------------------------|------------------------------------------------|--------------------------|
132
- | PUT | /teams/settings | Update team-wide settings | `teamSettingsDtoSchema` | Yes |
133
- | PUT | /teams/settings/general | Update general team settings | `teamGeneralSettingsDtoSchema` | Yes |
134
- | GET | /teams/settings/general | Retrieve general team settings | N/A | Yes |
135
- | PUT | /teams/settings/insights| Update team insights settings | `insightsSettingsSchema` | Yes |
136
- | GET | /teams/settings/insights| Retrieve team insights settings | N/A | Yes |
137
- | GET | /teams/settings/shop | Get team's Shopify shop settings | N/A | Yes |
138
- | GET | /teams/members | Get list of team members and invitations | N/A | Yes |
139
- | POST | /teams/send-invitations | Send invitations to new members | `sendInvitationsRequestDtoSchema` | Yes |
140
- | PATCH | /teams/user/:id/deactivate | Deactivate a user by ID | N/A | Yes, Admin only |
141
- | DELETE | /teams/invitations/:email| Remove pending invitation by email | N/A | Yes |
142
- | POST | /teams/accept-invitation | Accept an invitation using a code (public) | `AcceptInvitationRequestDto` | No |
143
-
144
- **Failure modes**:
145
- - Actions throw `GenieException` if the user is not assigned to a team.
146
- - Only Admins can deactivate users.
147
- - Invitation acceptance fails with `ForbiddenException` on invalid, expired codes, or email conflicts.
148
-
149
- Authentication and Authorization are managed implicitly by checking `user.teamId` and `user.role`.
150
-
151
- ### 6. Environment & Configuration
152
-
153
- No explicit environment variables are required specifically by this module mentioned in context. However, it depends on:
154
- - EmailService for invitation emails.
155
- - JWT secret for signing tokens.
156
-
157
- Local development requires connection to the appropriate database used by TypeORM.
158
-
159
- ### 7. Testing, Monitoring, and Deployment
160
-
161
- Testing specifics are not provided. The module uses NestJS conventions allowing unit and integration tests for controllers and services.
162
-
163
- Monitoring and error logging happen via `GenieException` with structured logging.
164
-
165
- ### 8. Troubleshooting & Known Issues
166
-
167
- No explicit troubleshooting or common issues are documented.
168
-
169
- ### Summary
170
-
171
- The User & Teams API manages team member lifecycle, settings, and invitations with a focus on security, validation, and up-to-date team data management. The modular pattern and strong typing with DTOs and Zod schemas make it robust and maintainable. Understanding the team membership checks and invitation handling flow is key to working with this codebase.
@@ -1,157 +0,0 @@
1
- ---
2
- title: 'Bundles Management'
3
- description: 'Managing product bundles, adding or editing bundled products, and bulk operations.'
4
- ---
5
-
6
- ## Bundles Management - Internal Developer Documentation
7
-
8
- ### 1. Purpose and Scope
9
-
10
- The Bundles Management subsystem is responsible for handling product bundles within the Genie platform. Bundles represent products composed of multiple standalone components, allowing the system to track aggregate sales data while managing individual components separately. This module manages CRUD operations on bundles and their components, synchronizes bundles with purchase orders, and supports upstream and downstream data consistency.
11
-
12
- This subsystem operates within the Product Information Management (PIM) context and interfaces closely with key services such as purchase order processing and team management. It solves the problem of associating bundles' sales attribution to component products, ensuring data cleanliness, and maintaining bundle mappings in sync with inventory and sales data.
13
-
14
- ### 2. Technical Overview
15
-
16
- Bundles are implemented primarily via specialized `ProductVariantEntity` entries where the variant `type` is set to `InventoryItemType.Bundle`. Components of bundles are managed via `ProductVariantComponentEntity` entities that link parent (bundle) variants to child (standalone) product variants with specified quantities.
17
-
18
- The system employs a layered architecture with clear separation:
19
- - **API/Controller Layer**: e.g., `BundlesController` handles HTTP requests related to bundle operations and team inventory migrations.
20
- - **Service Layer**: e.g., `ProductsMappingService` and `PoBundlesService` encapsulate business logic for bundle creation, deletion, updates, and purchase order synchronization.
21
-
22
- Key technologies include:
23
- - NestJS framework with dependency injection and decorators.
24
- - TypeORM as the ORM for database abstraction.
25
- - PostgreSQL for relational storage with SQL queries optimized for bundle and component retrieval.
26
-
27
- Design patterns:
28
- - **Repository pattern** via TypeORM repositories.
29
- - Upsert operations to handle idempotent creation or updates of components.
30
- - Transactional integrity ensuring consistency when modifying bundles and components.
31
-
32
- ### Mermaid Diagram of Core Components and Relationships
33
-
34
- ```mermaid
35
- flowchart TD
36
- subgraph Backend Services
37
- BundlesController["BundlesController (API Layer)"]:::controller
38
- ProductsMappingService["ProductsMappingService (Bundle Logic)"]:::service
39
- PoBundlesService["PoBundlesService (PO Bundle Sync)"]:::service
40
- TeamsService["TeamsService (Team Management)"]:::service
41
- end
42
-
43
- subgraph Database
44
- ProductEntity[("ProductEntity (Products Table)")]
45
- ProductVariantEntity[("ProductVariantEntity (Variants Table)")]
46
- ProductVariantComponentEntity[("ProductVariantComponentEntity (Bundle Components)")]
47
- PurchaseOrderItemEntity[("PurchaseOrderItemEntity (PO Items)")]
48
- PurchaseOrderBundleItemEntity[("PurchaseOrderBundleItemEntity (PO Bundle Items)")]
49
- end
50
-
51
- BundlesController -->|"calls"| TeamsService
52
- BundlesController -->|"calls"| PoBundlesService
53
- PoBundlesService -->|"uses Repos"| PurchaseOrderItemEntity
54
- PoBundlesService -->|"uses Repos"| PurchaseOrderBundleItemEntity
55
- ProductsMappingService -->|"updates"| ProductVariantEntity
56
- ProductsMappingService -->|"manages"| ProductVariantComponentEntity
57
- ProductsMappingService -->|"delegates"| PoBundlesService
58
- ProductVariantComponentEntity -->|"links"| ProductVariantEntity
59
- PurchaseOrderBundleItemEntity -->|"linked with"| ProductEntity
60
-
61
- classDef controller fill:#55aaff,stroke:#004466,color:#fff
62
- classDef service fill:#ffaa55,stroke:#664400,color:#000
63
- ```
64
-
65
- ### 3. Core Concepts and Responsibilities
66
-
67
- - **Bundle vs StandAlone Variants**: Variants of type `InventoryItemType.Bundle` represent bundles; others are standalone.
68
- - **Bundle Components**: Components link bundle variants (parents) to standalone variants (children) with quantities.
69
- - **Purchase Order Bundle Synchronization**: Bundles are reflected in purchase orders via `PurchaseOrderBundleItemEntity`.
70
- - **Bundle Status**: Bundles can have statuses such as `SetupComplete`, `SetupIncomplete`, `ErrorInUpdate`, and `SetupNotStarted` based on completeness and validity of component mappings.
71
-
72
- Ownership of this subsystem lies with the PIM team, with logs and error captures routed through the `Logger` instances in services and exceptions like `GenieException`.
73
-
74
- Non-functional requirements include:
75
- - **Performance**: Efficient SQL queries with joins, indexing to handle large product sets.
76
- - **Reliability**: Use of transactions and upserts to maintain consistent state.
77
- - **Scalability**: Supports bulk updates and paginated queries for large product catalogs.
78
-
79
- ### 4. Code Structure
80
-
81
- - **Controllers**
82
- - `apps/api/src/admin/controllers/bundles.controller.ts`
83
- - Entry point for admin-level bundle operations, such as migrating team inventory to bundle items.
84
-
85
- - **Services**
86
- - `apps/api/src/pim/services/products-mapping.service.ts`
87
- - Core business logic for creating/deleting bundles and managing bundle components.
88
- - Handles bundle retrieval with detailed component data and supports bulk CSV exports.
89
- - `apps/api/src/purchase-order/services/po-bundles.service.ts`
90
- - Manages synchronization of bundles within purchase orders.
91
- - Converts item bundles to purchase order bundle items and removes orphaned bundle data.
92
-
93
- - **API Exports**
94
- - `apps/web/src/api/resources/products-mapping/index.ts`
95
- - Aggregates bundle-related API calls including add, remove, get bundle and bundle components operations.
96
-
97
- #### Key Files and Their Roles
98
- - [apps/api/src/pim/services/products-mapping.service.ts](apps/api/src/pim/services/products-mapping.service.ts): Implements main domain logic for bundles.
99
- - [apps/api/src/purchase-order/services/po-bundles.service.ts](apps/api/src/purchase-order/services/po-bundles.service.ts): Sync bundles with purchase order data.
100
- - [apps/api/src/admin/controllers/bundles.controller.ts](apps/api/src/admin/controllers/bundles.controller.ts): Admin API controller for bundle-related commands.
101
-
102
- #### Code Snippet: Creating Bundles
103
- ```ts
104
- async createBundles(teamId: string, ids: string[]): Promise<void> {
105
- await this.productVariantRepository.update(
106
- { productId: In(ids), teamId },
107
- { type: InventoryItemType.Bundle }
108
- );
109
-
110
- await this.poBundlesService.convertItemBundlesToPOBundleItems(teamId);
111
- }
112
- ```
113
- This updates product variants to type `Bundle` for given product IDs and then synchronizes purchase order bundle items accordingly.
114
-
115
- ### 5. API and Interfaces
116
-
117
- #### BundlesController
118
- - POST `/admin/bundles/migrate-all-teams-inventory-to-bundle-items`
119
- - Migrates all active teams' inventory items identifying as bundles to purchase order bundle items.
120
-
121
- #### ProductsMappingService Public Methods
122
- - `createBundles(teamId: string, ids: string[])` - Marks specified products as bundles.
123
- - `deleteBundles(teamId: string, ids: string[])` - Removes bundles and reverts variants back to standalone.
124
- - `updateComponentsQuantities(teamId: string, componentQuantities)` - Batch update quantities of components within bundles.
125
- - `createBundleVariantsComponents(teamId: string, bundleVariantsComponents)` - Creates component mappings for bundle variants.
126
- - `deleteComponents(teamId: string, componentIds: string[])` - Deletes bundle components by IDs.
127
- - `getBundle(teamId: string, bundleId: string)` - Retrieves bundle details including variants and components.
128
- - `getBundlesByProducts(teamId: string, queryParams)` - Retrieves paginated bundles list with statuses and component products.
129
- - `getBundlesCsvMap(teamId: string)` - Exports component mapping data as CSV.
130
-
131
- #### Failure Modes
132
- - `getBundle` throws `GenieException` with code `BundleNotFound` if bundle ID does not exist or if the product is not a bundle.
133
- - Attempts to create components where parent is not a bundle or children are bundles raise `GenieException` with relevant error codes.
134
-
135
- ### 6. Environment & Configuration
136
-
137
- No explicit environment variables or external config parameters were found specifically related to bundles management in the provided context.
138
-
139
- ### 7. Testing, Monitoring, and Deployment
140
-
141
- No direct information about tests, logs, deployment, or monitoring specific to bundles was given in the current context. Logging uses NestJS `Logger` class for error and operation tracing within services.
142
-
143
- ### 8. Troubleshooting & Known Issues
144
-
145
- - The `PoBundlesService` logs to Console if a purchase order item has an undefined product variant during conversion.
146
- - `ProductsMappingService` tracks invalid bundle relations and handles bundle component update failures with exception captures.
147
- - Bundles with no child components get reverted to standalone variants on relation removals.
148
-
149
- ### References
150
- - `apps/api/src/pim/services/products-mapping.service.ts`
151
- - `apps/api/src/purchase-order/services/po-bundles.service.ts`
152
- - `apps/api/src/admin/controllers/bundles.controller.ts`
153
- - `apps/web/src/api/resources/products-mapping/index.ts`
154
-
155
- ---
156
-
157
- This documentation serves as the foundation for maintaining and extending bundles management within Genie's PIM system, facilitating understanding of core logic, integration points, and design decisions involved.