@clidey/dory 0.1.0 → 0.3.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 (53) 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 +9 -10
  15. package/src/mdx/fence.tsx +2 -1
  16. package/src/mdx/mermaid.tsx +39 -11
  17. package/src/mdx/source.tsx +15 -4
  18. package/docs/README.md +0 -2
  19. package/docs/configuration/app-settings/feature-flags.mdx +0 -157
  20. package/docs/configuration/app-settings/user-settings.mdx +0 -201
  21. package/docs/configuration/installation-setup/env-vars.mdx +0 -198
  22. package/docs/configuration/installation-setup/installation.mdx +0 -127
  23. package/docs/integrations/analytics-monitoring/error-tracking.mdx +0 -199
  24. package/docs/integrations/analytics-monitoring/notifications.mdx +0 -189
  25. package/docs/integrations/analytics-monitoring/user-analytics.mdx +0 -182
  26. package/docs/integrations/shopify-integration/shopify-setup.mdx +0 -226
  27. package/docs/integrations/shopify-integration/shopify-webhooks.mdx +0 -207
  28. package/docs/overview/developer-overview/dev-architecture.mdx +0 -292
  29. package/docs/overview/product-intro/app-overview.mdx +0 -167
  30. package/docs/overview/product-intro/architecture.mdx +0 -203
  31. package/docs/overview/product-intro/core-concepts.mdx +0 -267
  32. package/docs/platform-admin/billing-subscriptions/billing.mdx +0 -176
  33. package/docs/platform-admin/system-maintenance/db-migrations.mdx +0 -184
  34. package/docs/platform-admin/system-maintenance/health-monitoring.mdx +0 -222
  35. package/docs/platform-admin/system-maintenance/queue-management.mdx +0 -234
  36. package/docs/platform-admin/user-team-management/teams.mdx +0 -170
  37. package/docs/platform-admin/user-team-management/users.mdx +0 -185
  38. package/docs/support/legal/dependency-analysis.mdx +0 -132
  39. package/docs/support/legal/privacy-terms.mdx +0 -73
  40. package/docs/support/troubleshooting/common-issues.mdx +0 -159
  41. package/docs/usage/api-usage/api-inventory.mdx +0 -213
  42. package/docs/usage/api-usage/api-products.mdx +0 -249
  43. package/docs/usage/api-usage/api-purchase-orders.mdx +0 -289
  44. package/docs/usage/api-usage/api-reports.mdx +0 -227
  45. package/docs/usage/api-usage/api-suppliers.mdx +0 -171
  46. package/docs/usage/api-usage/api-user-management.mdx +0 -171
  47. package/docs/usage/ui-workflows/bundles.mdx +0 -157
  48. package/docs/usage/ui-workflows/demand-planning.mdx +0 -210
  49. package/docs/usage/ui-workflows/favorites.mdx +0 -167
  50. package/docs/usage/ui-workflows/inventory-management.mdx +0 -179
  51. package/docs/usage/ui-workflows/onboarding.mdx +0 -215
  52. package/docs/usage/ui-workflows/purchase-orders.mdx +0 -200
  53. package/docs/usage/ui-workflows/reports.mdx +0 -257
