@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,210 +0,0 @@
1
- ---
2
- title: 'Demand Planning'
3
- description: 'Accessing and using planning tools, forecasts, breakdowns, and metrics to manage product demand.'
4
- ---
5
-
6
- # Demand Planning Service and Web UI Component
7
-
8
- ## 1. Purpose and Scope
9
-
10
- The Demand Planning module encompasses the backend service (`DemandPlanService`) and the frontend React components (e.g., `DemandPlanContent`, `DemandPlanning`) responsible for managing the full lifecycle of demand planning. It provides an end-to-end solution for generating, adjusting, summarizing, and refreshing sales forecasts and demand plans for a team.
11
-
12
- This module addresses demand forecasting challenges by integrating historical sales data, forecasts, and product information to produce actionable demand plans with monthly granularity. It supports both planned and actual sales tracking, provides detailed revenue breakdowns by supplier and Shopify categories, and enables manual adjustments with granular controls.
13
-
14
- ### System Boundaries and Architectural Context
15
-
16
- - The Demand Planning Service is a NestJS injectable that interacts with the database and external domain services (InventoryService, SalesOrdersService, TeamsService, ForecastService, WorkflowService, EmailService).
17
- - The frontend React components form part of the Genie Web application and use React Hook Form and multiple API endpoints to present and update demand plan data.
18
- - Demand plan data is persisted and queried from PostgreSQL tables (demand_plan, demand_plan_item, demand_plan_item_monthly_sales).
19
- - The service integrates tightly with the Workflow subsystem to handle asynchronous generation and update of plans.
20
-
21
-
22
- ## 2. Technical Overview
23
-
24
- ### High-Level Architecture
25
-
26
- ```mermaid
27
- flowchart TD
28
- subgraph Backend["Backend - NestJS Service"]
29
- DPService["DemandPlanService"]:::service
30
- InventoryService["InventoryService"]:::service
31
- SalesOrdersService["SalesOrdersService"]:::service
32
- TeamsService["TeamsService"]:::service
33
- ForecastService["ForecastService"]:::service
34
- WorkflowService["WorkflowService"]:::service
35
- EmailService["EmailService"]:::service
36
- DB["PostgreSQL DB"]:::database
37
- end
38
-
39
- subgraph Frontend["Frontend - React Web UI"]
40
- DPPage["DemandPlanning Component"]:::frontend
41
- DPContent["DemandPlanContent Component"]:::frontend
42
- API["Demand Plan API Endpoints"]:::api
43
- end
44
-
45
- DPService -->|"reads/writes"| DB
46
- DPService -->|"calls"| InventoryService
47
- DPService -->|"calls"| SalesOrdersService
48
- DPService -->|"calls"| TeamsService
49
- DPService -->|"calls"| ForecastService
50
- DPService -->|"starts workflows"| WorkflowService
51
- DPService -->|"sends emails"| EmailService
52
-
53
- DPPage -->|"uses"| DPContent
54
- DPContent -->|"calls"| API
55
- API -->|"calls"| DPService
56
-
57
- classDef service fill:#d1e7dd,stroke:#0f5132,color:#0f5132,stroke-width:1px
58
- classDef api fill:#cfe2ff,stroke:#084298,color:#084298,stroke-width:1px
59
- classDef frontend fill:#f8d7da,stroke:#842029,color:#842029,stroke-width:1px
60
- classDef database fill:#fff3cd,stroke:#664d03,color:#664d03,stroke-width:1px
61
- ```
62
-
63
- ### Key Technologies and Frameworks
64
-
65
- - **Backend:** NestJS framework with Dependency Injection for modular services.
66
- - **Data Access:** TypeORM with PostgreSQL.
67
- - **Validation:** Zod schemas for DTOs.
68
- - **Frontend:** React, React Hook Form for form state management.
69
- - **API:** React Query hooks for data fetching and mutations.
70
- - **UI Components:** Custom Jasmine component library for design consistency.
71
-
72
- ## 3. Core Concepts and Responsibilities
73
-
74
- ### Key Concepts
75
-
76
- - **DemandPlanEntity:** Represents a demand plan instance linked to a team, with lifecycle statuses such as `Generating` and `Ready`.
77
- - **DemandPlanItemEntity:** Represents inventory variants within a demand plan including sale and cost prices.
78
- - **DemandPlanItemMonthlySalesEntity:** Holds monthly sales data per demand plan item, including forecast, adjusted, previous period, and actual sales quantities.
79
- - **Breakdown Types:** Revenue breakdowns can be viewed by supplier or Shopify category.
80
- - **WorkflowService:** Manages asynchronous workflows for generating plans, refreshing forecasts, and updating actuals.
81
-
82
- ### Responsibilities
83
-
84
- - **DemandPlanService:** Primary service managing demand plan lifecycle, data generation, adjustments, refreshes, and notifications.
85
- - **Frontend Components:** Render the demand planning UI, showing plan summaries, revenue breakouts, product-level forecasts, and providing user actions.
86
-
87
- ### Ownership and Logging
88
-
89
- - Maintained by the Forecast and Planning engineering team.
90
- - Uses NestJS Logger for structured logs.
91
- - Catches and reports errors using custom `GenieException` and `captureException` for observability.
92
-
93
- ### Non-Functional Requirements (NFRs)
94
-
95
- - **Performance:** Batch processing for demand plan item creation and monthly sales insertion ensures scalability.
96
- - **Reliability:** Transactional operations used in demand plan refresh to maintain data consistency.
97
- - **Security:** Access control presumed implemented at broader application layer (not detailed in context).
98
- - **Scalability:** Asynchronous workflows scale demand plan generation and actual updates across teams.
99
-
100
- ## 4. Code Structure
101
-
102
- ### Major Files and Folders
103
-
104
- - **Backend Service:**
105
- - `apps/api/src/forecast/services/demand-plan.service.ts` — Core business logic and data handling.
106
- - **Frontend:**
107
- - `apps/web/src/components/pages/demand-planning/demand-plan-content.tsx` — Detailed demand planning UI and form management.
108
- - `apps/web/src/components/pages/demand-planning/index.tsx` — Page entry point managing demand plan lifecycle views.
109
- - `apps/web/src/components/pages/demand-planning/hooks.ts` — Hooks for aggregated summary and feature flag checks.
110
-
111
- ### Key Execution Flows
112
-
113
- - **Demand Plan Generation:**
114
- - Initiated by mutation `useGenerateDemandPlanMutation` on frontend.
115
- - Backend `startGeneratingDemandPlan()` creates a new demand plan in `Generating` status.
116
- - Items are populated in batches from inventory.
117
- - Monthly sales generated using forecast and historical sales data.
118
- - When complete, backend marks demand plan as `Ready` and triggers actual sales update workflow and notifications.
119
-
120
- - **Demand Plan Refresh:**
121
- - Triggered via `refreshForecast` mutation.
122
- - Creates a new `Generating` demand plan, deactivates old one.
123
- - Starts regeneration workflows.
124
-
125
- - **Adjusting Sales Quantities:**
126
- - User edits quantities in the frontend form.
127
- - On submit, dirty fields are mapped and sent to `updateDemandPlanItemQuantitiesMutation`.
128
- - Backend updates adjustedQuantity fields in monthly sales.
129
-
130
- ### Representative Code Snippet: Adjust Monthly Sales (Backend)
131
- ```ts
132
- async adjustMonthlySales({ teamId, adjustments }: { teamId: string; adjustments: AdjustDemandPlanMonthlySalesRequestDto; }) {
133
- // Validate demand plan items belong to current ready demand plan.
134
- const demandPlan = await this.ensureCurrentDemandPlanInStatus({ teamId, status: DemandPlanStatus.Ready });
135
-
136
- // Find related monthly sales and update adjustedQuantity.
137
- const monthlySalesToUpdate = adjustments.map((adjustment) => {
138
- const monthlySale = relatedMonthlySales.find(item => item.demandPlanItemId === adjustment.demandPlanItemId && item.month === adjustment.month);
139
- if (!monthlySale) throw new GenieException("Monthly sale not found", { /* details */ });
140
- monthlySale.adjustedQuantity = adjustment.adjustedQuantity;
141
- return monthlySale;
142
- });
143
-
144
- await this.dataSource.getRepository(DemandPlanItemMonthlySalesEntity).save(monthlySalesToUpdate);
145
- }
146
- ```
147
-
148
- ### Representative Code Snippet: Frontend Submit Handler
149
- ```tsx
150
- const onSubmit = handleSubmit((values) => {
151
- const dirtyItems = values.items
152
- .map((item, i) => ({
153
- ...item,
154
- sales: item.sales.filter((_, si) => dirtyFields.items?.[i]?.sales?.[si]?.adjustedQuantity),
155
- }))
156
- .filter(item => item.sales.length > 0);
157
-
158
- const mapped = mapToAdjustDemandPlanMonthlySalesRequestDto({ items: dirtyItems });
159
- updateDemandPlanItemQuantities(mapped);
160
- });
161
- ```
162
-
163
- ## 5. API and Interfaces
164
-
165
- ### Demand Plan Summary Endpoint
166
- - Returns current demand plan metadata plus monthly aggregates (planned, previous period, actuals).
167
-
168
- ### Revenue Breakdown Endpoints
169
- - Provide monthly revenue breakdown by Shopify category or supplier.
170
-
171
- ### Mutation Endpoints
172
- - `updateDemandPlanItemQuantities`: Accepts adjusted monthly sales per item.
173
- - `refreshShopifyPrices` and `refreshForecast`: Trigger price and forecast updates respectively.
174
-
175
- ### Data Schemas
176
- - Demand plan date ranges use 12 months starting from plan start date.
177
- - Sales quantities are integers, with adjusted quantities nullable.
178
-
179
- ### Failure Modes
180
-
181
- - Exceptions thrown if invalid demand plan status or missing entities.
182
- - Validation errors if duplicate months for same item adjusted.
183
- - Errors during workflow start rollback demand plan state.
184
-
185
- ## 6. Environment & Configuration
186
-
187
- - Environment configuration details not provided.
188
- - Service depends on database connectivity, external services for inventory, forecast, and workflows.
189
-
190
- ## 7. Testing, Monitoring, and Deployment
191
-
192
- - No explicit testing or CI/CD details provided.
193
- - Logging and error capture integrated via `Logger` and `captureException` utilities.
194
-
195
- ## 8. Troubleshooting & Known Issues
196
-
197
- - Generation or refresh failure leads to demand plan deletion and rollback.
198
- - Warnings logged when SKU counts mismatch or invalid periods detected.
199
-
200
- ## Additional Notes
201
-
202
- - Frontend components implement polling for generation status with refetchInterval.
203
- - Demand plan modal dialogs for refreshing forecasts provide user feedback.
204
- - Dashboard includes detailed breakdown components and product-level forecasts.
205
-
206
- ## References
207
- - [DemandPlanService Source Code](apps/api/src/forecast/services/demand-plan.service.ts)
208
- - [DemandPlanContent React Component](apps/web/src/components/pages/demand-planning/demand-plan-content.tsx)
209
- - [DemandPlanning Page Component](apps/web/src/components/pages/demand-planning/index.tsx)
210
- - [Demand Planning API Exports](apps/web/src/api/resources/demand-plan/index.ts)
@@ -1,167 +0,0 @@
1
- ---
2
- title: 'Favorites & User Preferences'
3
- description: 'Managing favorite inventory items and quick-access preferences to enhance productivity.'
4
- ---
5
-
6
- # Favorites & User Preferences
7
-
8
- ## Overview
9
-
10
- The Favorites feature in the Genie app provides users with a dedicated workflow to manage their preferred products efficiently. It enables users to mark inventory variants as favorites, maintain a curated list, export favorite items, and create or add to purchase orders directly from this set of prioritized products.
11
-
12
- This system is integrated tightly within the inventory management domain and serves to enhance user productivity by offering filtered views, quick actions, and seamless data export related to favorite items.
13
-
14
- ## Purpose and Scope
15
-
16
- This documentation covers the Favorites feature implementation within the Genie web application, detailing its UI components, hooks, integration with API resources, and their interaction with the inventory subsystem.
17
-
18
- It is intended for developers maintaining the Favorites workflows and related API services.
19
-
20
- ## Architectural Context
21
-
22
- The Favorites functionality is implemented as a React UI feature connected to backend services using GraphQL or REST APIs exposed by the Genie platform. It uses React hooks for state management, server mutations, and querying filtered inventory data.
23
-
24
- It leverages shared data types from `@genie/shared` and common utility modules for operations like CSV export and notifications.
25
-
26
- ### Key system boundaries:
27
-
28
- - **UI Layer:** React components and hooks managing Favorites state, triggers, and rendering.
29
- - **API Layer:** Mutations and queries to mark/unmark favorites, fetch filtered favorite inventory items, and interact with purchase orders.
30
- - **Data Layer:** Inventory entities with a `favourite` property representing if the item is marked as a favorite.
31
-
32
- ## Technical Overview
33
-
34
- Favorites management is primarily handled through hooks such as `useFavoritesActions` and `useFavoritesData` located within the Favorites page directory.
35
-
36
- These hooks coordinate with API mutations for:
37
-
38
- - Adding/removing inventory items as favorites
39
- - Creating purchase orders from favorite variants
40
- - Exporting favorites subset to CSV
41
-
42
- The UI layer (`Favorites` page component) uses these hooks to present filtering, searching, pagination, and action controls to users.
43
-
44
- ### Integration Points:
45
-
46
- - Inventory API to fetch inventory items filtered by the favorite flag.
47
- - Inventory mutation endpoints for toggling favorite states.
48
- - Purchase order API for creating purchase orders from selected favorites.
49
-
50
- These API integrations are wrapped by custom React Query mutations, ensuring data consistency and mutation side-effect handling (e.g., UI notifications).
51
-
52
- ## Core Concepts and Responsibilities
53
-
54
- - **Favorite Inventory Item:** Inventory variant marked by the user to indicate priority or preference.
55
- - **SelectedProductVariants:** The current set of variant IDs that the user has selected for batch operations.
56
- - **FavoriteAction:** Determines the next toggle action, between "Favorite" and "Unfavorite" depending on the current items' states.
57
-
58
- ### Design Assumptions:
59
-
60
- - Favoriting is a user/team level setting stored in the product variant entity.
61
- - Bulk operations (toggle, export, create PO) operate on currently selected variants.
62
- - The UI supports filtering and sorting to assist users in managing favorites.
63
-
64
- ### Ownership & Maintenance:
65
-
66
- - The Favorites feature is primarily owned by the web frontend team.
67
- - Backend services track favorite state changes and onboard events through the `FavouritesService`.
68
-
69
- ## Code Structure
70
-
71
- ### Key Files & Components:
72
-
73
- - **`apps/web/src/components/pages/favorites/index.tsx`**
74
- - Entry component for the Favorites page.
75
- - Renders UI including headers, filters, favorites list, action buttons, and pagination.
76
- - Uses hooks `useFavoritesActions`, `useFavoritesData`, and `useInventoryItemsFilterProps`.
77
-
78
- - **`apps/web/src/components/pages/favorites/hooks.ts`**
79
- - Contains hooks managing favorite items state, selection, mutations, and data fetching.
80
- - Key hooks:
81
- - `useFavoritesActions` handles selection, export, favorite toggling, and purchase order creation.
82
- - `useFavoritesData` provides paginated, filtered inventory data scoped to favorites.
83
- - `useInventoryItemsFilterProps` defines filtering properties and options.
84
-
85
- - **`apps/web/src/api/resources/inventory-items/favourites.ts`** (implied from exports)
86
- - API mutations and queries related to favorites management.
87
-
88
- - **`apps/api/src/pim/services/favourites.service.ts`**
89
- - Backend service managing database updates for favorite flags on product variants.
90
- - Tracks onboarding events when favorites are set.
91
-
92
- ### Example: Favorite toggle mutation call
93
- ```ts
94
- const onFavouritesToggle = useCallback(() => {
95
- const variantIdsToChange = selectedProductVariants;
96
- if (nextFavouriteAction === FavouriteAction.Favourite) {
97
- mutateAddFavourites(variantIdsToChange);
98
- } else {
99
- mutateRemoveFavourites(variantIdsToChange);
100
- }
101
- }, [mutateRemoveFavourites, mutateAddFavourites, nextFavouriteAction, selectedProductVariants]);
102
- ```
103
- ### Example: Exporting favorites to CSV
104
- ```ts
105
- const onExportSelectedItemCSV = useCallback(() => {
106
- const exportedInventoryItems = inventoryItems.filter(item =>
107
- selectedProductVariants.includes(item.variantId)
108
- );
109
- const csv = prepareFavoritesCSVData(exportedInventoryItems);
110
- const filename = `Favorites-${formatDate(new Date())}.csv`;
111
- exportToCsv(csv, filename);
112
- }, [inventoryItems, selectedProductVariants]);
113
- ```
114
-
115
- ## API and Interfaces
116
-
117
- ### Mutations
118
- - **`useAddInventoryItemsFavouritesMutation`**: Adds specified product variants to favorites.
119
- - **`useRemoveInventoryItemsFavouritesMutation`**: Removes specified product variants from favorites.
120
- - **`useCreatePurchaseOrderMutation`**: Creates a purchase order from a list of variant IDs.
121
-
122
- ### Queries
123
- - **`useGetInventoryItemsQuery` with favorite filter**: Retrieves inventory items marked as favorites.
124
-
125
- ### Backend Service: FavouritesService
126
- - Responsible for efficient batch updates of favorite flags on product variants.
127
- - Implements differential updates (adds and removes) to sync user's current favorite selections.
128
-
129
- ## Environment & Configuration
130
-
131
- No explicit environment variables or secrets related to Favorites are detailed in the provided context.
132
-
133
- ## Testing, Monitoring, and Deployment
134
-
135
- No specific information on testing, monitoring, or deployment practices related to the Favorites feature is provided.
136
-
137
- ## Troubleshooting & Known Issues
138
-
139
- No documented issues or troubleshooting steps are available for this component.
140
-
141
- ## Usage Example
142
-
143
- Users interact with the Favorites page to:
144
-
145
- - Search and filter favorite products using pre-configured filter options.
146
- - Select multiple favorite variants using UI cards.
147
- - Toggle favorite state for selected items in bulk.
148
- - Export selected or all favorites to CSV.
149
- - Create new or add to existing purchase orders from selected favorites.
150
-
151
- ## Summary
152
-
153
- The Favorites & User Preferences feature provides an integrated and streamlined approach for users to manage their priority inventory items efficiently. It leverages React hooks and modular API operations to maintain state and synchronize with backend services while providing typical inventory actions specialized for favorites.
154
-
155
- This functionality is crucial for workflows that prioritize commonly used or monitored products, easing downstream operations such as procurement.
156
-
157
- ---
158
-
159
- ## References
160
-
161
- - [Favorites Component Source](apps/web/src/components/pages/favorites/index.tsx)
162
- - [Favorites Hooks](apps/web/src/components/pages/favorites/hooks.ts)
163
- - [Favorites Backend Service](apps/api/src/pim/services/favourites.service.ts)
164
- - [Inventory Actions Hook](apps/web/src/hooks/use-inventory-actions.ts)
165
- - [Inventory Table Actions](apps/web/src/components/pages/inventory/table-actions.tsx)
166
-
167
- ---
@@ -1,179 +0,0 @@
1
- ---
2
- title: 'Inventory Management'
3
- description: 'How to manage inventory items, views, filters, and performing actions like excluding products or changing status.'
4
- ---
5
-
6
- ## Inventory Management Service
7
-
8
- ### Purpose and Scope
9
- The **InventoryService** is a core backend module responsible for managing inventory data within the Genie application. It handles the retrieval, filtration, enrichment, and export of inventory items for a given team. This service solves challenges around accurate and efficient access to inventory metrics, stock status, historical data, and integration with purchase orders.
10
-
11
- This service is situated within the Product Information Management (PIM) subsystem and interfaces directly with database repositories (e.g., `InventoryItemEntity`, `InventoryItemHistoryEntity`), other domain services such as purchase orders, assets, and email, and external Shopify integrations.
12
-
13
-
14
- ### Technical Overview
15
-
16
- The service uses the NestJS framework and TypeORM for database access. It codifies complex business logic primarily through database views (e.g., `inventory_item` view) and sophisticated TypeORM query builders.
17
-
18
- Key dependencies:
19
- - TypeORM Repositories: Inventory items, Product Variants, Inventory Item History.
20
- - Other services: `PurchaseOrdersService`, `EmailService`, `AssetsService`.
21
- - Shared utilities and types from the `@genie/shared` package.
22
-
23
- The service encapsulates queries with filter and sort capabilities, supports bulk operations on ignored variants, handles inventory history synchronization, and supports item export functionality.
24
-
25
- #### Key Technologies & Patterns
26
- - **NestJS**: Modular dependency injection and service structure.
27
- - **TypeORM**: SQL view-based entities and complex dynamic query building.
28
- - **SQL Views**: Centralized inventory item state computation in `inventory_item` view.
29
- - **Batch Processing**: For large exports and history sync operations.
30
-
31
- ### Core Concepts and Responsibilities
32
-
33
- - **Inventory Items:** Represent products or product variants with stock quantities, sales data, status (e.g., running low, out of stock), and metadata (e.g., suppliers, locations).
34
-
35
- - **Filters and Sorting:** Custom filters support multiple operators and field types, allowing precise querying.
36
-
37
- - **Historical Data:** Maintains snapshots of inventory state over time for reports and analysis.
38
-
39
- - **Stock Metrics:** Calculates key metrics such as days to out of stock, days to order, grading levels, and stock status.
40
-
41
- - **Integration Points:** Interfaces with purchase order data for in-transit quantities, supplier data, and Shopify inventory levels.
42
-
43
- - **Exports:** Supports asynchronous export of full inventory lists to CSV stored in S3, with email notification.
44
-
45
-
46
- ### Code Structure
47
-
48
- - **InventoryService (apps/api/src/pim/services/inventory.service.ts):**
49
- Primary service class implementing all core inventory functions.
50
-
51
- - **InventoryItemEntity (apps/api/src/pim/entities/inventory-item.entity.ts):**
52
- TypeORM view entity mapping to the `inventory_item` SQL view for inventory data.
53
-
54
- - **Migrations (in `apps/api/src/migrations/db/`):**
55
- Manage schema and view updates related to inventory data, e.g., adding suppliers, locations, and adjusting stock calculations.
56
-
57
- - **Supporting Components:**
58
- Includes repositories for entity persistence and utilities for filtering and processing.
59
-
60
- **Example of bulk action method for getting inventory items:**
61
- ```ts
62
- async getInventoryItems<T extends InventoryItemSelect[]>(
63
- teamId: string,
64
- options: GetInventoryItemsRequestDto
65
- ): Promise<[InventoryItem<T>[], number]> {
66
- // Performs queries with filtering, sorting, pagination
67
- }
68
- ```
69
-
70
- ### API and Interfaces
71
-
72
- - **getInventoryItems(teamId, options):**
73
- Fetch inventory items by team with options for filters, sorting, pagination, search terms, and selected fields.
74
-
75
- - **getToBuyInventoryItems(teamId, request):**
76
- Retrieve inventory variants that need to be restocked, with sorting and filtering tailored to buying criteria.
77
-
78
- - **addToBuyIgnore(teamId, variantIds, ignoreUntil):**
79
- Mark specific variants to be ignored in to-buy calculations until a specified date.
80
-
81
- - **removeFromToBuyIgnore(teamId, variantIds):**
82
- Removes variants from the ignore list.
83
-
84
- - **syncHistory(teamId):**
85
- Sync persistent inventory snapshots from current live data to history table for trend analysis.
86
-
87
- - **exportAllInventoryItems(teamId, userEmail, columns):**
88
- Initiates export of all inventory items data to CSV in S3 and emails download link to user.
89
-
90
- **Request/Response shapes are strongly typed using `@genie/shared` DTOs and Types.**
91
-
92
- ### Environment & Configuration
93
-
94
- The service relies on environment and config such as:
95
- - `DATA_SYNC_TIMEZONE` used in history synchronization for consistent time zones.
96
- - S3 bucket config via `AssetsService` for exporting CSV files.
97
-
98
- Specific env vars beyond this are not present in the context.
99
-
100
- ### Testing, Monitoring, and Deployment
101
-
102
- Testing and monitoring strategies are not detailed in provided info.
103
-
104
- ### Troubleshooting & Known Issues
105
-
106
- No explicit troubleshooting guidance or known issues are documented in the current context.
107
-
108
- ### Inventory Item View (`inventory_item`)
109
-
110
- The `InventoryItemEntity` is based on a complex SQL view that consolidates data from product variants, supplier info, purchase orders, tags, locations, and other metadata to provide a comprehensive snapshot of inventory status.
111
-
112
- Key calculated fields include:
113
- - **quantity:** Adjusted for synced and unsynced stock quantities.
114
- - **daysToOutOfStock:** Estimated days until stock depletion, considering incoming shipments.
115
- - **daysToOrder:** Days to reorder based on safety buffers.
116
- - **gradingLevel/Percent/Value:** Performance grades based on configurable strategies.
117
- - **status:** Overall stock health (e.g., RUNNING_LOW, OUT_OF_STOCK, OVERSTOCKED).
118
- - **incomingQuantity:** Stock expected from purchase orders.
119
- - **locationQuantities:** Stock quantities segmented by physical locations.
120
- - **suppliers:** List of associated suppliers.
121
-
122
- This view is maintained via multiple migration scripts enhancing it progressively to include new metrics like gross margin, location quantities, suppliers, product shopify categories, and more.
123
-
124
- ### Integration Overview
125
-
126
- - Interacts closely with **PurchaseOrdersService** to enrich inventory data with in-transit quantities and upcoming shipments.
127
- - **EmailService** is used to deliver export notifications.
128
- - **AssetsService** handles persisting CSV files in S3.
129
- - Queries integrate with **Shopify API** for accurate product and inventory information.
130
-
131
- ### Mermaid Diagram
132
-
133
- ```mermaid
134
- flowchart TD
135
- subgraph "API Layer"
136
- InventoryService["InventoryService"]:::service
137
- end
138
-
139
- subgraph "Database Layer"
140
- InventoryItemEntity["InventoryItemEntity (inventory_item view)"]:::database
141
- InventoryItemHistoryEntity["InventoryItemHistoryEntity"]:::database
142
- ProductVariantEntity["ProductVariantEntity"]:::database
143
- ProductVariantBuyIgnoreEntity["ProductVariantBuyIgnoreEntity"]:::database
144
- TeamEntity["TeamEntity"]:::database
145
- end
146
-
147
- subgraph "Supporting Services"
148
- PurchaseOrdersService["PurchaseOrdersService"]:::service
149
- EmailService["EmailService"]:::service
150
- AssetsService["AssetsService"]:::service
151
- ShopifyProductsService["ShopifyProductsService"]:::service
152
- end
153
-
154
- InventoryService -->|reads/writes| InventoryItemEntity
155
- InventoryService -->|reads/writes| InventoryItemHistoryEntity
156
- InventoryService -->|reads/writes| ProductVariantEntity
157
- InventoryService -->|manages ignore list| ProductVariantBuyIgnoreEntity
158
- InventoryService -->|fetches team config| TeamEntity
159
- InventoryService -->|enriches data| PurchaseOrdersService
160
- InventoryService -->|sends export notifications| EmailService
161
- InventoryService -->|uploads export files| AssetsService
162
- PurchaseOrdersService -->|relies on| InventoryItemEntity
163
- InventoryService -->|integrates for product info| ShopifyProductsService
164
-
165
- %% Click Events for navigation
166
- click InventoryService "apps/api/src/pim/services/inventory.service.ts"
167
- click InventoryItemEntity "apps/api/src/pim/entities/inventory-item.entity.ts"
168
- click PurchaseOrdersService "apps/api/src/purchase-order/services/purchase-orders.service.ts"
169
- click EmailService "apps/api/src/email/services/email.service.ts"
170
- click AssetsService "apps/api/src/asset/services/assets.service.ts"
171
- click ShopifyProductsService "apps/api/src/shopify/services/shopify-products.service.ts"
172
-
173
- classDef service fill:#ffcc00,stroke:#333,stroke-width:1.5px,color:#000
174
- classDef database fill:#66ccff,stroke:#333,stroke-width:1.5px,color:#000
175
-
176
- %% Style guide
177
- class InventoryService,PurchaseOrdersService,EmailService,AssetsService,ShopifyProductsService service
178
- class InventoryItemEntity,InventoryItemHistoryEntity,ProductVariantEntity,ProductVariantBuyIgnoreEntity,TeamEntity database
179
- ```