@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,267 +0,0 @@
1
- ---
2
- title: 'Core Concepts & Terminology'
3
- description: 'Internal definitions, key domain concepts, and important terminology consistent across the codebase and documentation.'
4
- ---
5
-
6
- ## Core Concepts & Terminology
7
-
8
- This document provides an in-depth technical overview of key concepts, entities, and modules within the Product Information Management (PIM) domain and its integration points within the Genie system. It serves as a reference for developers working with product, inventory, and supplier data, clarifying terminology and architectural boundaries.
9
-
10
- ---
11
-
12
- ### 1. Overview
13
-
14
- The PIM module handles the management of product variants, inventory, suppliers, collections, and related entities. It integrates deeply with other subsystems including Sales Orders, Shopify, User Management, Purchase Orders, and Tracking, supporting the core workflows of product inventory and vendor management.
15
-
16
- The PIM module's responsibilities include:
17
-
18
- - Managing product and variant data, including Shopify synchronization and tagging.
19
- - Tracking inventory items, their locations, histories, and sales metrics.
20
- - Handling product-supplier relationships, including variant-level supplier mappings and pricing.
21
- - Coordinating with external services such as Shopify for real-time webhook syncs and sales orders.
22
- - Providing APIs and services consumed by UI workflows and other microservices.
23
-
24
- ### 2. Architectural Context and Boundaries
25
-
26
- - The PIM module encapsulates all product, variant, inventory, location, and supplier-related domain logic primarily within itself.
27
- - It acts as a backbone for the Genie application’s supply chain and inventory management capabilities.
28
- - It exposes services for syncing insights, scheduled tasks, and data snapshotting.
29
- - It connects to external platforms such as Shopify (via the Shopify module) and internal modules like Sales Order, Purchase Order, Workflow, and User Management.
30
-
31
- ### 3. Technical Overview
32
-
33
- #### Main Components
34
-
35
- - **Entities**: Core database models using TypeORM representing products, variants, inventory items, suppliers, locations, collections, and related domain objects.
36
- - **Services**: Business logic layers managing CRUD, batch processing, syncing operations, and data mappings.
37
- - **Controllers**: REST API endpoints for managing products, inventory, locations, saved views, and dashboard queries.
38
-
39
- #### Key Dependencies
40
-
41
- - **TypeORM**: ORM framework for database interaction.
42
- - **NestJS**: Framework organizing the module via controllers, providers, and dependency injection.
43
- - **External Modules**: Shopify (integration and syncing), Sales Order, Purchase Order, Slack, Email, User Management, Comment, Asset, Tracking, Workflow, and Billing.
44
-
45
- ### 4. Core Concepts and Data Model Glossary
46
-
47
- | Term | Description |
48
- |------------------------------------|---------------------------------------------------------------------------------------------------------------|
49
- | **Product** | Represents a merchant's item catalog entry, linked to Shopify products, identified by `shopifyId` and team. |
50
- | **Product Variant** | A specific version of a product, differing by options (e.g., size, color). |
51
- | **Inventory Item** | Physical stock unit linked to a product variant and its location, maintaining quantity and history. |
52
- | **Location** | Physical or logical stock storage place, uniquely tied to a team and Shopify location ID. |
53
- | **Supplier** | Vendor entity supplying products, including contact info and payment terms. |
54
- | **Product Supplier** | Junction entity linking products with suppliers. Can denote primary suppliers. |
55
- | **Product Supplier Variant** | Links a product supplier to specific product variants, storing unit price and supplier SKU. |
56
- | **Collection** | Grouping of products, often used for categorization or marketing. |
57
- | **Product Variant Component** | Used for representing bundled or composed products where variants have child components. |
58
- | **Inventory Item History** | Time-series data tracking inventory metrics such as quantity, sales velocity, and related attributes. |
59
- | **Saved View** | User-customizable saved filters or views for data presentation. |
60
- | **Stock Levels Settings** | Configuration for stock level management on a product, stored as JSON metadata. |
61
-
62
- ### 5. Detailed Conceptual Definitions
63
-
64
- #### ProductEntity
65
- - Uniquely identified by a team-scoped UUID and a Shopify product ID (`shopifyId`).
66
- - Maintains fields such as `title`, `shopifyVendor`, `shopifyStatus`, publication timestamps, tags, and synchronization metadata.
67
- - Relationships with `variants` (product variants) and `suppliers`.
68
- - Supports soft deletion with a `deletedAt` timestamp.
69
- - Stores stock level configuration in JSON format.
70
-
71
- #### ProductVariantEntity (Referenced indirectly)
72
- - Represents the individual variant of a product.
73
- - Supports tagging and components indicating sub-parts if part of bundles.
74
-
75
- #### InventoryItemEntity and InventoryItemHistoryEntity
76
- - Inventory items represent stock of a variant at a given location.
77
- - Inventory item history maintains daily snapshots and metrics, including sales velocity, quantities, incoming stock, and grading.
78
- - Tracks if the item is marked as a favorite and relevant retail/cost values.
79
-
80
- #### LocationEntity
81
- - Represents physical or virtual stock storage points.
82
- - Includes address details encapsulated in a JSON `info` field.
83
- - Linked uniquely to a team and Shopify location ID.
84
- - Includes flags such as `isDefault` and `isSynced` to manage location state and integration.
85
-
86
- #### SupplierEntity
87
- - Describes supplier with contact details, lead time, minimum order quantities, payment terms (upfront, net days, installments), and operational metadata.
88
- - Payment terms are managed via related entities to encapsulate different terms.
89
- - Maintains relationships to products and purchase orders.
90
-
91
- #### ProductSupplierEntity and ProductSupplierVariantEntity
92
- - Junction tables linking suppliers with products and product variants respectively.
93
- - Flag for primary suppliers at the product level.
94
- - Variant-level mapping includes pricing and supplier SKU.
95
-
96
- #### ProductVariantComponentEntity
97
- - Defines hierarchical relationships between variants when products are bundled or composed of multiple variants.
98
- - Supports quantity mapping of child components.
99
-
100
- ### 6. Key Services and Providers
101
-
102
- - **ProductsService** & **ProductsMappingService**: Handles product and variant data operations including mappings.
103
- - **InventoryService** & **InventorySalesMetricsService**: Manages inventory levels, history, and sales-related metrics.
104
- - **LocationsService**: Manages stock location data.
105
- - **IdeaProductsService**: Specialized service for managing proposed or conceptual product entities.
106
- - **SavedViewService**: Provides management of persisted user views.
107
- - **DashboardService**: Aggregates and provides dashboard-relevant data.
108
- - **InsightsSyncService** and related Consumers: Handles data synchronization with external analytics and reporting services.
109
-
110
- ### 7. Integration Points
111
-
112
- - **ShopifyModule**: Importing and syncing product, variant, location, and inventory data using webhooks and APIs.
113
- - **SalesOrderModule**: Coordinating product sales data.
114
- - **PurchaseOrderModule**: Handling procurement and supply chain purchase orders.
115
- - **UserManagementModule**: Managing team and user ownership of product and supplier data.
116
-
117
- ### 8. System Boundaries
118
-
119
- - PIM module operates within Genie backend API, exposing RESTful API controllers.
120
- - External communication for Shopify synchronization is delegated via the Shopify integration.
121
- - Internal modules rely on PIM services for product and supplier data operations.
122
-
123
- ---
124
-
125
- ## Code Structure and Key Files
126
-
127
- - **`pim.module.ts`**
128
- - Defines module imports, controllers, providers, and exports.
129
- - Key imports include TypeOrm entities representing core domain models.
130
- - Uses `forwardRef` to resolve circular dependencies with SalesOrder and Shopify modules.
131
-
132
- - **Entities**
133
- - `product.entity.ts`: Core product data.
134
- - `product-variant.entity.ts`: Variants of a product.
135
- - `inventory-item.entity.ts` and `inventory-item-history.entity.ts`: Current stock and historical records.
136
- - `location.entity.ts`: Stock locations.
137
- - `supplier.entity.ts`: Supplier data.
138
- - `product-supplier.entity.ts`, `product-supplier-variant.entity.ts`: Supplier-product relationships.
139
- - `product-variant-component.entity.ts`: Components representing product bundles.
140
-
141
- - **Controllers**
142
- - Handle HTTP requests for product, inventory, locations, saved views, dashboard, idea products, and product-supplier mappings.
143
-
144
- - **Services**
145
- - Implement business logic for each domain, including synchronization, metrics, favorites, and scheduled background tasks.
146
-
147
- ---
148
-
149
- ## Example Entity Snippet: LocationEntity
150
- ```ts
151
- @Entity("location")
152
- @Index(["teamId", "shopifyId"], { unique: true })
153
- export class LocationEntity extends BaseEntity {
154
- @Index()
155
- @Column({ type: "uuid" })
156
- teamId!: string;
157
-
158
- @ManyToOne(() => TeamEntity, { onDelete: "CASCADE" })
159
- team?: TeamEntity;
160
-
161
- @Column({ type: "bigint", transformer: BigIntTransformer })
162
- shopifyId!: number;
163
-
164
- @Column({ type: "character varying", nullable: true })
165
- name?: string | null;
166
-
167
- @Column({ type: "jsonb" })
168
- info!: LocationInfo;
169
-
170
- @OneToMany(() => ProductVariantLocationEntity, (entity) => entity.location)
171
- productVariants?: ProductVariantLocationEntity[];
172
-
173
- @Column()
174
- isDefault!: boolean;
175
-
176
- @Column({ type: "boolean", default: true })
177
- isSynced!: boolean;
178
-
179
- @Index()
180
- @DeleteDateColumn()
181
- deletedAt?: Date;
182
- }
183
- ```
184
-
185
- ---
186
-
187
- ## Mermaid Diagram: PIM Module Architecture
188
-
189
- ```mermaid
190
- flowchart TD
191
- subgraph "PIM Module"
192
- ProductsService["ProductsService"]:::service
193
- InventoryService["InventoryService"]:::service
194
- LocationsService["LocationsService"]:::service
195
- SuppliersService["SuppliersService"]:::service
196
- SavedViewService["SavedViewService"]:::service
197
- DashboardService["DashboardService"]:::service
198
- ProductsController["ProductsController"]:::controller
199
- InventoryController["InventoryController"]:::controller
200
- LocationsController["LocationsController"]:::controller
201
- SuppliersController["SuppliersController"]:::controller
202
- end
203
-
204
- subgraph "Entities"
205
- ProductEntity["ProductEntity"]:::entity
206
- ProductVariantEntity["ProductVariantEntity"]:::entity
207
- InventoryItemEntity["InventoryItemEntity"]:::entity
208
- InventoryItemHistoryEntity["InventoryItemHistoryEntity"]:::entity
209
- LocationEntity["LocationEntity"]:::entity
210
- SupplierEntity["SupplierEntity"]:::entity
211
- ProductSupplierEntity["ProductSupplierEntity"]:::entity
212
- ProductSupplierVariantEntity["ProductSupplierVariantEntity"]:::entity
213
- ProductVariantComponentEntity["ProductVariantComponentEntity"]:::entity
214
- end
215
-
216
- subgraph "External Modules"
217
- ShopifyModule["ShopifyModule"]:::module
218
- SalesOrderModule["SalesOrderModule"]:::module
219
- PurchaseOrderModule["PurchaseOrderModule"]:::module
220
- UserManagementModule["UserManagementModule"]:::module
221
- TrackingModule["TrackingModule"]:::module
222
- end
223
-
224
- %% Relationships
225
- ProductsController -->|"uses"| ProductsService
226
- InventoryController -->|"uses"| InventoryService
227
- LocationsController -->|"uses"| LocationsService
228
- SuppliersController -->|"uses"| SuppliersService
229
- ProductsService -->|"manages"| ProductEntity
230
- ProductsService -->|"manages"| ProductVariantEntity
231
- InventoryService -->|"manages"| InventoryItemEntity
232
- InventoryService -->|"manages"| InventoryItemHistoryEntity
233
- LocationsService -->|"manages"| LocationEntity
234
- SuppliersService -->|"manages"| SupplierEntity
235
- SuppliersService -->|"manages"| ProductSupplierEntity
236
- SuppliersService -->|"manages"| ProductSupplierVariantEntity
237
- ProductsService -->|"manages"| ProductVariantComponentEntity
238
-
239
- %% Cross-Module Dependencies
240
- ProductsService -->|"calls"| ShopifyModule
241
- InventoryService -->|"calls"| SalesOrderModule
242
- SuppliersService -->|"calls"| PurchaseOrderModule
243
- SuppliersService -->|"calls"| UserManagementModule
244
- InventoryService -->|"calls"| TrackingModule
245
-
246
- %% Click Events
247
- click ProductsModule "apps/api/src/pim/pim.module.ts"
248
- click ProductEntity "apps/api/src/pim/entities/product.entity.ts"
249
- click ProductVariantEntity "apps/api/src/pim/entities/product-variant.entity.ts"
250
- click InventoryItemEntity "apps/api/src/pim/entities/inventory-item.entity.ts"
251
- click InventoryItemHistoryEntity "apps/api/src/pim/entities/inventory-item-history.entity.ts"
252
- click LocationEntity "apps/api/src/pim/entities/location.entity.ts"
253
- click SupplierEntity "apps/api/src/supplier/entities/supplier.entity.ts"
254
- click ProductSupplierEntity "apps/api/src/pim/entities/product-supplier.entity.ts"
255
- click ProductSupplierVariantEntity "apps/api/src/pim/entities/product-supplier-variant.entity.ts"
256
- click ProductVariantComponentEntity "apps/api/src/pim/entities/product-variant-component.entity.ts"
257
- click ShopifyModule "apps/api/src/shopify"
258
- click SalesOrderModule "apps/api/src/sales-order"
259
- click PurchaseOrderModule "apps/api/src/purchase-order"
260
- click UserManagementModule "apps/api/src/user-management"
261
- click TrackingModule "apps/api/src/tracking"
262
-
263
- classDef service fill:#f9f,stroke:#333,stroke-width:2px
264
- classDef controller fill:#bbf,stroke:#333,stroke-width:2px
265
- classDef entity fill:#bfb,stroke:#333,stroke-width:2px
266
- classDef module fill:#ffd700,stroke:#333,stroke-width:2px
267
- ```
@@ -1,176 +0,0 @@
1
- ---
2
- title: 'Billing & Plans'
3
- description: 'Details on plan selection, subscription management, and billing integration.'
4
- ---
5
-
6
- ## Billing & Plans Module Documentation
7
-
8
- ---
9
-
10
- ### 1. Purpose and Scope
11
-
12
- The Billing & Plans module manages subscription plans and billing interactions for users within the Genie platform. It facilitates plan selection, subscription management, and billing interval adjustments. This component enables users to view and upgrade their current subscription plans, handles plan-related UI interactions, and integrates with the Mantle billing service.
13
-
14
- **System boundaries and architectural context:**
15
- - This module is part of the Platform & Administration layer responsible for billing and subscription management.
16
- - It interfaces with the Mantle client library (`@heymantle/react`), which provides hooks like `useMantle` for accessing plans, subscriptions, and subscription mutations.
17
- - It interacts with routing (`next/router`) and authentication context to manage user state.
18
- - The component is implemented in React with hooks and integrated into the settings page UI under billing controls.
19
-
20
-
21
- ### 2. Technical Overview
22
-
23
- The Billing & Plans module consists primarily of UI React components that:
24
- - Display the current active plan for a team (`TeamActivePlanCard`).
25
- - Present a modal dialog (`PlanSelectionModal`) for users to select a subscription plan and billing interval.
26
-
27
- The module relies on Mantle API hooks (`useMantle`) for retrieving plans and subscriptions, subscribing users to selected plans, and refetching subscription data post-actions.
28
-
29
- The subscription flow includes:
30
- - Rendering the user's current plan in `TeamActivePlanCard` with option to upgrade.
31
- - Displaying selectable plans filtered by billing interval in `PlanSelectionModal`.
32
- - Managing form state with `react-hook-form` to select plans and billing intervals.
33
- - Triggering the Mantle `subscribe` mutation when the user submits a selection.
34
- - Handling redirection to confirmation URLs or returning to the billing settings tab upon subscription success.
35
-
36
- #### Key Technologies and Patterns
37
- - React functional components with hooks (`useForm`, `useWatch`) for state and form management.
38
- - Mantle React SDK for billing logic integration.
39
- - Next.js routing utilities for programmatic navigation.
40
- - Controlled components pattern for form inputs.
41
- - UI composition with custom reusable components (`Modal`, `Button`, `Radio`, `Typography`, etc.).
42
-
43
-
44
- ### 3. Core Concepts and Responsibilities
45
-
46
- - **Plans:** A subscription offering defined by ID, name, billing interval (`EVERY_30_DAYS` or `ANNUAL`), price, currency, and optional description.
47
- - **Subscription:** The current user’s active subscription, includes the plan and payment status.
48
- - **Billing Intervals:** Differ between monthly (`EVERY_30_DAYS`) and annual (`ANNUAL`) billing cycles.
49
- - **Plan Selection Modal:** Enables users to select and subscribe to plans filtered by chosen billing interval.
50
- - **Subscription Flow:** Handled via Mantle `subscribe` method with automatic redirection to external payment confirmation or immediate update.
51
-
52
- **Ownership & Logging:**
53
- - UI components logging is minimal as this module focuses on user interaction.
54
- - Mantle service manages backend billing workflows and errors.
55
-
56
-
57
- ### 4. Code Structure
58
-
59
- | File | Description |
60
- |-------|-------------|
61
- | `apps/web/src/components/jasmine/billing/plan-selection-modal/index.tsx` | Implements the plan selection modal component with billing interval selector and plan cards. Handles subscription mutation and routing post-selection. |
62
- | `apps/web/src/components/jasmine/billing/plan-selection-modal/plan-card.tsx` | Renders individual selectable plan cards including name, description, pricing, and current plan indicator. |
63
- | `apps/web/src/components/jasmine/billing/plan-selection-modal/billing-interval-select.tsx` | Dropdown component for selecting billing interval (Monthly or Yearly). |
64
- | `apps/web/src/components/jasmine/billing/team-active-plan-card.tsx` | Displays the currently active team plan with details and an 'Upgrade Plan' call to action. |
65
- | `apps/web/src/components/pages/settings/plans-and-billing-settings.tsx` | Top-level page component that shows the active plan card and controls opening the plan selection modal. |
66
-
67
- **Key component snippet from plan-selection-modal:**
68
-
69
- ```tsx
70
- // Default form values set based on available plans or current subscription
71
- const {
72
- control,
73
- handleSubmit,
74
- resetField,
75
- reset,
76
- formState: { isSubmitting, isLoading },
77
- } = useForm<FormFields>({
78
- defaultValues: {
79
- selectedPlan: plans.find(p => p.interval === 'EVERY_30_DAYS')?.id || subscription?.plan.id,
80
- billingInterval: 'EVERY_30_DAYS',
81
- },
82
- });
83
-
84
- // Filter plans visible based on selected billing interval or free plans
85
- const filteredPlans = plans
86
- .filter(plan => plan.interval === watchBillingInterval || plan.amount === 0)
87
- .sort((a, b) => a.interval === 'EVERY_30_DAYS' ? -1 : b.interval === 'EVERY_30_DAYS' ? 1 : 0);
88
-
89
- // On form submit, execute subscription mutation and handle redirects
90
- await subscribe({ planId: selectedPlan, returnUrl });
91
- ```
92
-
93
-
94
- ### 5. API and Interfaces
95
-
96
- #### Subscribed Functions
97
- - `subscribe({ planId: string, returnUrl: string }) => Promise<{ confirmationUrl?: string }>`
98
- - Initiates the subscription to a selected plan.
99
- - If `confirmationUrl` is provided, the client redirects the user for payment or confirmation.
100
-
101
- #### Forms
102
- - `selectedPlan` (string): The unique ID of the selected plan.
103
- - `billingInterval` (`EVERY_30_DAYS` | `ANNUAL`): The chosen subscription recurrence period.
104
-
105
- #### Failure modes
106
- - Subscription mutation may fail or return an error (not explicitly handled in UI, fallback to Mantle error handling).
107
- - No fallback UI is described for failures or loading errors beyond button disabling and loading state.
108
-
109
-
110
- ### 6. Environment & Configuration
111
-
112
- - No explicit environment variables or secrets are required by the frontend module beyond those configured globally for Mantle and Next.js.
113
- - The backend Mantle service (not detailed here) handles billing API calls and subscriptions.
114
-
115
-
116
- ### 7. Testing, Monitoring, and Deployment
117
-
118
- - Specific tests for the Billing & Plans UI are not detailed in the provided context.
119
- - Loading states and controlled form validations are implemented to manage UX during asynchronous calls.
120
- - Monitoring and errors during subscription are managed downstream in Mantle and API layers.
121
-
122
-
123
- ### 8. Troubleshooting & Known Issues
124
-
125
- - No documented known issues or specific troubleshooting guides exist in the current context.
126
- - UI disables subscription button if the selected plan matches the current subscription plan to prevent redundant submissions.
127
-
128
-
129
- ### 9. Integration Details
130
-
131
- This module tightly integrates:
132
- - With the Mantle billing service for fetching plans and managing subscriptions.
133
- - With Next.js routing to redirect users after subscription actions.
134
- - With authentication context to personalize UI (e.g., displaying user initials).
135
-
136
- The common integration pattern is user-initiated plan changes within the app settings UI, backed by Mantle API calls, with smooth UI updates upon success.
137
-
138
-
139
- ---
140
-
141
- ## Mermaid Diagram: Billing & Plans Module Architecture
142
-
143
- ```mermaid
144
- flowchart TD
145
- subgraph UI
146
- SettingsPage["Plans & Billing Settings Page"]:::ui
147
- ActivePlanCard["TeamActivePlanCard"]:::ui
148
- PlanModal["PlanSelectionModal"]:::ui
149
- BillingIntervalSelect["BillingIntervalSelect"]:::ui
150
- PlanCard["PlanCard (Selectable Plan Cards)"]:::ui
151
- end
152
-
153
- subgraph Services
154
- Mantle["Mantle Billing Service"]:::service
155
- AuthContext["Auth Context"]:::service
156
- Router["Next.js Router"]:::service
157
- end
158
-
159
- SettingsPage -->|"shows current plan"| ActivePlanCard
160
- SettingsPage -->|"opens modal"| PlanModal
161
- PlanModal --> BillingIntervalSelect
162
- PlanModal --> PlanCard
163
- PlanModal -->|"uses hook"| Mantle
164
- PlanModal -->|"uses auth info"| AuthContext
165
- PlanModal -->|"redirect after subscribe"| Router
166
-
167
- classDef ui fill:#f9f9f9,stroke:#77aaff,color:#222,stroke-width:1px;
168
- classDef service fill:#cde9ff,stroke:#005aee,color:#03396c,stroke-width:2px;
169
-
170
- click SettingsPage "apps/web/src/components/pages/settings/plans-and-billing-settings.tsx"
171
- click ActivePlanCard "apps/web/src/components/jasmine/billing/team-active-plan-card.tsx"
172
- click PlanModal "apps/web/src/components/jasmine/billing/plan-selection-modal/index.tsx"
173
- click BillingIntervalSelect "apps/web/src/components/jasmine/billing/plan-selection-modal/billing-interval-select.tsx"
174
- click PlanCard "apps/web/src/components/jasmine/billing/plan-selection-modal/plan-card.tsx"
175
-
176
- ```
@@ -1,184 +0,0 @@
1
- ---
2
- title: 'Database Migrations & Seeding'
3
- description: 'How to manage database schema migrations and seed the database with initial or demo data.'
4
- ---
5
-
6
- # Database Migrations & Seeding
7
-
8
- ## Purpose and Scope
9
-
10
- This document provides detailed technical guidance on managing database migrations and seeding for the Genie application. It covers how to create, generate, run, and revert database schema migrations using TypeORM tools integrated into the project, alongside instructions for initializing and seeding the local database. This module is essential for maintaining the PostgreSQL database schema consistency across development, staging, and production environments.
11
-
12
- The migration system is part of the back-end API built with NestJS and operates within the PostgreSQL database context managed via Docker.
13
-
14
- ## Technical Overview
15
-
16
- Database migrations in Genie are handled through TypeORM's CLI commands, orchestrated via Yarn scripts. Migrations ensure database schema evolves reliably along with application code changes. Seed commands reset the database, apply all migrations, and populate the database with required initial data.
17
-
18
- A dedicated migration class specifically addresses Purchase Orders, handling complex content version migrations in a paginated manner for scalability.
19
-
20
- ## Key Features
21
-
22
- - Creation and generation of new database migrations.
23
- - Execution and reversion of migrations.
24
- - Seeding of the local development database with initial data.
25
- - Migration of complex domain entities with version control.
26
-
27
- ## Setup and Configuration
28
-
29
- Before working with migrations, ensure the PostgreSQL database is running locally using Docker Compose as described in the installation guide. Ensure all necessary users are created in the database with appropriate privileges.
30
-
31
- Fill in the `.env` file with correct credentials corresponding to each database user.
32
-
33
- ## Migration Commands
34
-
35
- ### Create a Migration
36
-
37
- Creates a blank migration file for manual editing.
38
-
39
- ```bash
40
- yarn typeorm:create <MigrationName>
41
- ```
42
-
43
- Replace `<MigrationName>` with a descriptive name, e.g., `AddNewTable`.
44
-
45
- ### Generate a Migration
46
-
47
- Automatically generates a migration reflecting entity changes.
48
-
49
- ```bash
50
- yarn typeorm:generate <MigrationName>
51
- ```
52
-
53
- Replace `<MigrationName>` appropriately.
54
-
55
- ### Run Migrations
56
-
57
- Apply all pending migrations to the database.
58
-
59
- ```bash
60
- yarn typeorm:run
61
- ```
62
-
63
- ### Revert Last Migration
64
-
65
- Undo the last applied migration, reverting schema changes.
66
-
67
- ```bash
68
- yarn typeorm:revert
69
- ```
70
-
71
- ## Seeding Local Database
72
-
73
- To reset and populate the local database with initial data, run:
74
-
75
- ```bash
76
- yarn cmd seed-data
77
- ```
78
-
79
- This command drops the current schema, reapplies all migrations, and seeds essential data required for local development and testing.
80
-
81
- ## Purchase Orders Migration
82
-
83
- The `PurchaseOrdersMigration` service manages migration of purchase order records to keep content schemas up-to-date with the current version. It:
84
-
85
- - Iterates over purchase orders with versions older than the current defined version.
86
- - Loads migration functions from the migrations directory.
87
- - Applies migrations sequentially to the content field.
88
- - Saves updated purchase orders with the new version.
89
- - Logs errors and captures exceptions without failing the entire migration process.
90
-
91
- This approach handles large datasets efficiently by paginating through records in batches of 1000.
92
-
93
- ### Code Snippet (Migration Process Entry Point)
94
-
95
- ```ts
96
- @Injectable()
97
- export class PurchaseOrdersMigration implements Migration {
98
- private readonly logger = new Logger(PurchaseOrdersMigration.name);
99
-
100
- constructor(
101
- @InjectRepository(PurchaseOrderEntity)
102
- private purchaseOrderRepository: Repository<PurchaseOrderEntity>
103
- ) {}
104
-
105
- async migrate() {
106
- const migrateFns = await this.getMigrateFns();
107
- const pageSize = 1000;
108
- let page = 0;
109
- let purchaseOrders;
110
-
111
- do {
112
- purchaseOrders = await this.purchaseOrderRepository.find({
113
- where: { version: LessThan(PURCHASE_ORDER_CURRENT_VERSION) },
114
- skip: page * pageSize,
115
- take: pageSize,
116
- });
117
-
118
- await Promise.all(
119
- purchaseOrders.map(po => this.migratePurchaseOrder(po, migrateFns))
120
- );
121
-
122
- page++;
123
- } while (purchaseOrders.length === pageSize);
124
- }
125
-
126
- private async migratePurchaseOrder(po: PurchaseOrderEntity, migrateFns: MigrateFn[]) {
127
- try {
128
- if (po.version === migrateFns.length) return;
129
- po.content = await this.migrateSequentially(po.version, po.content, migrateFns);
130
- po.version = migrateFns.length;
131
- await this.purchaseOrderRepository.save(po);
132
- } catch (error) {
133
- this.logger.error(`Failed to migrate purchase order: ${po.id}`);
134
- captureException({ error, purchaseOrderEntity: JSON.stringify(po, null, 2) });
135
- }
136
- }
137
- }
138
- ```
139
-
140
- ## Database Integration & Access
141
-
142
- - The PostgreSQL database runs inside a Docker container, controlled via `docker-compose up -d`.
143
- - Use `docker ps` to identify the container ID and `docker logs <container-id>` to view database logs.
144
- - To enter the database shell:
145
-
146
- ```bash
147
- docker exec -it <container-id> bash
148
- psql -U postgres
149
- ```
150
-
151
- - To stop the database container:
152
-
153
- ```bash
154
- docker-compose down
155
- ```
156
-
157
- ## Database View Migrations
158
-
159
- Several migration scripts create or modify SQL views (e.g., `inventory_item`, `inventory_sales_metrics`) to reflect updated business logic, such as adding columns, views, indexes, or changing table structures.
160
-
161
- ### Important Database Views
162
-
163
- - **inventory_item**: Aggregates detailed inventory item information across products, variants, suppliers, and locations.
164
- - **inventory_sales_metrics**: Provides sales metrics for active product variants over configurable periods, supporting grading strategies.
165
-
166
- These views get updated as part of migrations to align with evolving application analytics and reporting requirements.
167
-
168
- ## Best Practices
169
-
170
- - Always create descriptive migration names that clearly indicate the schema change.
171
- - Confirm migrations run successfully in a development environment before applying to staging or production.
172
- - Use the `seed-data` command during initial setup or when resetting the local database to maintain consistent test data.
173
- - Monitor migration logs for errors, especially in batch operations like purchase order migrations.
174
-
175
- ## References
176
-
177
- - [TypeORM Migrations Documentation](https://typeorm.io/migrations)
178
- - Purchase orders migration entry: [purchase-orders.migration.ts](apps/api/src/migrations/purchase-orders/purchase-orders.migration.ts)
179
-
180
- ---
181
-
182
- For detailed schema changes, view the individual migration files under `apps/api/src/migrations/db`.
183
-
184
- ---