@@ -1,215 +0,0 @@
1
- ---
2
- title: 'User Onboarding'
3
- description: 'Step-by-step user onboarding workflow including product syncing, bundle mapping, excluding products, and favorite products setup.'
4
- ---
5
-
6
- # User Onboarding - Internal Developer Documentation
7
-
8
- ## 1. Purpose and Scope
9
-
10
- The **Onboarding** functionality orchestrates the initial setup flow for new teams and users within Genie. It ensures teams are properly configured with products, bundles, purchase orders, and settings necessary for smooth operation. This service-driven onboarding process allows new users to start using Genie effectively and ensures the backend tracks and verifies onboarding progress to completion.
11
-
12
- **System Boundaries and Context:**
13
- - The onboarding service is primarily part of the backend API layer under `setup/services/onboarding.service.ts`.
14
- - It interacts closely with user and team management services, Shopify integration components, product management, purchase order services, workflow services, and notification components.
15
- - It manages persistent onboarding state stored in the database (`OnboardingProgressEntity` and related entities).
16
-
17
- This module is critical for initializing and validating new team environments and monitoring onboarding status to drive the user onboarding UI and workflows.
18
-
19
- ## 2. Technical Overview
20
-
21
- ### Architectural Placement
22
-
23
- Onboarding is implemented as a NestJS injectable service (`OnboardingService`) that encapsulates business logic related to onboarding progress and related workflows.
24
-
25
- It consumes the following key dependencies:
26
- - `TeamsService` for user and team context and updates
27
- - `ShopifyStoreService` for store details and status
28
- - `ProductsService` and `ShopifyProductsService` for product data syncing and variants counts
29
- - `PurchaseOrdersService` to manage purchase order data syncing and notifications
30
- - `WorkflowService` to trigger bundle mapping workflows
31
- - `SlackService` and tracking services for notifications and telemetry
32
-
33
- A high-level data and interaction flow is as follows:
34
- - Onboarding progress is stored and updated in `OnboardingProgressEntity`
35
- - The service runs data sync flows to import products, orders, and settings from Shopify
36
- - Tracks confirmation steps users complete (e.g., settings, grading, suppliers)
37
- - Onboarding completion triggers enabling the team and initializing webhook registrations
38
- - Manages bundle products and purchase order import tracking
39
- - Provides APIs for front-end to query progress and update steps
40
-
41
-
42
- ```mermaid
43
- flowchart TD
44
- subgraph Backend API
45
- O["OnboardingService"]:::service
46
- T["TeamsService"]:::service
47
- SS["ShopifyStoreService"]:::service
48
- PS["ProductsService"]:::service
49
- PO["PurchaseOrdersService"]:::service
50
- WF["WorkflowService"]:::service
51
- SL["SlackService"]:::service
52
- JWT["JWT Service"]:::service
53
- end
54
-
55
- DB["Database (Postgres Entities)"]:::database
56
-
57
- subgraph User Management
58
- U["UserEntity"]:::entity
59
- TM["TeamEntity"]:::entity
60
- end
61
-
62
- subgraph Shopify Integration
63
- SP["ShopifyStore"]:::external
64
- SPProd["Shopify Products"]:::external
65
- end
66
-
67
- UI["Onboarding UI"]:::frontend
68
-
69
- UI -->|queries| O
70
- O -->|uses| T
71
- O -->|uses| SS
72
- O -->|uses| PS
73
- O -->|uses| PO
74
- O -->|uses| WF
75
- O -->|uses| SL
76
- O -->|updates| DB
77
- T -->|manages| TM
78
- T -->|manages| U
79
- SS --> SP
80
- PS --> SPProd
81
-
82
- classDef service fill:#6fcf97,stroke:#2d6a4f,color:#fff,stroke-width:1px
83
- classDef database fill:#ffd6a5,stroke:#b06500,color:#000,stroke-width:1px
84
- classDef entity fill:#f9c74f,stroke:#f9844a,color:#000,stroke-width:1px
85
- classDef external fill:#90e0ef,stroke:#0077b6,color:#000,stroke-width:1px
86
- classDef frontend fill:#f72585,stroke:#9d174d,color:#fff,stroke-width:1px
87
-
88
- click O "apps/api/src/setup/services/onboarding.service.ts"
89
- click T "apps/api/src/user-management/services/teams.service.ts"
90
-
91
- ```
92
-
93
- ## 3. Core Concepts and Responsibilities
94
-
95
- - **Onboarding Progress Tracking:** Maintains persistent state per team of which onboarding steps have been completed and which required data syncs are done.
96
- - **Data Sync:** Triggers asynchronous data import flows for Shopify products, purchase orders, and settings to prepare the environment.
97
- - **Step Confirmation:** Tracks user confirmations of key setup steps such as insights settings, grading, suppliers, orders import, favorites, exclusions, bundle setup, and final completion.
98
- - **Invitation and User Management:** Managed by `TeamsService` with invitations, user creation/assignment, and deactivation as part of onboarding.
99
- - **Bundle Products:** Supports onboarding flows for identifying and mapping bundle products.
100
- - **Notifications & Tracking:** Integrates with Slack service and internal tracking events to alert admins and monitor progress.
101
-
102
- ### Ownership & Maintenance
103
- - Owned by backend platform team - service located in `setup/services/onboarding.service.ts`.
104
- - Logs errors and exceptions via the logger and centralized capture mechanisms.
105
-
106
- ### Non-Functional Requirements
107
- - **Reliability:** Onboarding flows support resuming after outages or server restarts (`resumeOnboardingProgressFlows`).
108
- - **Performance:** Implements deduplicated job queues for long-running syncs.
109
- - **Security:** Access to updating onboarding state requires authenticated user's team context.
110
-
111
- ## 4. Code Structure
112
-
113
- ### Key Files
114
- - `apps/api/src/setup/services/onboarding.service.ts`
115
- - Core business logic and state management
116
- - Integrates with all other services mentioned
117
- - `apps/api/src/setup/controllers/onboarding.controller.ts`
118
- - REST API layer exposing onboarding endpoints
119
- - Validates user team context before delegating to service
120
- - `apps/api/src/user-management/services/teams.service.ts`
121
- - Manages user invitations, team users, and onboarding step updates
122
-
123
- ### Important Code Excerpt - Progress Retrieval
124
- ```ts
125
- async getProgress(teamId: string): Promise<GetOnboardingProgressResponseDto> {
126
- const progress = await this.progressRepository.findOneOrFail({ where: { teamId } });
127
- return {
128
- steps: {
129
- hasInsightSettingsStepConfirmed: progress.hasInsightSettingsStepConfirmed,
130
- hasGradingStepConfirmed: progress.hasGradingStepConfirmed,
131
- hasSuppliersStepConfirmed: progress.hasSuppliersStepConfirmed,
132
- hasImportPurchaseOrdersStepConfirmed: progress.hasImportPurchaseOrdersStepConfirmed,
133
- hasFavouriteProductsStepConfirmed: progress.hasFavouriteProductsStepConfirmed,
134
- hasExcludeProductsStepConfirmed: progress.hasExcludeProductsStepConfirmed,
135
- hasBundleMappingStepConfirmed: progress.hasBundleMappingStepConfirmed,
136
- hasSetupCompleteStepConfirmed: progress.hasSetupCompleteStepConfirmed,
137
- },
138
- data: {
139
- hasPimDataSynced: progress.hasPimDataSynced,
140
- hasInitialOrdersDataSynced: progress.hasInitialOrdersDataSynced,
141
- },
142
- };
143
- }
144
- ```
145
-
146
- ### Entry Points and Main Flows
147
- - **Initialization:** `initOnboardingProgress(teamId)` - sets initial progress if none exists, checks variant count constraints.
148
- - **Progress Updates:** `updateProgressSteps(teamId, steps)` updates partial step confirmations and triggers completion check asynchronously.
149
- - **Completion:** `ensureCompletion(teamId)` called post-step confirmation and data sync to finalize onboarding.
150
- - **Data Sync:** `ensureDataSync(teamId)` triggers deduplicated workflow jobs to sync Shopify data.
151
- - **Resume:** `resumeOnboardingProgressFlows()` resumes all incomplete onboarding sync flows after downtime.
152
-
153
- ## 5. API and Interfaces
154
-
155
- ### Controller Endpoints (exposed via `/onboarding`)
156
-
157
- | Method | Path | Description | Request Body/Params | Response |
158
- |--------|---------------------------|--------------------------------------------|------------------------------------------------|--------------------------------|
159
- | GET | /progress | Retrieve onboarding progress for user's team | Authenticated user context (teamId required) | Onboarding progress DTO |
160
- | PUT | /progress | Update progress steps | Partial confirmation steps DTO | 204 No Content |
161
- | PUT | /purchase-orders/import | Update purchase order import URLs | PurchaseOrdersImport DTO | 204 No Content |
162
- | GET | /purchase-orders/import | Get purchase order import URLs | Authenticated user context | PurchaseOrdersImport DTO |
163
- | PUT | /bundle-products | Update bundle products setup state | BundleProducts DTO | 204 No Content |
164
- | GET | /bundle-products | Get bundle products | Authenticated user context | BundleProductsResponse DTO |
165
- | GET | /shopify-products-variants-count | Get count of Shopify product variants | Authenticated user context | Count DTO |
166
- | POST | /setup-subscription | Assign default plan/subscription | Authenticated user context | Redirect URL DTO for payment |
167
-
168
- ### Validation
169
- - All inputs use Zod schemas for validation.
170
- - Requests require users to be assigned to a team; otherwise, exceptions are thrown.
171
-
172
- ### Failure Modes & Edge Cases
173
- - Missing or invalid team associations cause errors.
174
- - Teams exceeding maximum allowed product variants are disabled automatically.
175
- - Data sync workflows use deduplication to avoid duplicate job execution.
176
-
177
- ## 6. Environment & Configuration
178
-
179
- - **Env Vars used include:**
180
- - `INTERCOM_IDENTITY_VERIFICATION_SECRET` for user hash generation.
181
- - `MANTLE_FREE_PLAN_ID` to identify free subscription plans.
182
- - Slack related tokens and channel IDs such as `SLACK_APP_TOKEN`, `SLACK_APP_USER_REQUESTS_CHANNEL_ID`, `SLACK_APP_SYSTEM_ALERTS_CHANNEL_ID` for notifications.
183
-
184
- - ConfigService manages and exposes these values.
185
-
186
- ## 7. Testing, Monitoring, and Deployment
187
-
188
- - Service uses NestJS logger (`Logger`) and centralized exception capturing (`captureException`).
189
- - Includes telemetry via tracking events, e.g., when onboarding status changes or bundle products imported.
190
- - Slack service integration sends onboarding notifications.
191
- - Onboarding flows are resilient and resume on server restarts.
192
-
193
- ## 8. Troubleshooting & Known Issues
194
-
195
- - Teams with excessive Shopify product variants are automatically disabled to prevent system overload.
196
- - Onboarding progress resumes automatically but manual triggers exist for admins via `/admin/onboarding/resume-all-teams` or `/admin/onboarding/resume-for-team`.
197
-
198
- ## 9. Style and Tone
199
-
200
- - Documentation follows concise, declarative style.
201
- - Terminology aligns with Genie codebase (e.g., `teamId`, `UserEntity`, `OnboardingProgressEntity`).
202
- - Use code links for ease of navigation.
203
-
204
- ---
205
-
206
- ## References to Key Source Files
207
-
208
- - [Onboarding Service](apps/api/src/setup/services/onboarding.service.ts)
209
- - [Onboarding Controller](apps/api/src/setup/controllers/onboarding.controller.ts)
210
- - [Teams Service](apps/api/src/user-management/services/teams.service.ts)
211
- - [Slack Service](apps/api/src/slack/services/slack.service.ts)
212
-
213
- ---
214
-
215
- This document enables developers to understand the onboarding domain fully and guides maintenance or enhancement work efficiently.
@@ -1,200 +0,0 @@
1
- ---
2
- title: 'Purchase Orders'
3
- description: 'Creating, editing, viewing, and managing purchase orders including shipments, payments, bundles, and export options.'
4
- ---
5
-
6
- ## Purchase Orders - Internal Developer Documentation
7
-
8
- ### Purpose and Scope
9
-
10
- The Purchase Orders module manages all aspects of purchase order (PO) lifecycle within the Genie system. It encompasses creation, retrieval, updating, deleting, shipment handling, payment processing, and exporting purchase orders. This module is responsible for ensuring accurate PO data management, shipment tracking, cost calculations, and integration with external systems such as Shopify and email notifications.
11
-
12
- This module defines the system boundary around Purchase Order business logic and persistence, exposing APIs consumed by the web frontend and internal services.
13
-
14
- ---
15
-
16
- ### Technical Overview
17
-
18
- Purchase Orders are implemented as a backend service with a RESTful API layer and paired frontend components for UI interaction. The backend is primarily encapsulated in the `PurchaseOrdersService` class, supported by related controllers and repositories. The frontend UI includes React components for form handling, editing, and actions on purchase orders.
19
-
20
- #### Architecture Diagram
21
-
22
- ```mermaid
23
- flowchart TD
24
- subgraph Backend["Backend Services"]
25
- direction TB
26
- POService["PurchaseOrdersService"]:::service
27
- POController["PurchaseOrdersController"]:::controller
28
- POBundlesService["PoBundlesService"]:::service
29
- ExportService["ExportService"]:::service
30
- ShopifyService["ShopifyProductsService"]:::service
31
- EmailService["EmailService"]:::service
32
- SlackService["SlackService"]:::service
33
- TeamsService["TeamsService"]:::service
34
- AssetsService["AssetsService"]:::service
35
- WorkflowService["WorkflowService"]:::service
36
- PORepository[("PurchaseOrderEntity Repository")]:::db
37
- POItemRepository[("PurchaseOrderItemEntity Repository")]:::db
38
- POShipmentRepository[("PurchaseOrderShipmentEntity Repository")]:::db
39
- POShipmentItemRepository[("PurchaseOrderShipmentItemEntity Repository")]:::db
40
- POPaymentRepository[("PurchaseOrderPaymentEntity Repository")]:::db
41
- LocationRepository[("LocationEntity Repository")]:::db
42
- end
43
-
44
- subgraph Frontend["Web Frontend"]
45
- direction TB
46
- POForm["PurchaseOrderForm Component"]:::frontend
47
- POPage["PurchaseOrder Page"]:::frontend
48
- end
49
-
50
- POController -->|calls| POService
51
- POService -->|uses DB access| PORepository
52
- POService -->|uses DB access| POItemRepository
53
- POService -->|uses DB access| POShipmentRepository
54
- POService -->|uses DB access| POShipmentItemRepository
55
- POService -->|uses DB access| POPaymentRepository
56
- POService -->|uses DB access| LocationRepository
57
- POService -->|calls| ShopifyService
58
- POService -->|calls| ExportService
59
- POService -->|calls| EmailService
60
- POService -->|calls| SlackService
61
- POService -->|calls| TeamsService
62
- POService -->|calls| WorkflowService
63
- POService -->|calls| AssetsService
64
- POService -->|calls| POBundlesService
65
-
66
- POController -->|serves| POPage
67
- POPage -->|wraps with FormProvider| POForm
68
- POForm -->|calls API via hooks| POService
69
-
70
- classDef service fill:#4a90e2,stroke:#1c5480,color:#ffffff,stroke-width:1px;
71
- classDef controller fill:#f5a623,stroke:#b07000,color:#000000,stroke-width:1px;
72
- classDef db fill:#7ed321,stroke:#4b7100,color:#000000,stroke-width:1px,stroke-dasharray: 5 5;
73
- classDef frontend fill:#9013fe,stroke:#5b0a9b,color:#ffffff,stroke-width:1px;
74
-
75
- click POService "apps/api/src/purchase-order/services/purchase-orders.service.ts"
76
- click POController "apps/api/src/purchase-order/controllers/purchase-orders.controller.ts"
77
- click ExportService "apps/api/src/admin/services/export.service.ts"
78
- click POForm "apps/web/src/components/pages/purchase-order/index.tsx"
79
- ```
80
-
81
- ---
82
-
83
- ### Core Concepts and Responsibilities
84
-
85
- - **PurchaseOrderEntity**: Represents a purchase order in the database, including status, supplier, currency, and associated items and shipments.
86
- - **PurchaseOrderItemEntity**: Represents individual items within a PO, linked to product variants and containing quantity, cost, and SKU info.
87
- - **PurchaseOrderShipmentEntity**: Represents shipments linked to a PO, contains shipment details, costs, and status (e.g., received or not).
88
- - **PurchaseOrderPaymentEntity**: Details payments against the PO, with status tracking (paid, not paid).
89
- - **Supplier Integration**: Suppliers and related product variants are linked to enable default unit costs and SKUs.
90
- - **Bundles**: Support for grouped products appearing as bundles, handled both in backend (`PoBundlesService`) and frontend UI (`BundlesCard`).
91
- - **Shipment Receipt & Shopify Sync**: Backend updates stock quantities on shipment receipt, optionally pushing changes to Shopify inventories.
92
-
93
- #### Ownership
94
- - Maintained by the Purchase Order backend and frontend teams.
95
- - Critical integrations: Shopify for stock sync, Email and Slack for notifications.
96
-
97
- #### Non-Functional Requirements
98
- - **Performance**: Query optimizations and paginated shipment queries implemented.
99
- - **Reliability**: Transactions used for key updates like duplicating POs to ensure consistency.
100
- - **Security**: Team-based authorization enforced at controller layer.
101
-
102
- ---
103
-
104
- ### Code Structure
105
-
106
- | Path | Description |
107
- |---|---|
108
- | `apps/api/src/purchase-order/services/purchase-orders.service.ts` | Main backend service logic covering PO CRUD, shipment and payment management, exporting PDFs, duplication, and business rules. |
109
- | `apps/api/src/purchase-order/controllers/purchase-orders.controller.ts` | REST controller exposing the Purchase Orders API, with input validation and error handling. |
110
- | `apps/web/src/components/pages/purchase-order/index.tsx` | React components for viewing, editing, and managing a single purchase order. Includes form state and UI actions. |
111
- | `apps/api/src/admin/services/export.service.ts` | Service supporting CSV and JSON exports related to purchase orders and inventory data. |
112
- | `apps/web/src/api/resources/purchase-orders` | API hooks and mutations for frontend usage. |
113
- | `apps/web/src/components/pages/purchase-orders` | UI components for listing and bulk actions on purchase orders. |
114
-
115
- #### Key Code Snippet: Purchase Order Update Flow
116
- ```ts
117
- const onSubmit = handleSubmit(({ supplierId, lineItems, status, exchangeRates, payments, shipmentCosts, issueDate, ...values }) => {
118
- updatePurchaseOrder({
119
- id: purchaseOrderId,
120
- data: {
121
- content: {
122
- ...values,
123
- name: values.name?.trim(),
124
- exchangeRates: exchangeRates.reduce((acc, { currency, value }) => ({ ...acc, [currency]: value }), {}),
125
- },
126
- items: lineItems,
127
- status,
128
- supplierId,
129
- issueDate,
130
- payments,
131
- shipmentCosts: Object.entries(_.groupBy(shipmentCosts, "shipmentId")).map(([shipmentId, costs]) => ({ shipmentId, costs })),
132
- },
133
- });
134
- });
135
- ```
136
- This excerpt from the frontend `PurchaseOrderForm` component demonstrates submission of all related data to the update mutation in `PurchaseOrdersService`.
137
-
138
- ---
139
-
140
- ### API and Interfaces
141
-
142
- The `PurchaseOrdersController` exposes a comprehensive REST API surface:
143
-
144
- - `POST /purchase-orders`: List purchase orders with filtering by supplier or variant IDs.
145
- - `GET /purchase-orders/summary`: Returns summarized purchase order information including statuses and key dates.
146
- - `GET /purchase-orders/:purchaseOrderId`: Retrieve detailed PO including items, shipments, payments.
147
- - `POST /purchase-orders/create`: Create new purchase order with product variants.
148
- - `POST /purchase-orders/create-with-quantities`: Create PO specifying quantities.
149
- - `PUT /purchase-orders/status`: Bulk status updates.
150
- - `PUT /purchase-orders/:purchaseOrderId`: Update PO details.
151
- - `DELETE /purchase-orders/:purchaseOrderId`: Soft delete a purchase order.
152
- - `POST /purchase-orders/:purchaseOrderId/duplicate`: Duplicate an existing PO.
153
- - `POST /purchase-orders/import`: Handle import requests for POs from files.
154
- - `POST /purchase-orders/:purchaseOrderId/export/pdf`: Export PO to PDF.
155
- - Several endpoints for shipments and payments management.
156
-
157
- Input schemas and validation are implemented using Zod (`ZodValidationPipe`), ensuring type-safe and correct data structures.
158
-
159
- Failures are handled via exceptions, including dedicated error codes for common cases (e.g., PO not found).
160
-
161
- ---
162
-
163
- ### Environment & Configuration
164
-
165
- - Utilizes database connections managed through TypeORM repositories injected into the service.
166
- - Relies on external services such as EmailService, SlackService, ShopifyProductsService.
167
- - ExportService manages PDF and CSV generation.
168
- - Configuration (including toggles, environment modes) is accessible through injected ConfigService.
169
-
170
- Local development requires running backend with connected Postgres DB, Elasticsearch (where applicable), and frontend with mocked or live backend endpoints.
171
-
172
- ---
173
-
174
- ### Testing, Monitoring, and Deployment
175
-
176
- - No explicit test code provided in context, but the layered architecture promotes unit testing of service methods and integration tests of controllers.
177
- - Logging is implemented using NestJS Logger in services.
178
- - Exception tracking through `captureException` utility enables external issue monitoring.
179
- - Scheduled background jobs exist for sending notifications related to POs left in draft, arriving soon, and overdue (in `ScheduledTasksService`).
180
-
181
- ---
182
-
183
- ### Troubleshooting & Known Issues
184
-
185
- - Error handling is designed to differentiate missing POs (404) from other errors.
186
- - Shipment receipt updates may fail if shipment or shipment items are not found.
187
- - Bulk updates ensure transactional integrity where possible.
188
-
189
- ---
190
-
191
- ### References
192
-
193
- - [`PurchaseOrdersService` Source Code](apps/api/src/purchase-order/services/purchase-orders.service.ts)
194
- - [`PurchaseOrdersController` Source Code](apps/api/src/purchase-order/controllers/purchase-orders.controller.ts)
195
- - [`PurchaseOrderForm` Frontend Component](apps/web/src/components/pages/purchase-order/index.tsx)
196
- - [`ExportService` Source Code](apps/api/src/admin/services/export.service.ts)
197
-
198
- ---
199
-
200
- This document summarizes the internal workings and structure of the Purchase Orders module, providing developers with a detailed reference for maintenance and extension efforts.
@@ -1,257 +0,0 @@
1
- ---
2
- title: 'Reports & Analytics'
3
- description: 'Generating, viewing, and managing reports including custom reports, report instance details, and scheduled alerts.'
4
- ---
5
-
6
- ## Reports & Analytics - Internal Developer Documentation
7
-
8
- ### Purpose and Scope
9
- The **Reports & Analytics** module in Genie is responsible for creating, managing, and delivering detailed inventory and purchase order reports and alert emails to users. It supports both manual and scheduled report generation, integrates with inventory, purchase orders, teams, and email services, and facilitates insightful business analytics that help users monitor critical inventory metrics and operational health.
10
-
11
- This module serves as the bridge between raw inventory and purchase order data and user-facing reporting features. It handles complex data aggregation, report instance management, alert email dispatch, and report exclusion logic for variants.
12
-
13
- **System Boundaries:**
14
- - Acts as the backend service layer interacting with the database and domain services such as inventory, purchase orders, suppliers, payment services, and email sending.
15
- - Exposes APIs to the frontend (React web UI) for report definitions, report instances, exclusions, and alert configuration.
16
- - Automated scheduled tasks generate reports and send alerts based on defined frequencies.
17
-
18
- The module's codebase resides primarily in `apps/api/src/reports/` and its API consumption by the frontend is through well-defined resource endpoints.
19
-
20
- ---
21
-
22
- ### Technical Overview
23
-
24
- The Reports system consists of several interconnected services and components:
25
-
26
- - **ReportsService**: Core service implementing report definition management, generation of report instances, content creation, and exclusion handling.
27
- - **ScheduledTasksService**: A cron-driven service that periodically triggers generation of scheduled reports and sends alert emails.
28
- - **EmailService**: Handles templating and dispatch of report alert emails, including formatting and notifications.
29
- - **Report Definitions and Instances**: Persisted in the database, defining report types, frequencies, and generated content snapshots.
30
- - **Frontend Components**: React-based UI components fetch definitions and instances, display lists of reports, their details, and allow users to manage exclusions.
31
-
32
- The system employs the following technologies and patterns:
33
- - **NestJS Framework**: For backend API development.
34
- - **TypeORM**: ORM layer managing entity persistence and repository queries.
35
- - **React with React Query**: For frontend data fetching and UI rendering.
36
- - **Cron Scheduling via EnhancedCron Decorator**: For background scheduled tasks.
37
-
38
- #### Key interactions flow (Mermaid Sequence)
39
-
40
- ```mermaid
41
- sequenceDiagram
42
- participant UI as Web UI (React)
43
- participant API as Reports API (NestJS)
44
- participant DB as Database
45
- participant Email as EmailService (SendGrid)
46
- participant InventorySvc as InventoryService
47
- participant POSvc as PurchaseOrdersService
48
-
49
- UI->>API: Fetch report definitions
50
- API->>DB: Query ReportDefinitions
51
- DB-->>API: Return definitions
52
- API-->>UI: Send definitions
53
-
54
- UI->>API: Request manual report generation
55
- API->>ReportsSvc: GenerateReportInstance
56
- ReportsSvc->>InventorySvc/POSvc: Aggregate data
57
- ReportsSvc->>DB: Save ReportInstance
58
- ReportsSvc-->>API: Return instance ID
59
- API-->>UI: Confirm generation
60
-
61
- ScheduledTasks->>API: Trigger scheduled report generation
62
- API->>ReportsSvc: Generate for due reports
63
- ReportsSvc->>DB: Save generated instances
64
- API->>Email: Send alerts to users
65
- Email-->>Users: Alert emails
66
-
67
- ```
68
-
69
- ---
70
-
71
- ### Core Concepts and Responsibilities
72
-
73
- - **Report Definitions**: Templates specifying report type, frequency, schedule, and settings. Each is associated with a team.
74
- - **Report Instances**: Generated reports based on definitions, each with an attached snapshot of data content.
75
- - **Email Alerts**: Sent automatically for some report types if `notifyViaEmail` flag is set.
76
- - **Variant Exclusions**: Product variants can be excluded from reports, stored in exclusion entities and managed via API.
77
- - **Scheduled Execution**: The system runs every 15 minutes to determine which reports need generation based on schedule and frequency.
78
- - **Report Content Types**: Diverse types covering inventory health, sales velocity, stock risk, purchase order snapshots, dashboard data, and variance.
79
-
80
- **Ownership & Logging:**
81
- - The Reports team maintains this module.
82
- - Logging is done extensively via NestJS Logger in backend services to trace report generation and errors.
83
-
84
- **Non-Functional Requirements:**
85
- - Must support scalability across multiple teams with isolation.
86
- - Ensure reliability for timely report generation and alert delivery.
87
- - Secure access, verifying user's team membership before data access.
88
-
89
- ---
90
-
91
- ### Code Structure
92
-
93
- - `apps/api/src/reports/controllers/reports.controller.ts`: Handles REST API endpoints for reports — fetching definitions, generating reports, updating exclusions.
94
- - `apps/api/src/reports/services/reports.service.ts`: Implements core report generation logic, data aggregation, and persistence.
95
- - `apps/api/src/reports/services/scheduled-tasks.service.ts`: Scheduled cron jobs for automated report generation and email alerts.
96
- - `apps/api/src/email/services/email.service.ts`: Email templating and sending mechanisms, specifically for report alerts and purchase order notifications.
97
- - `apps/web/src/components/pages/reports/reports.tsx`: Frontend main page rendering report lists and managing open definition slide outs.
98
- - `apps/web/src/components/pages/reports/report-definition-slide-out/past-reports-tab.tsx`: Displays list of past report instances.
99
- - `apps/web/src/components/pages/report-instance/no-results.tsx`: UI component showing message when a report instance has no data.
100
-
101
- #### Example snippet: report instance generation flow
102
- ```ts
103
- // Trigger report instance generation
104
- async generateReportInstance({teamId, definitionId, type}) {
105
- const definition = await this.getReportDefinition(teamId, definitionId);
106
- if (!definition.isValid()) throw new Error("Invalid report");
107
-
108
- const instance = this.reportInstanceRepository.create({
109
- teamId,
110
- reportDefinitionId: definitionId,
111
- reportDefinitionSnapshot: definition.getSnapshot(),
112
- type,
113
- });
114
-
115
- instance.content = await this.generateReportContent(instance);
116
- await this.reportInstanceRepository.save(instance);
117
- return instance;
118
- }
119
- ```
120
-
121
- [Link to source](apps/api/src/reports/services/reports.service.ts)
122
-
123
- ---
124
-
125
- ### API and Interfaces
126
-
127
- The Reports API uses standard REST semantics with authentication and authorization based on user team membership.
128
-
129
- **Endpoints overview include:**
130
- - `GET /reports/definitions` - Retrieve all report definitions for the user's team.
131
- - `GET /reports/definitions/:id` - Get a single report definition.
132
- - `PUT /reports/definitions/:id` - Update a report definition.
133
- - `POST /reports/definitions/:id/generate` - Manually trigger report generation.
134
- - `GET /reports/definitions/:id/instances` - List past report instances (previews).
135
- - `GET /reports/instances/:id/details` - Get detailed data of a report instance.
136
- - `GET /reports/definitions/:id/excluded-product-variants` - Get list of excluded variants.
137
- - `POST /reports/definitions/:id/excluded-product-variants/exclude` - Exclude variants.
138
- - `POST /reports/definitions/:id/excluded-product-variants/include` - Include variants back.
139
-
140
- Input validation is performed with Zod schemas (e.g., `createReportRequestDtoSchema`). Exceptions such as missing team membership or unfound report definitions respond with 403 or 404 respectively.
141
-
142
- ---
143
-
144
- ### Environment & Configuration
145
-
146
- Key environment variables used in related modules:
147
- - `APP_URL` - Base URL for the web app, used in email links.
148
- - `SENDGRID_API_KEY` - API key for SendGrid email service.
149
- - `API_ENV` - Environment designation (production, staging, dev) for conditional behaviors.
150
-
151
- Configurations for report scheduling and frequency are stored in the database per team and may include timezone preferences via settings service.
152
-
153
- ---
154
-
155
- ### Testing, Monitoring, and Deployment
156
-
157
- - Unit and integration tests are implied to exist covering service methods and API controllers (no explicit test details provided).
158
- - Logging via NestJS Logger and error capturing via `captureException` provide observability.
159
- - Reports run automatically via cron (every 15 minutes) with precise time-window checks to avoid duplicate generation.
160
- - Email sending failures are caught and logged without crashing the batch.
161
-
162
- Deployment follows standard CI/CD pipelines for the NestJS backend and React frontend.
163
-
164
- ---
165
-
166
- ### Troubleshooting & Known Issues
167
-
168
- There is no explicit documented troubleshooting guidance, but due to detailed logging and error capture patterns in the ScheduledTasksService and ReportsService, developers can trace:
169
- - Report generation failures.
170
- - Email sending errors.
171
- - Report exclusion inconsistencies.
172
-
173
- No known critical pitfalls or remediation steps are documented.
174
-
175
- ---
176
-
177
- ### Summary
178
- The Reports & Analytics module is a highly integrated backend service with database persistence, scheduled tasks, and email notification capabilities. It empowers teams to monitor inventory health through scheduled and manual reports made visible through the Genie Web UI. The codebase is organized around domain services, RESTful controllers, scheduled tasks, and email dispatch.
179
-
180
- ##### Key Documentation Links:
181
- - [Reports Controller](apps/api/src/reports/controllers/reports.controller.ts)
182
- - [Reports Service Core Logic](apps/api/src/reports/services/reports.service.ts)
183
- - [Scheduled Tasks Service](apps/api/src/reports/services/scheduled-tasks.service.ts)
184
- - [Email Service](apps/api/src/email/services/email.service.ts)
185
- - [Frontend Reports Page](apps/web/src/components/pages/reports/reports.tsx)
186
-
187
- ---
188
-
189
- ### Mermaid Architecture Diagram
190
-
191
- ```mermaid
192
- flowchart TD
193
- subgraph "Frontend (React Web UI)"
194
- UI_Reports["Reports Page UI"]:::frontend
195
- UI_ReportDefinition["Report Definition Slide Out"]:::frontend
196
- end
197
-
198
- subgraph "Reports API (NestJS Backend)"
199
- ReportsController["ReportsController"]:::backend
200
- ReportsService["ReportsService"]:::backend
201
- ScheduledTasks["ScheduledTasksService"]:::backend
202
- end
203
-
204
- subgraph "Support Services"
205
- InventorySvc["InventoryService"]:::backend
206
- PurchaseOrdersSvc["PurchaseOrdersService"]:::backend
207
- SuppliersSvc["SuppliersService"]:::backend
208
- DashboardSvc["DashboardService"]:::backend
209
- PaymentSvc["PaymentsService"]:::backend
210
- EmailSvc["EmailService"]:::backend
211
- TeamsSvc["TeamsService"]:::backend
212
- SettingsSvc["SettingsService"]:::backend
213
- end
214
-
215
- subgraph "Database"
216
- ReportDefs[("ReportDefinitions Table")]:::database
217
- ReportInstances[("ReportInstances Table")]:::database
218
- VariantExclude[("ReportDefinitionVariantExclude Table")]:::database
219
- EmailAlertDefs[("EmailAlertDefinitions Table")]:::database
220
- end
221
-
222
- %% UI -> API
223
- UI_Reports -->|"REST API calls"| ReportsController
224
- UI_ReportDefinition -->|"Fetch / Update"| ReportsController
225
-
226
- %% Reports API
227
- ReportsController -->|"call"| ReportsService
228
- ScheduledTasks -->|"call cron jobs"| ReportsService
229
- ReportsService -->|"query/update"| ReportDefs
230
- ReportsService -->|"query/update"| ReportInstances
231
- ReportsService -->|"query/update"| VariantExclude
232
- ReportsService -->|"query/update"| EmailAlertDefs
233
-
234
- %% ReportsService calls supporting services
235
- ReportsService --> InventorySvc
236
- ReportsService --> PurchaseOrdersSvc
237
- ReportsService --> SuppliersSvc
238
- ReportsService --> DashboardSvc
239
- ReportsService --> PaymentSvc
240
- ReportsService --> TeamsSvc
241
- ReportsService --> SettingsSvc
242
-
243
- %% ScheduledTasks email alerts
244
- ScheduledTasks --> EmailSvc
245
- ReportsService --> EmailSvc
246
-
247
- %% Click events
248
- click ReportsController "apps/api/src/reports/controllers/reports.controller.ts"
249
- click ReportsService "apps/api/src/reports/services/reports.service.ts"
250
- click ScheduledTasks "apps/api/src/reports/services/scheduled-tasks.service.ts"
251
- click EmailSvc "apps/api/src/email/services/email.service.ts"
252
- click UI_Reports "apps/web/src/components/pages/reports/reports.tsx"
253
-
254
- %% Styles
255
- classDef frontend fill:#f9f,stroke:#333,stroke-width:1px,color:#222
256
- classDef backend fill:#bbf,stroke:#333,stroke-width:1px,color:#000
257
- classDef database fill:#bfb,stroke:#333,stroke-width:1px,color:#000