@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,127 +0,0 @@
1
- ---
2
- title: 'Installation & Setup Guide'
3
- description: 'Steps to clone, install dependencies, run the application, and prepare the database.'
4
- ---
5
-
6
- ## Installation & Setup Guide
7
-
8
- ### Overview
9
- This guide covers the installation and setup of the Genie application backend and frontend components essential for onboarding, data synchronization, and product variant management.
10
-
11
- Genie integrates tightly with Shopify stores to synchronize product, inventory, bundle, and purchase order data. It handles onboarding workflows, monitors product variant counts, and manages webhooks for real-time data sync.
12
-
13
- ### Components Involved
14
- - **Onboarding Service**: Manages user onboarding progress, data synchronization, and notification workflows.
15
- - **Shopify Webhooks Service**: Registers and manages Shopify webhook subscriptions for data updates.
16
- - **Database Views and Migrations**: Defines database schemas, especially for inventory data and product variant tracking.
17
- - **Frontend Modals and UI Components**: Provide user feedback and guides, such as store size warnings when variant count is large.
18
-
19
- ---
20
-
21
- ## Backend Installation & Setup
22
-
23
- ### 1. Database Setup and Migrations
24
-
25
- Genie uses a PostgreSQL database with TypeORM. Core migrations include:
26
-
27
- - **Initial Database Schema**: Creates tables for users, teams, products, product variants, purchase orders, and related entities. [Initialise Migration](apps/api/src/migrations/db/1688040345407-Initialise.ts)
28
- - **Inventory Item View**: Creates a SQL view consolidating product and variant data for inventory management, including sales and stock metrics. This view gets updated with new columns like `isNewProduct` for enhanced data insights. [Inventory View Migration](apps/api/src/migrations/db/1692960155848-add-is-new-product-to-inventory-item-view.ts)
29
- - **Product Variant Location & Shopify Inventory Item ID**: Adds location-based inventory tracking and links variants to Shopify InventoryItem IDs. [Variant Location Migration](apps/api/src/migrations/db/1701958615964-add-product-variant-location-and-shopify-inventory-item-id.ts)
30
-
31
- Run migrations after database setup to ensure schema is current.
32
-
33
- ### 2. Onboarding Service Setup
34
-
35
- The `OnboardingService` handles setup progress and sync workflows:
36
-
37
- - Initializes onboarding progress record for a new team.
38
- - Verifies product variant count does not exceed limits and disables teams if necessary.
39
- - Manages multi-step onboarding including insight settings, grading, suppliers, purchase order import, bundle mapping, and final completion.
40
- - Tracks progress and triggers background data sync jobs using BullMQ queues (`QUEUE.ONBOARDING`).
41
-
42
- Key files and location:
43
- - Service: `apps/api/src/setup/services/onboarding.service.ts`
44
- - Controller: `apps/api/src/setup/controllers/onboarding.controller.ts`
45
- - Module: `apps/api/src/setup/setup.module.ts`
46
-
47
- **Important:** On module initialization, the onboarding service resumes incomplete onboarding flows for all teams to ensure no data sync or onboarding step is left hanging after a server restart.
48
-
49
- ### 3. Shopify Webhooks
50
-
51
- Webhook registration is essential for real-time syncing of Shopify events such as:
52
- - Products and variants create, update, delete
53
- - Locations activate, create, update, delete
54
- - Inventory levels update and disconnect
55
- - Collections create, update, delete
56
- - Orders create, update, cancel, delete
57
- - Shop updates
58
-
59
- The `WebhooksInsightsSyncService` manages webhook registration and event processing pipelines. It includes:
60
- - Registration and unregistration of webhooks for active/inactive teams
61
- - Processing batched Shopify events through a set of ordered pipes for syncing data to database
62
- - Retry mechanism for failed webhook registrations
63
-
64
- Files of interest:
65
- - `apps/api/src/pim/services/webhooks-insights-sync.service.ts`
66
-
67
- ### 4. Billing & Subscription
68
-
69
- The `MantleService` integrates billing, subscription state handling, and plan assignments:
70
- - Identifies customers in the billing system and assigns plans
71
- - Handles trial expirations, subscription cancellations, activations
72
- - Reacts to install/reinstall/uninstall Shopify app webhooks
73
-
74
- File:
75
- - `apps/api/src/billing/services/mantle.service.ts`
76
-
77
- ---
78
-
79
- ## Frontend Setup
80
-
81
- ### 1. Store Size Warning Modal
82
-
83
- To alert users whose Shopify store has a very high number of product variants (exceeding `MAX_ALLOWED_PRODUCT_VARIANTS_COUNT`), Genie shows a modal prompting a discovery call before proceeding with onboarding.
84
-
85
- - The modal displays the exact variant count fetched by querying the API.
86
- - Includes an embedded HubSpot calendar iframe to book time with the Genie team.
87
-
88
- Relevant file:
89
- - `apps/web/src/components/pages/Onboarding/store-too-large-modal.tsx`
90
-
91
- ### 2. Sync Product Variants Manually
92
-
93
- Users can manually refresh Shopify store sync from settings:
94
-
95
- - The "Shopify Store Data" card lets users trigger manual sync to refresh product variants.
96
- - Sync status and feedback notifications are provided.
97
-
98
- Relevant file:
99
- - `apps/web/src/components/pages/settings/general-settings.tsx`
100
-
101
- ---
102
-
103
- ## Running Genie Locally
104
-
105
- 1. **Set up all environment variables** as per your environment. Refer to `Environment Variables & Configuration` documentation for required keys.
106
- 2. **Initialize and migrate the database** using TypeORM migrations.
107
- 3. **Start backend services**, ensuring BullMQ queues and Redis are operational for job processing.
108
- 4. **Start the frontend web server** using Next.js; the onboarding modals and syncing features will be accessible.
109
-
110
- ---
111
-
112
- ## Summary
113
- This installation and setup guide provides technical details for initializing Genie’s backend services, database, webhooks integration with Shopify, billing system connectivity, and frontend user experience components necessary for a seamless onboarding and store data synchronization process.
114
-
115
- Developers are encouraged to familiarize themselves with the onboarding service flows and webhook synchronization pipelines to understand the end-to-end data flow from Shopify to Genie’s internal representations and UI triggers.
116
-
117
- For deeper understanding, review:
118
- - [Onboarding Service Implementation](apps/api/src/setup/services/onboarding.service.ts)
119
- - [Webhook Synchronization Service](apps/api/src/pim/services/webhooks-insights-sync.service.ts)
120
- - [General Settings Sync Component](apps/web/src/components/pages/settings/general-settings.tsx)
121
- - [Store Too Large Modal](apps/web/src/components/pages/Onboarding/store-too-large-modal.tsx)
122
-
123
- Regularly check migration files to keep the schema updated and refer to the workflow queues for processing status.
124
-
125
- ---
126
-
127
- Please refer to the respective internal modules and service implementations for detailed operational logic and error handling behaviors.
@@ -1,199 +0,0 @@
1
- ---
2
- title: 'Error Tracking with Sentry'
3
- description: 'Sentry integration details including error filters and module usages.'
4
- ---
5
-
6
- ## Error Tracking with Sentry
7
-
8
- ### Purpose and Scope
9
-
10
- The Sentry integration within the Genie App is designed to capture, track, and monitor runtime errors and performance issues across the entire application stack. This includes capturing errors in the backend API (NestJS), frontend web application (Next.js), and edge middleware/runtime environments. The primary role of the Sentry integration is to provide comprehensive error reporting and observability, enabling developers to diagnose, trace, and resolve issues promptly.
11
-
12
- This integration handles exception capturing, context enrichment, transaction tracing, profiling, and custom event tracking. It supports error reporting from different runtime contexts such as server-side, client-side, and edge environments.
13
-
14
- ### Technical Overview
15
-
16
- The Sentry service is integrated at multiple layers of the Genie App:
17
-
18
- - **Backend (API)**: Sentry is initialized using `@sentry/nestjs` with advanced configurations including performance tracing, CPU profiling, and custom sampling strategies. The setup is found in `apps/api/src/sentry-integration/instrument.ts`.
19
- - **Frontend (Web)**: Sentry initialization is split into client, server, and edge configurations using the `@sentry/nextjs` package, each tailored for their execution context (`sentry.client.config.ts`, `sentry.server.config.ts`, `sentry.edge.config.ts`).
20
- - **Custom Exception Handling**: A helper `captureException` function enriches error events with additional contextual data such as user details, team info, and breadcrumbs specific to internally defined `GenieException` class.
21
-
22
- #### Architectural Context
23
-
24
- ```mermaid
25
- flowchart TD
26
- subgraph Backend API Layer
27
- APISentryInit[Sentry Init]:::backend
28
- TrackingService[TrackingService]:::backend
29
- ExceptionHandler[captureException Helper]:::backend
30
- end
31
-
32
- subgraph Frontend Web Layer
33
- ClientSentryInit[Sentry Init Next.js Client]:::frontend
34
- ServerSentryInit[Sentry Init Next.js Server]:::frontend
35
- EdgeSentryInit[Sentry Init Next.js Edge]:::frontend
36
- OnErrorHandler[Global onError Handler]:::frontend
37
- TestPage[Error Trigger Page]:::frontend
38
- end
39
-
40
- subgraph External Services
41
- SentryService[Sentry Platform]:::external
42
- SegmentService[Segment Analytics Service]:::backend
43
- HubspotService[Hubspot Analytics Service]:::backend
44
- end
45
-
46
- APISentryInit -->|captures errors| SentryService
47
- ExceptionHandler -->|enhanced capture| SentryService
48
- TrackingService -->|captures exceptions using captureException| ExceptionHandler
49
-
50
- ClientSentryInit -->|captures client-side errors| SentryService
51
- ServerSentryInit -->|captures server-side errors| SentryService
52
- EdgeSentryInit -->|captures edge errors| SentryService
53
- OnErrorHandler -->|captures errors on UI| ClientSentryInit
54
- TestPage -->|explicitly capture test error| ClientSentryInit
55
-
56
- classDef backend fill:#d0ebff,stroke:#339af0,color:#1c7ed6,stroke-width:1px;
57
- classDef frontend fill:#d3f9d8,stroke:#40c057,color:#2b8a3e,stroke-width:1px;
58
- classDef external fill:#ffe3e3,stroke:#fa5252,color:#c92a2a,stroke-width:1px;
59
-
60
- click APISentryInit "apps/api/src/sentry-integration/instrument.ts"
61
- click ExceptionHandler "apps/api/src/commons/error-handlers/captureException.ts"
62
- click TrackingService "apps/api/src/tracking/services/tracking.service.ts"
63
- click ClientSentryInit "apps/web/sentry.client.config.ts"
64
- click ServerSentryInit "apps/web/sentry.server.config.ts"
65
- click EdgeSentryInit "apps/web/sentry.edge.config.ts"
66
- click OnErrorHandler "apps/web/src/utils/on-error.ts"
67
- click TestPage "apps/web/src/pages/test-error.tsx"
68
- click SegmentService "apps/api/src/tracking/services/segment.service.ts"
69
- click HubspotService "apps/api/src/tracking/services/tracking.service.ts"
70
- ```
71
-
72
- ### Core Concepts and Responsibilities
73
-
74
- - **Sentry Initialization Per Context**: Sentry is initialized separately for server, client, and edge environments, ensuring tailored configurations for each runtime.
75
- - **Error Enrichment**: Errors thrown as `GenieException` carry rich context. These exceptions are parsed to add breadcrumbs recursively, and user/team contextual data is embedded before sending to Sentry.
76
- - **Performance and Profiling**: On the API backend, the Sentry SDK uses node processing and CPU profiling integrations, with finely controlled sampling based on request URL and environment.
77
- - **Event Tracking Integration**: The tracking system (`TrackingService`) leverages `captureException` to log error events internally, integrating Sentry error tracking with business events.
78
- - **Interactive Error Capture**: Frontend includes manual error capturing on demand (e.g., in `test-error.tsx`) for validation and debugging.
79
-
80
- ### Code Structure
81
-
82
- - **API Layer:**
83
- - `apps/api/src/sentry-integration/instrument.ts`: Sets up Sentry SDK with environment-based sampling and profiling.
84
- - `apps/api/src/commons/error-handlers/captureException.ts`: Provides a utility function to capture exceptions with enhanced context and breadcrumbs.
85
- - `apps/api/src/tracking/services/tracking.service.ts`: Integrates error capture into event tracking flows.
86
-
87
- - **Web Frontend:**
88
- - `apps/web/sentry.client.config.ts`: Initializes Sentry for client-side errors and session replay with specific integrations.
89
- - `apps/web/sentry.server.config.ts`: Configures server-side Sentry initialization for Next.js pages.
90
- - `apps/web/sentry.edge.config.ts`: Configures Sentry for edge runtime features.
91
- - `apps/web/src/utils/on-error.ts`: Central error handler capturing errors and sending to Sentry while managing authentication errors.
92
- - `apps/web/src/pages/test-error.tsx`: Example page to trigger and capture errors for testing Sentry integration.
93
-
94
- #### Example: Enhanced Exception Capture (from `captureException.ts`)
95
- ```ts
96
- export function captureException({
97
- error,
98
- context,
99
- logger,
100
- genieContext,
101
- }: {
102
- error: unknown;
103
- context?: ExecutionContext;
104
- logger?: Logger;
105
- genieContext?: GenieExecutionContext;
106
- }) {
107
- (logger ?? console).error(getErrorMessages(error).join("\n\n"));
108
-
109
- Sentry.withScope((scope: Sentry.Scope) => {
110
- if (error instanceof GenieException) {
111
- addGenieBreadcrumb(scope, error.cause);
112
- }
113
-
114
- const transaction = context?.switchToHttp().getRequest();
115
- if (transaction) {
116
- scope.addEventProcessor((event) =>
117
- addRequestDataToEvent(event, transaction, { include: { ip: true, request: ["method", "url", "headers"] } })
118
- );
119
- }
120
-
121
- if (genieContext?.user) {
122
- scope.setContext("user", genieContext.user);
123
- }
124
- if (genieContext?.team) {
125
- scope.setContext("team", genieContext.team);
126
- }
127
-
128
- Sentry.captureException(error, error instanceof GenieException ? { extra: error.context } : undefined);
129
- });
130
- }
131
- ```
132
-
133
- ### Environment & Configuration
134
-
135
- | Environment Variable | Purpose | Used In |
136
- |----------------------------|--------------------------------------------|------------------------------------------------|
137
- | `SENTRY_DSN` | DSN for backend Sentry error reporting | `apps/api/src/sentry-integration/instrument.ts`|
138
- | `API_ENV` | API environment (e.g., production, staging) | Controls sampling and profiling |
139
- | `NEXT_PUBLIC_SENTRY_DSN` | DSN for frontend (client, server, edge) | `apps/web/sentry.*.config.ts` |
140
-
141
- #### Sampling Strategies (Backend)
142
- - Transactions and CPU profiling sampling are customized based on URL filtering and environment (production uses 0.5 and 0.3 rates respectively)
143
- - Certain webhook URLs (`/shopify/webhooks`) and endpoints ending with space are ignored from sampling.
144
-
145
- #### Frontend Sampling
146
- - Traces sample rate is set to 1 for client, server, and edge in non-production setups.
147
- - Client-side config enables session replay at 100% on error and samples sessions at 10%.
148
-
149
- ### Usage Examples
150
-
151
- #### Triggering a Manual Error Capture on Frontend
152
- ```tsx
153
- import * as Sentry from "@sentry/nextjs";
154
-
155
- const triggerError = () => {
156
- try {
157
- throw new Error("This is a test error!");
158
- } catch (error) {
159
- Sentry.captureException(error);
160
- console.error("Error captured by Sentry:", error);
161
- }
162
- };
163
- ```
164
- Use this pattern on internal test pages to verify Sentry capturing behavior.
165
-
166
- #### Tracking Errors in Backend Service
167
- Within the `TrackingService`, any error during event processing is captured:
168
- ```ts
169
- try {
170
- // event tracking logic
171
- } catch (error) {
172
- captureException({ error, logger: this.logger });
173
- }
174
- ```
175
-
176
- ### Testing, Monitoring, and Debugging
177
-
178
- - Logs are available via NestJS `Logger` instances and consolidated with Sentry events.
179
- - The `captureException` helper prints error details to logger or console in addition to sending to Sentry.
180
- - The frontend global error handler enriches Axios errors with HTTP request and response data in Sentry.
181
- - The profiling integrations on the backend allow monitoring of CPU and transaction duration for performance tuning.
182
-
183
- ### Integration Details
184
-
185
- - The Sentry service is integrated closely with the custom error type `GenieException`, allowing detailed breadcrumbs and context to be sent.
186
- - Error capture is spread across backend services, frontend global error handlers, and manual triggers for comprehensive coverage.
187
- - This integration supports multi-environment setup via environment variables, allowing differentiation between dev, staging, and production.
188
-
189
- ---
190
-
191
- For further exploration, see the following implementation files:
192
- - Backend Sentry init: `apps/api/src/sentry-integration/instrument.ts`
193
- - Backend exception capture: `apps/api/src/commons/error-handlers/captureException.ts`
194
- - Tracking service usage: `apps/api/src/tracking/services/tracking.service.ts`
195
- - Frontend client config: `apps/web/sentry.client.config.ts`
196
- - Frontend server config: `apps/web/sentry.server.config.ts`
197
- - Frontend edge config: `apps/web/sentry.edge.config.ts`
198
- - Frontend error handler: `apps/web/src/utils/on-error.ts`
199
- - Test error page: `apps/web/src/pages/test-error.tsx`
@@ -1,189 +0,0 @@
1
- ---
2
- title: 'Slack Notifications'
3
- description: 'Slack service integrations for alerts and application notifications.'
4
- ---
5
-
6
- # Slack Notifications
7
-
8
- ## Purpose and Scope
9
-
10
- The `SlackService` is a core notification component within the Genie application ecosystem. It facilitates sending varied notifications directly to designated Slack channels, primarily concerning user reports, onboarding progress, feature suggestions, system alerts, and purchase order activities. This service abstracts Slack integration details and provides specialized message formats to ensure consistent communication flow.
11
-
12
- It serves as the bridge between the Genie backend and Slack, supporting actionable alerts and update notifications critical to team coordination and monitoring.
13
-
14
- This service operates within the backend API layer of the application and depends on Slack's Web API via the `@slack/web-api` client.
15
-
16
- ## Technical Overview
17
-
18
- `SlackService` is implemented as an injectable singleton service in a NestJS environment, leveraging `@nestjs/common` for dependency injection and lifecycle management.
19
-
20
- - Uses Slack's WebClient initialized with an application token (`SLACK_APP_TOKEN`).
21
- - Interacts with Slack channels to post messages ensuring the app is a member before posting.
22
- - Retrieves application user ID dynamically to verify channel membership.
23
- - Wraps operations with custom exceptions (`GenieException`) to provide contextual error handling.
24
- - Retrieves environment configuration values dynamically via a `ConfigService`.
25
-
26
- ### Integration Points
27
-
28
- - ConfigService: Supplies Slack tokens and channel IDs.
29
- - GenieException: Provides domain-specific error wrapping.
30
- - Slack Web API: Underlying external dependency for communications.
31
- - Util functions: `getTeamLabel` and `getUserLabel` generate formatted labels in notifications.
32
-
33
- ### Key Functional Roles
34
-
35
- - Joining channels automatically if not a member.
36
- - Sending generalized text notifications.
37
- - Sending specialized, structured notifications for:
38
- - New user report requests
39
- - Date range feature suggestions
40
- - Daily data sync performance summaries
41
- - Product bundles import requests and onboarding
42
- - Purchase order import requests
43
- - Sales sync health check updates
44
-
45
- ## Core Concepts and Responsibilities
46
-
47
- ### Design Assumptions and Decisions
48
-
49
- - Slack authorization is managed using a single app token stored in configuration.
50
- - The service proactively joins channels to avoid permission errors when sending messages.
51
- - Custom error handling enhances observability by including contextual metadata.
52
- - Notification content follows Slack's markdown formatting conventions for readability.
53
- - Separate system alert and user request channels are used, identified via dedicated env variables.
54
-
55
- ### Ownership and Maintenance
56
-
57
- - Maintained by the backend team managing integrations and notifications.
58
- - Errors and failures are surfaced through `GenieException` for centralized logging.
59
-
60
- ### Non-Functional Requirements
61
-
62
- - Reliability: Ensures app joins channels before messaging.
63
- - Scalability: Modular methods allow adding more notification types easily.
64
- - Security: The app token is securely managed and scoped.
65
-
66
- ## Code Structure
67
-
68
- ### Location
69
-
70
- - Primary source: `apps/api/src/slack/services/slack.service.ts`
71
-
72
- ### Overview of Components
73
-
74
- - **SlackService Class**: Main class encapsulating all Slack notification logic.
75
- - **Methods:**
76
- - `joinChannel(channelId)`: Joins a Slack channel.
77
- - `isAppMemberOfChannel(channelId)`: Checks membership status.
78
- - `getAppUserId()`: Retrieves the Slack app user ID.
79
- - `sendNotification(channel, content)`: Core method to send messages.
80
- - Specialized notification methods for different use cases, e.g., `sendNewReportsNotification`, `sendDailyDataSyncPerformanceNotification`, etc.
81
-
82
- ### Example Snippet
83
-
84
- ```ts
85
- async sendNotification(channel: string, content: string): Promise<void> {
86
- const isMember = await this.isAppMemberOfChannel(channel);
87
- if (!isMember) {
88
- await this.joinChannel(channel);
89
- }
90
-
91
- try {
92
- await this.webClient.chat.postMessage({
93
- channel,
94
- text: content,
95
- });
96
- } catch (error) {
97
- throw new GenieException(`Failed to send a message`, { error, channel });
98
- }
99
- }
100
- ```
101
-
102
- ## API and Interfaces
103
-
104
- The `SlackService` exposes primarily asynchronous methods designed to send notifications:
105
-
106
- | Method | Parameters | Description |
107
- |-----------------------------------------|--------------------------------------------------------|-------------------------------------------------------------------|
108
- | `sendNotification(channel, content)` | `channel: string`, `content: string` | Sends a raw text notification to specified Slack channel. |
109
- | `sendNewReportsNotification({ userEmail, content })` | `{ userEmail: string; content: string }` | Sends a new user report request notification. |
110
- | `sendDateRangeFeatureSuggestionNotification({ team, userName, userSurname, userEmail, suggestion })` | Issues a date range feature suggestion notification. |
111
- | `sendDailyDataSyncPerformanceNotification(summary: string)` | Summary string of data sync duration/performance. |
112
- | `sendProductBundlesImportRequestNotification({ team, user, description })` | Notification for team-requested product bundle imports. |
113
- | `sendOnboardingProductBundlesNotification({ team, user, products })` | Notifies about onboarding with bundles. |
114
- | `sendImportPORequestNotification({ team, user, fileUrls })` | Purchase order import requests with associated files. |
115
- | `sendSalesSyncHealthCheckNotification(summary)` | Health check results summary for team sales sync accuracy. |
116
-
117
- ### Failure Modes
118
-
119
- - Throws `GenieException` wrapping Slack Web API errors with channel context.
120
- - Throws an error if fetching app user ID fails during membership checks.
121
-
122
- ### Authentication & Authorization
123
-
124
- - Slack app token is injected from environment via `ConfigService` (`SLACK_APP_TOKEN`).
125
- - This token scopes API access and membership checks.
126
-
127
- ### Sample Notification Template
128
-
129
- New User Report Example:
130
-
131
- ```
132
- *New User Report request*
133
-
134
- User Email: <user@example.com>
135
-
136
- Content: Example report content
137
- ```
138
-
139
- ## Environment & Configuration
140
-
141
- ### Required Environment Variables
142
-
143
- | Variable | Description |
144
- |-----------------------------------|------------------------------------------------|
145
- | `SLACK_APP_TOKEN` | OAuth token for Slack Web API authentication. |
146
- | `SlACK_APP_USER_REQUESTS_CHANNEL_ID` | Slack channel ID for user requests notifications. |
147
- | `SLACK_APP_SYSTEM_ALERTS_CHANNEL_ID` | Slack channel ID for system alert notifications. |
148
- | `API_ENV` | Current environment label (e.g., production). |
149
-
150
- ### Notes
151
-
152
- - Channel IDs are stored as config keys and injected at runtime.
153
- - Slack app token must have necessary permission scopes for reading channel info, joining channels, and posting messages.
154
-
155
- ## Testing, Monitoring, and Deployment
156
-
157
- - Error handling throws domain exceptions that are logged by the system's centralized logger.
158
- - No explicit unit testing or mocks shown here, but methods are async and can be unit tested by mocking `WebClient`.
159
- - The structured exception handling facilitates diagnosing Slack API interaction failures.
160
-
161
- ## Troubleshooting & Known Issues
162
-
163
- - If messaging fails due to channel membership, the service attempts to join the channel automatically.
164
- - Errors when joining or messaging channels raise `GenieException` with detailed error data.
165
-
166
- ## Mermaid Diagram
167
-
168
- ```mermaid
169
- flowchart TD
170
- subgraph Backend API
171
- SLACK["SlackService"]:::service
172
- CONF["ConfigService"]:::service
173
- GENIEEXC["GenieException"]:::exception
174
- end
175
-
176
- subgraph External Services
177
- SLACKAPI["Slack Web API"]:::external
178
- end
179
-
180
- CONF -->|provides tokens and channel IDs| SLACK
181
- SLACK -->|uses| SLACKAPI
182
- SLACK -->|raises errors via| GENIEEXC
183
-
184
- classDef service fill:#e3f2fd,stroke:#2196f3,stroke-width:2px,color:#0d47a1;
185
- classDef external fill:#ede7f6,stroke:#5e35b1,stroke-width:2px,color:#311b92;
186
- classDef exception fill:#ffebee,stroke:#f44336,stroke-width:2px,color:#b71c1c;
187
-
188
- click SLACK "apps/api/src/slack/services/slack.service.ts"
189
- click CONF "apps/api/src/config"