@axova/shared 1.0.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.
- package/CONFIGURATION_GUIDE.md +1 -0
- package/README.md +384 -0
- package/SCHEMA_ORGANIZATION.md +209 -0
- package/dist/configs/index.d.ts +85 -0
- package/dist/configs/index.js +555 -0
- package/dist/events/kafka.d.ts +40 -0
- package/dist/events/kafka.js +311 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +41 -0
- package/dist/interfaces/customer-events.d.ts +85 -0
- package/dist/interfaces/customer-events.js +2 -0
- package/dist/interfaces/inventory-events.d.ts +453 -0
- package/dist/interfaces/inventory-events.js +3 -0
- package/dist/interfaces/inventory-types.d.ts +894 -0
- package/dist/interfaces/inventory-types.js +3 -0
- package/dist/interfaces/order-events.d.ts +320 -0
- package/dist/interfaces/order-events.js +3 -0
- package/dist/lib/auditLogger.d.ts +162 -0
- package/dist/lib/auditLogger.js +626 -0
- package/dist/lib/authOrganization.d.ts +24 -0
- package/dist/lib/authOrganization.js +110 -0
- package/dist/lib/db.d.ts +6 -0
- package/dist/lib/db.js +88 -0
- package/dist/middleware/serviceAuth.d.ts +60 -0
- package/dist/middleware/serviceAuth.js +272 -0
- package/dist/middleware/storeOwnership.d.ts +15 -0
- package/dist/middleware/storeOwnership.js +156 -0
- package/dist/middleware/storeValidationMiddleware.d.ts +44 -0
- package/dist/middleware/storeValidationMiddleware.js +180 -0
- package/dist/middleware/userAuth.d.ts +27 -0
- package/dist/middleware/userAuth.js +218 -0
- package/dist/schemas/admin/admin-schema.d.ts +741 -0
- package/dist/schemas/admin/admin-schema.js +111 -0
- package/dist/schemas/ai-moderation/ai-moderation-schema.d.ts +648 -0
- package/dist/schemas/ai-moderation/ai-moderation-schema.js +88 -0
- package/dist/schemas/common/common-schemas.d.ts +436 -0
- package/dist/schemas/common/common-schemas.js +94 -0
- package/dist/schemas/compliance/compliance-schema.d.ts +3388 -0
- package/dist/schemas/compliance/compliance-schema.js +472 -0
- package/dist/schemas/compliance/kyc-schema.d.ts +2642 -0
- package/dist/schemas/compliance/kyc-schema.js +361 -0
- package/dist/schemas/customer/customer-schema.d.ts +2727 -0
- package/dist/schemas/customer/customer-schema.js +399 -0
- package/dist/schemas/index.d.ts +27 -0
- package/dist/schemas/index.js +138 -0
- package/dist/schemas/inventory/inventory-tables.d.ts +9476 -0
- package/dist/schemas/inventory/inventory-tables.js +1470 -0
- package/dist/schemas/inventory/lot-tables.d.ts +3281 -0
- package/dist/schemas/inventory/lot-tables.js +608 -0
- package/dist/schemas/order/order-schema.d.ts +5825 -0
- package/dist/schemas/order/order-schema.js +954 -0
- package/dist/schemas/product/discount-relations.d.ts +15 -0
- package/dist/schemas/product/discount-relations.js +34 -0
- package/dist/schemas/product/discount-schema.d.ts +1975 -0
- package/dist/schemas/product/discount-schema.js +297 -0
- package/dist/schemas/product/product-relations.d.ts +41 -0
- package/dist/schemas/product/product-relations.js +133 -0
- package/dist/schemas/product/product-schema.d.ts +4544 -0
- package/dist/schemas/product/product-schema.js +671 -0
- package/dist/schemas/store/store-audit-schema.d.ts +4135 -0
- package/dist/schemas/store/store-audit-schema.js +556 -0
- package/dist/schemas/store/store-schema.d.ts +3100 -0
- package/dist/schemas/store/store-schema.js +381 -0
- package/dist/schemas/store/store-settings-schema.d.ts +665 -0
- package/dist/schemas/store/store-settings-schema.js +141 -0
- package/dist/schemas/types.d.ts +50 -0
- package/dist/schemas/types.js +3 -0
- package/dist/types/events.d.ts +2396 -0
- package/dist/types/events.js +505 -0
- package/dist/utils/errorHandler.d.ts +12 -0
- package/dist/utils/errorHandler.js +36 -0
- package/dist/utils/subdomain.d.ts +6 -0
- package/dist/utils/subdomain.js +20 -0
- package/nul +8 -0
- package/package.json +43 -0
- package/src/configs/index.ts +654 -0
- package/src/events/kafka.ts +429 -0
- package/src/index.ts +26 -0
- package/src/interfaces/customer-events.ts +106 -0
- package/src/interfaces/inventory-events.ts +545 -0
- package/src/interfaces/inventory-types.ts +1004 -0
- package/src/interfaces/order-events.ts +381 -0
- package/src/lib/auditLogger.ts +1117 -0
- package/src/lib/authOrganization.ts +153 -0
- package/src/lib/db.ts +64 -0
- package/src/middleware/serviceAuth.ts +328 -0
- package/src/middleware/storeOwnership.ts +199 -0
- package/src/middleware/storeValidationMiddleware.ts +247 -0
- package/src/middleware/userAuth.ts +248 -0
- package/src/schemas/admin/admin-schema.ts +208 -0
- package/src/schemas/ai-moderation/ai-moderation-schema.ts +180 -0
- package/src/schemas/common/common-schemas.ts +108 -0
- package/src/schemas/compliance/compliance-schema.ts +927 -0
- package/src/schemas/compliance/kyc-schema.ts +649 -0
- package/src/schemas/customer/customer-schema.ts +576 -0
- package/src/schemas/index.ts +189 -0
- package/src/schemas/inventory/inventory-tables.ts +1927 -0
- package/src/schemas/inventory/lot-tables.ts +799 -0
- package/src/schemas/order/order-schema.ts +1400 -0
- package/src/schemas/product/discount-relations.ts +44 -0
- package/src/schemas/product/discount-schema.ts +464 -0
- package/src/schemas/product/product-relations.ts +187 -0
- package/src/schemas/product/product-schema.ts +955 -0
- package/src/schemas/store/ethiopian_business_api.md.resolved +212 -0
- package/src/schemas/store/store-audit-schema.ts +1257 -0
- package/src/schemas/store/store-schema.ts +661 -0
- package/src/schemas/store/store-settings-schema.ts +231 -0
- package/src/schemas/types.ts +67 -0
- package/src/types/events.ts +646 -0
- package/src/utils/errorHandler.ts +44 -0
- package/src/utils/subdomain.ts +19 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
package/README.md
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
# 🚀 Axova Shared Package
|
|
2
|
+
|
|
3
|
+
A comprehensive shared utilities and configuration package for the Axova platform, providing centralized services, configurations, and utilities for all microservices.
|
|
4
|
+
|
|
5
|
+
## 📋 Table of Contents
|
|
6
|
+
|
|
7
|
+
- [Overview](#overview)
|
|
8
|
+
- [Installation](#installation)
|
|
9
|
+
- [Service Profiles](#service-profiles)
|
|
10
|
+
- [Features](#features)
|
|
11
|
+
- [Configuration](#configuration)
|
|
12
|
+
- [Usage](#usage)
|
|
13
|
+
- [API Reference](#api-reference)
|
|
14
|
+
- [Migration Guide](#migration-guide)
|
|
15
|
+
|
|
16
|
+
## 🌟 Overview
|
|
17
|
+
|
|
18
|
+
The Axova Shared Package provides:
|
|
19
|
+
|
|
20
|
+
- **Service-specific configuration profiles** for all microservices
|
|
21
|
+
- **Centralized database management** with connection pooling
|
|
22
|
+
- **Kafka event streaming** with type-safe event handling
|
|
23
|
+
- **Comprehensive audit logging** with sensitive data masking
|
|
24
|
+
- **Service authentication** with JWT and internal service communication
|
|
25
|
+
- **Type-safe schemas** and interfaces for all services
|
|
26
|
+
- **Utility functions** for common operations
|
|
27
|
+
|
|
28
|
+
## 📦 Installation
|
|
29
|
+
|
|
30
|
+
```bash
|
|
31
|
+
npm install @axova/shared
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## 🎯 Service Profiles
|
|
35
|
+
|
|
36
|
+
The package includes pre-configured profiles for all Axova services:
|
|
37
|
+
|
|
38
|
+
| Service | Profile | Default Port | Description |
|
|
39
|
+
|---------|---------|--------------|-------------|
|
|
40
|
+
| **Store Service** | `STORE_SERVICE_PROFILE` | 3001 | Store management, customization, and content |
|
|
41
|
+
| **Compliance Service** | `COMPLIANCE_SERVICE_PROFILE` | 3002 | Compliance monitoring and violation management |
|
|
42
|
+
| **Product Service** | `PRODUCT_SERVICE_PROFILE` | 3003 | Product catalog and variant management |
|
|
43
|
+
| **Admin API Service** | `ADMIN_API_SERVICE_PROFILE` | 3004 | Administrative operations and user management |
|
|
44
|
+
| **Inventory Core Service** | `INVENTORY_SERVICE_PROFILE` | 3005 | Inventory tracking and warehouse management |
|
|
45
|
+
|
|
46
|
+
## ✨ Features
|
|
47
|
+
|
|
48
|
+
### 🔧 Configuration Management
|
|
49
|
+
- **Environment-based configuration** with sensible defaults
|
|
50
|
+
- **Service-specific profiles** with customizable features
|
|
51
|
+
- **Validation and error handling** for configurations
|
|
52
|
+
- **Hot-reloading support** for development
|
|
53
|
+
|
|
54
|
+
### 🎭 Audit Logging
|
|
55
|
+
- **Comprehensive audit trails** for all service operations
|
|
56
|
+
- **Sensitive data masking** for security compliance
|
|
57
|
+
- **Buffered logging** with configurable flush intervals
|
|
58
|
+
- **Risk level assessment** and categorization
|
|
59
|
+
- **Real-time event streaming** via Kafka
|
|
60
|
+
|
|
61
|
+
### 🚀 Kafka Integration
|
|
62
|
+
- **Type-safe event handling** with strong typing
|
|
63
|
+
- **Automatic producer/consumer management**
|
|
64
|
+
- **Dead letter queue support** for failed messages
|
|
65
|
+
- **Partition-aware processing** for scalability
|
|
66
|
+
|
|
67
|
+
### 🔐 Security & Authentication
|
|
68
|
+
- **Service-to-service authentication** with JWT
|
|
69
|
+
- **API key management** and validation
|
|
70
|
+
- **Role-based access control** (RBAC)
|
|
71
|
+
- **Request context tracking** for audit trails
|
|
72
|
+
|
|
73
|
+
## ⚙️ Configuration
|
|
74
|
+
|
|
75
|
+
### Basic Service Initialization
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import { initializeServiceWithProfile } from '@axova/shared';
|
|
79
|
+
|
|
80
|
+
// Initialize service with its profile
|
|
81
|
+
const serviceConfig = await initializeServiceWithProfile('store-service');
|
|
82
|
+
|
|
83
|
+
// Access configuration
|
|
84
|
+
console.log('Service Port:', serviceConfig.profile.base.port);
|
|
85
|
+
console.log('Features:', serviceConfig.profile.features);
|
|
86
|
+
|
|
87
|
+
// Check feature flags
|
|
88
|
+
if (serviceConfig.isFeatureEnabled('auditLogging')) {
|
|
89
|
+
console.log('Audit logging is enabled');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Environment checks
|
|
93
|
+
if (serviceConfig.isDevelopment()) {
|
|
94
|
+
console.log('Running in development mode');
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Environment Variables
|
|
99
|
+
|
|
100
|
+
Each service supports comprehensive environment-based configuration:
|
|
101
|
+
|
|
102
|
+
```env
|
|
103
|
+
# Base Configuration
|
|
104
|
+
PORT=3001
|
|
105
|
+
HOST=0.0.0.0
|
|
106
|
+
NODE_ENV=production
|
|
107
|
+
|
|
108
|
+
# Database Configuration
|
|
109
|
+
DATABASE_URL=postgresql://user:pass@localhost:5432/axova_db
|
|
110
|
+
POSTGRES_HOST=localhost
|
|
111
|
+
POSTGRES_PORT=5432
|
|
112
|
+
POSTGRES_USER=axova_user
|
|
113
|
+
POSTGRES_PASSWORD=secure_password
|
|
114
|
+
POSTGRES_DB=axova_store_db
|
|
115
|
+
DB_SSL=true
|
|
116
|
+
DB_POOL_SIZE=15
|
|
117
|
+
|
|
118
|
+
# Kafka Configuration
|
|
119
|
+
KAFKA_ENABLED=true
|
|
120
|
+
KAFKA_BROKERS=localhost:9092,localhost:9093
|
|
121
|
+
KAFKA_CLIENT_ID=store-service
|
|
122
|
+
KAFKA_GROUP_ID=store-service-group
|
|
123
|
+
KAFKA_SSL=false
|
|
124
|
+
KAFKA_USERNAME=
|
|
125
|
+
KAFKA_PASSWORD=
|
|
126
|
+
|
|
127
|
+
# Redis Configuration (if applicable)
|
|
128
|
+
REDIS_HOST=localhost
|
|
129
|
+
REDIS_PORT=6379
|
|
130
|
+
REDIS_PASSWORD=redis_password
|
|
131
|
+
REDIS_DB=0
|
|
132
|
+
REDIS_TTL=3600
|
|
133
|
+
|
|
134
|
+
# Audit Configuration
|
|
135
|
+
AUDIT_ENABLED=true
|
|
136
|
+
AUDIT_LEVEL=comprehensive
|
|
137
|
+
AUDIT_BUFFER_SIZE=100
|
|
138
|
+
AUDIT_FLUSH_INTERVAL=5000
|
|
139
|
+
AUDIT_MASK_SENSITIVE=true
|
|
140
|
+
|
|
141
|
+
# Service Authentication
|
|
142
|
+
INTERNAL_SECRET=your_internal_secret
|
|
143
|
+
SERVICE_TOKEN_EXPIRY=1h
|
|
144
|
+
|
|
145
|
+
# CORS Configuration
|
|
146
|
+
CORS_ORIGINS=http://localhost:3000,https://app.axova.com
|
|
147
|
+
RATE_LIMIT_MAX=100
|
|
148
|
+
RATE_LIMIT_WINDOW=1 minute
|
|
149
|
+
|
|
150
|
+
# Feature Flags
|
|
151
|
+
ENABLE_REAL_TIME_SYNC=true
|
|
152
|
+
ENABLE_AUDIT_LOGGING=true
|
|
153
|
+
ENABLE_ADVANCED_ANALYTICS=false
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## 🚀 Usage
|
|
157
|
+
|
|
158
|
+
### 1. Service Initialization
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
import {
|
|
162
|
+
initializeServiceWithProfile,
|
|
163
|
+
createKafkaInstance,
|
|
164
|
+
createServiceAuthenticator,
|
|
165
|
+
createAuditLogger,
|
|
166
|
+
db
|
|
167
|
+
} from '@axova/shared';
|
|
168
|
+
|
|
169
|
+
async function initializeService() {
|
|
170
|
+
// Get service configuration
|
|
171
|
+
const config = await initializeServiceWithProfile('store-service');
|
|
172
|
+
|
|
173
|
+
// Initialize Kafka
|
|
174
|
+
const kafka = createKafkaInstance(config.kafkaConfig);
|
|
175
|
+
await kafka.initializeProducer();
|
|
176
|
+
|
|
177
|
+
// Initialize service authentication
|
|
178
|
+
const serviceAuth = createServiceAuthenticator(config.serviceAuthConfig);
|
|
179
|
+
|
|
180
|
+
// Initialize audit logger
|
|
181
|
+
const auditLogger = createAuditLogger({
|
|
182
|
+
serviceName: config.profile.base.serviceName,
|
|
183
|
+
bufferSize: config.profile.audit.bufferSize,
|
|
184
|
+
flushInterval: config.profile.audit.flushInterval,
|
|
185
|
+
sensitiveFieldMasking: config.profile.audit.sensitiveFieldMasking,
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
return { config, kafka, serviceAuth, auditLogger, db };
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
### 2. Event Publishing
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import { createKafkaInstance, KAFKA_TOPICS } from '@axova/shared';
|
|
196
|
+
|
|
197
|
+
const kafka = createKafkaInstance(kafkaConfig);
|
|
198
|
+
|
|
199
|
+
// Publish a store creation event
|
|
200
|
+
await kafka.publishEvent(KAFKA_TOPICS.STORE_CREATED, {
|
|
201
|
+
id: 'event-id',
|
|
202
|
+
type: 'store.created',
|
|
203
|
+
source: 'store-service',
|
|
204
|
+
version: '1.0',
|
|
205
|
+
timestamp: new Date().toISOString(),
|
|
206
|
+
data: {
|
|
207
|
+
storeId: 'store-123',
|
|
208
|
+
userId: 'user-456',
|
|
209
|
+
storeName: 'My Amazing Store',
|
|
210
|
+
domain: 'amazing-store.myaxova.com'
|
|
211
|
+
}
|
|
212
|
+
});
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### 3. Audit Logging
|
|
216
|
+
|
|
217
|
+
```typescript
|
|
218
|
+
import { createAuditLogger } from '@axova/shared';
|
|
219
|
+
|
|
220
|
+
const auditLogger = createAuditLogger({
|
|
221
|
+
serviceName: 'store-service',
|
|
222
|
+
bufferSize: 100,
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
// Log a store creation
|
|
226
|
+
const auditEntry = auditLogger.log({
|
|
227
|
+
eventType: 'CREATE',
|
|
228
|
+
eventCategory: 'DATA_ACTION',
|
|
229
|
+
action: 'store_create',
|
|
230
|
+
resource: 'store',
|
|
231
|
+
resourceId: 'store-123',
|
|
232
|
+
performedBy: 'user-456',
|
|
233
|
+
performedByType: 'USER',
|
|
234
|
+
changes: {
|
|
235
|
+
after: { name: 'My Store', domain: 'mystore.com' }
|
|
236
|
+
},
|
|
237
|
+
riskLevel: 'LOW',
|
|
238
|
+
success: true
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// Quick action builders
|
|
242
|
+
auditLogger.quick.dataCreate('store', 'store-123', 'user-456', storeData);
|
|
243
|
+
auditLogger.quick.dataUpdate('store', 'store-123', 'user-456', changes);
|
|
244
|
+
auditLogger.quick.permissionChange('user-789', 'admin-123', roleChanges);
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
### 4. Database Operations
|
|
248
|
+
|
|
249
|
+
```typescript
|
|
250
|
+
import { db, stores, storeBlogs } from '@axova/shared';
|
|
251
|
+
import { eq } from 'drizzle-orm';
|
|
252
|
+
|
|
253
|
+
// Query stores
|
|
254
|
+
const userStores = await db
|
|
255
|
+
.select()
|
|
256
|
+
.from(stores)
|
|
257
|
+
.where(eq(stores.userId, 'user-123'));
|
|
258
|
+
|
|
259
|
+
// Create a new store blog post
|
|
260
|
+
const newBlog = await db
|
|
261
|
+
.insert(storeBlogs)
|
|
262
|
+
.values({
|
|
263
|
+
storeId: 'store-123',
|
|
264
|
+
title: 'My First Blog Post',
|
|
265
|
+
content: 'Hello world!',
|
|
266
|
+
published: true
|
|
267
|
+
})
|
|
268
|
+
.returning();
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### 5. Service Authentication
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
import { createServiceAuthenticator } from '@axova/shared';
|
|
275
|
+
|
|
276
|
+
const serviceAuth = createServiceAuthenticator({
|
|
277
|
+
internalSecret: process.env.INTERNAL_SECRET!,
|
|
278
|
+
tokenExpiry: '1h'
|
|
279
|
+
});
|
|
280
|
+
|
|
281
|
+
// Generate service token
|
|
282
|
+
const token = serviceAuth.generateServiceToken('store-service', {
|
|
283
|
+
permissions: ['read:stores', 'write:stores']
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
// Verify service token
|
|
287
|
+
const decoded = serviceAuth.verifyServiceToken(token);
|
|
288
|
+
console.log('Service:', decoded.service);
|
|
289
|
+
console.log('Permissions:', decoded.permissions);
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
## 📚 API Reference
|
|
293
|
+
|
|
294
|
+
### Configuration Profiles
|
|
295
|
+
|
|
296
|
+
#### `getServiceProfile(serviceName: ServiceName): ServiceProfile`
|
|
297
|
+
Get the configuration profile for a specific service.
|
|
298
|
+
|
|
299
|
+
#### `initializeServiceWithProfile(serviceName: ServiceName)`
|
|
300
|
+
Initialize a service with its profile and return configured instances.
|
|
301
|
+
|
|
302
|
+
#### `validateServiceConfig(profile: ServiceProfile)`
|
|
303
|
+
Validate a service configuration and return validation results.
|
|
304
|
+
|
|
305
|
+
### Event Management
|
|
306
|
+
|
|
307
|
+
#### `createKafkaInstance(config: AxovaKafkaConfig): AxovaKafka`
|
|
308
|
+
Create a Kafka instance with the provided configuration.
|
|
309
|
+
|
|
310
|
+
#### `kafka.publishEvent(topic: KafkaTopic, event: AxovaEvent)`
|
|
311
|
+
Publish an event to a specific Kafka topic.
|
|
312
|
+
|
|
313
|
+
#### `kafka.onEvent<T>(eventType: string, handler: EventHandler<T>)`
|
|
314
|
+
Register an event handler for a specific event type.
|
|
315
|
+
|
|
316
|
+
### Audit Logging
|
|
317
|
+
|
|
318
|
+
#### `createAuditLogger(config: AuditLoggerConfig): AuditLogger`
|
|
319
|
+
Create an audit logger instance with the provided configuration.
|
|
320
|
+
|
|
321
|
+
#### `auditLogger.log(entry: Partial<AuditLogEntry>): string`
|
|
322
|
+
Log an audit entry and return the audit ID.
|
|
323
|
+
|
|
324
|
+
#### Quick Action Builders
|
|
325
|
+
- `auditLogger.quick.dataCreate(resource, resourceId, userId, data)`
|
|
326
|
+
- `auditLogger.quick.dataUpdate(resource, resourceId, userId, changes)`
|
|
327
|
+
- `auditLogger.quick.dataDelete(resource, resourceId, userId)`
|
|
328
|
+
- `auditLogger.quick.permissionChange(targetUserId, changedBy, changes)`
|
|
329
|
+
|
|
330
|
+
### Database
|
|
331
|
+
|
|
332
|
+
#### `db: NodePgDatabase`
|
|
333
|
+
Drizzle ORM database instance with connection pooling.
|
|
334
|
+
|
|
335
|
+
#### Schema Exports
|
|
336
|
+
All database schemas are available for import:
|
|
337
|
+
- Store schemas: `stores`, `storeBlogs`, `storeContacts`, etc.
|
|
338
|
+
- Product schemas: `products`, `variants`, `collections`, etc.
|
|
339
|
+
- Inventory schemas: `inventory`, `warehouses`, `posLocations`, etc.
|
|
340
|
+
- Compliance schemas: `complianceViolations`, `appeals`, etc.
|
|
341
|
+
|
|
342
|
+
## 🔄 Migration Guide
|
|
343
|
+
|
|
344
|
+
### From Previous Version
|
|
345
|
+
|
|
346
|
+
If you're migrating from a previous version of the shared package:
|
|
347
|
+
|
|
348
|
+
1. **Update imports:**
|
|
349
|
+
```typescript
|
|
350
|
+
// Old
|
|
351
|
+
import { getKafkaConfigFromEnv } from '@axova/shared';
|
|
352
|
+
|
|
353
|
+
// New
|
|
354
|
+
import { initializeServiceWithProfile } from '@axova/shared';
|
|
355
|
+
const config = await initializeServiceWithProfile('your-service');
|
|
356
|
+
```
|
|
357
|
+
|
|
358
|
+
2. **Use service profiles:**
|
|
359
|
+
```typescript
|
|
360
|
+
// Old - manual configuration
|
|
361
|
+
const kafkaConfig = getKafkaConfigFromEnv();
|
|
362
|
+
|
|
363
|
+
// New - service profile
|
|
364
|
+
const { kafkaConfig, profile } = await initializeServiceWithProfile('store-service');
|
|
365
|
+
```
|
|
366
|
+
|
|
367
|
+
3. **Update environment variables:**
|
|
368
|
+
Follow the new environment variable naming conventions shown above.
|
|
369
|
+
|
|
370
|
+
## 🤝 Contributing
|
|
371
|
+
|
|
372
|
+
1. Make changes to the shared package
|
|
373
|
+
2. Run `npm run build` to compile TypeScript
|
|
374
|
+
3. Test changes in dependent services
|
|
375
|
+
4. Update documentation as needed
|
|
376
|
+
5. Submit pull request with detailed description
|
|
377
|
+
|
|
378
|
+
## 📄 License
|
|
379
|
+
|
|
380
|
+
MIT License - see LICENSE file for details.
|
|
381
|
+
|
|
382
|
+
---
|
|
383
|
+
|
|
384
|
+
**Built with ❤️ by the Axova Team**
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
# Axova Fusion - Database Schema Organization
|
|
2
|
+
|
|
3
|
+
## Overview
|
|
4
|
+
|
|
5
|
+
The database schemas have been organized by service domain within the shared package for better maintainability, reusability, and efficiency. Each service has its own dedicated schema folder with comprehensive table definitions, relationships, and performance optimizations.
|
|
6
|
+
|
|
7
|
+
## Schema Structure
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
packages/shared/src/schemas/
|
|
11
|
+
├── store/
|
|
12
|
+
│ └── store-schema.ts # Core store, business details, contacts, social, blogs
|
|
13
|
+
├── compliance/
|
|
14
|
+
│ └── compliance-schema.ts # Compliance status, violations, actions, policies, appeals
|
|
15
|
+
├── audit/
|
|
16
|
+
│ └── audit-schema.ts # Immutable audit logs, aggregations, trails
|
|
17
|
+
├── notification/
|
|
18
|
+
│ └── notification-schema.ts # Templates, notifications, preferences, events
|
|
19
|
+
├── ai-moderation/
|
|
20
|
+
│ └── ai-moderation-schema.ts # Content scans, moderation rules
|
|
21
|
+
├── admin/
|
|
22
|
+
│ └── admin-schema.ts # Admin users, actions, review queues
|
|
23
|
+
└── index.ts # Centralized exports
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Service Schema Mapping
|
|
27
|
+
|
|
28
|
+
| Service | Schema Location | Primary Tables | Purpose |
|
|
29
|
+
|---------|-----------------|----------------|---------|
|
|
30
|
+
| **Store Service** | `store/store-schema.ts` | stores, storeBusinessDetails, storeContacts, storeSocialProfiles, storeBlogs | Core store metadata and lifecycle management |
|
|
31
|
+
| **Compliance Service** | `compliance/compliance-schema.ts` | storeCompliance, complianceViolations, complianceActions, storePolicies, appeals | Verification, violations, bans, policies, appeals |
|
|
32
|
+
| **Audit Service** | `audit/audit-schema.ts` | auditLogs, auditLogAggregations, auditTrails | Immutable action logging and forensic trails |
|
|
33
|
+
| **Notification Service** | `notification/notification-schema.ts` | notificationTemplates, notifications, notificationPreferences, notificationEvents | Multi-channel messaging and delivery tracking |
|
|
34
|
+
| **AI Moderation Service** | `ai-moderation/ai-moderation-schema.ts` | contentScans, moderationRules | Content scanning and violation detection |
|
|
35
|
+
| **Admin API Service** | `admin/admin-schema.ts` | adminUsers, adminActions, reviewQueues | Internal admin operations and review workflows |
|
|
36
|
+
|
|
37
|
+
## Enhanced Features
|
|
38
|
+
|
|
39
|
+
### 1. Performance Optimizations
|
|
40
|
+
- **Comprehensive Indexing**: Strategic indexes for all common query patterns
|
|
41
|
+
- **Composite Indexes**: Multi-column indexes for complex filtering
|
|
42
|
+
- **Partial Indexes**: Conditional indexes for specific scenarios
|
|
43
|
+
- **Query-Specific Indexes**: Tailored for business logic patterns
|
|
44
|
+
|
|
45
|
+
### 2. Data Integrity
|
|
46
|
+
- **Foreign Key Constraints**: Proper referential integrity
|
|
47
|
+
- **Unique Constraints**: Prevent data duplication
|
|
48
|
+
- **Check Constraints**: Business rule enforcement
|
|
49
|
+
- **Cascade Rules**: Proper cleanup on deletions
|
|
50
|
+
|
|
51
|
+
### 3. Scalability Features
|
|
52
|
+
- **Partition-Ready**: Designed for future partitioning
|
|
53
|
+
- **Aggregation Tables**: Pre-computed metrics for performance
|
|
54
|
+
- **Immutable Design**: Append-only patterns for audit tables
|
|
55
|
+
- **Efficient Storage**: Optimized data types and JSONB usage
|
|
56
|
+
|
|
57
|
+
### 4. Business Intelligence
|
|
58
|
+
- **Rich Metadata**: Comprehensive context tracking
|
|
59
|
+
- **Analytics-Ready**: Built-in metrics and KPIs
|
|
60
|
+
- **Reporting Indexes**: Optimized for business intelligence queries
|
|
61
|
+
- **Time-Series Data**: Proper temporal data handling
|
|
62
|
+
|
|
63
|
+
## Key Schema Enhancements
|
|
64
|
+
|
|
65
|
+
### Store Schema Enhancements
|
|
66
|
+
- **Enhanced Business Details**: Legal structures, verification levels, industry classification
|
|
67
|
+
- **Advanced Contact Management**: Business hours, communication preferences, emergency contacts
|
|
68
|
+
- **Social Media Strategy**: Platform analytics, posting schedules, engagement tracking
|
|
69
|
+
- **Content Management**: SEO metadata, localization, engagement metrics
|
|
70
|
+
|
|
71
|
+
### Compliance Schema Enhancements
|
|
72
|
+
- **Multi-Level Compliance**: Different verification tiers and compliance scores
|
|
73
|
+
- **Advanced Violation Tracking**: Detection methods, confidence scores, impact assessment
|
|
74
|
+
- **Comprehensive Actions**: Approval workflows, effectiveness tracking, reversal support
|
|
75
|
+
- **Policy Management**: Versioning, approval workflows, compliance standards tracking
|
|
76
|
+
- **Appeals System**: Multi-level review, SLA tracking, communication history
|
|
77
|
+
|
|
78
|
+
### Audit Schema Enhancements
|
|
79
|
+
- **Immutable Design**: Append-only with integrity verification
|
|
80
|
+
- **Rich Context**: Geographic, device, and business context
|
|
81
|
+
- **Performance Metrics**: Duration, size, and efficiency tracking
|
|
82
|
+
- **Risk Assessment**: Security and compliance impact scoring
|
|
83
|
+
- **Aggregation Support**: Pre-computed metrics for performance
|
|
84
|
+
|
|
85
|
+
### Notification Schema Enhancements
|
|
86
|
+
- **Multi-Channel Templates**: Email, SMS, push, in-app support
|
|
87
|
+
- **Advanced Personalization**: Variable substitution, conditional logic
|
|
88
|
+
- **Delivery Tracking**: Comprehensive status and event tracking
|
|
89
|
+
- **Preference Management**: Granular control over notification preferences
|
|
90
|
+
- **Analytics Integration**: Open, click, and engagement tracking
|
|
91
|
+
|
|
92
|
+
### AI Moderation Enhancements
|
|
93
|
+
- **Provider Agnostic**: Support for multiple AI moderation services
|
|
94
|
+
- **Custom Rules**: Flexible rule engine for business-specific requirements
|
|
95
|
+
- **Confidence Scoring**: Detailed confidence and category breakdowns
|
|
96
|
+
- **Deduplication**: Content hashing for efficient processing
|
|
97
|
+
- **Cost Tracking**: API usage and cost monitoring
|
|
98
|
+
|
|
99
|
+
### Admin Schema Enhancements
|
|
100
|
+
- **Role-Based Access**: Granular permission system
|
|
101
|
+
- **Action Tracking**: Comprehensive admin action logging
|
|
102
|
+
- **Review Workflows**: Queue management with SLA tracking
|
|
103
|
+
- **Approval Processes**: Multi-level approval workflows
|
|
104
|
+
- **Performance Monitoring**: Efficiency and workload tracking
|
|
105
|
+
|
|
106
|
+
## Database Configuration
|
|
107
|
+
|
|
108
|
+
Each service has its own Drizzle configuration pointing to the appropriate schema:
|
|
109
|
+
|
|
110
|
+
```typescript
|
|
111
|
+
// apps/{service}/drizzle.config.ts
|
|
112
|
+
export default defineConfig({
|
|
113
|
+
schema: '../../packages/shared/src/schemas/{service}/{service}-schema.ts',
|
|
114
|
+
out: './drizzle',
|
|
115
|
+
dialect: 'postgresql',
|
|
116
|
+
dbCredentials: {
|
|
117
|
+
url: process.env.DATABASE_URL!,
|
|
118
|
+
},
|
|
119
|
+
});
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
## Usage Examples
|
|
123
|
+
|
|
124
|
+
### Importing Schemas
|
|
125
|
+
```typescript
|
|
126
|
+
// Import all schemas
|
|
127
|
+
import * from '@axova/shared/schemas';
|
|
128
|
+
|
|
129
|
+
// Import specific service schemas
|
|
130
|
+
import { stores, storeBusinessDetails } from '@axova/shared/schemas/store';
|
|
131
|
+
import { storeCompliance, complianceViolations } from '@axova/shared/schemas/compliance';
|
|
132
|
+
import { auditLogs } from '@axova/shared/schemas/audit';
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Service Integration
|
|
136
|
+
```typescript
|
|
137
|
+
// In compliance service
|
|
138
|
+
import { db, storeCompliance, complianceViolations } from '@axova/shared';
|
|
139
|
+
|
|
140
|
+
const createComplianceRecord = async (storeId: string) => {
|
|
141
|
+
return await db.insert(storeCompliance).values({
|
|
142
|
+
storeId,
|
|
143
|
+
isVerified: false,
|
|
144
|
+
complianceScore: 100,
|
|
145
|
+
riskLevel: 'LOW'
|
|
146
|
+
});
|
|
147
|
+
};
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
## Migration Strategy
|
|
151
|
+
|
|
152
|
+
1. **Backwards Compatibility**: Legacy exports maintained in `models/store-schema.ts`
|
|
153
|
+
2. **Gradual Migration**: Services can migrate to new schemas incrementally
|
|
154
|
+
3. **Consistent Interface**: All schemas follow the same patterns and conventions
|
|
155
|
+
4. **Shared Utilities**: Common patterns and utilities available across all schemas
|
|
156
|
+
|
|
157
|
+
## Performance Considerations
|
|
158
|
+
|
|
159
|
+
### Indexing Strategy
|
|
160
|
+
- **Primary Access Patterns**: Indexed based on service-specific query patterns
|
|
161
|
+
- **Cross-Service Queries**: Foreign key indexes for service-to-service lookups
|
|
162
|
+
- **Analytics Queries**: Specialized indexes for reporting and business intelligence
|
|
163
|
+
- **Time-Based Queries**: Temporal indexes for audit trails and activity tracking
|
|
164
|
+
|
|
165
|
+
### Query Optimization
|
|
166
|
+
- **Selective Columns**: Avoid SELECT * patterns
|
|
167
|
+
- **Proper Joins**: Efficient relationship traversal
|
|
168
|
+
- **Pagination Support**: Cursor-based pagination for large datasets
|
|
169
|
+
- **Aggregation Tables**: Pre-computed summaries for heavy analytics
|
|
170
|
+
|
|
171
|
+
### Storage Optimization
|
|
172
|
+
- **JSONB Usage**: Structured but flexible data storage
|
|
173
|
+
- **Text vs VARCHAR**: Appropriate type selection for content
|
|
174
|
+
- **Timestamp Precision**: Timezone-aware timestamps throughout
|
|
175
|
+
- **Null Handling**: Proper null vs default value strategies
|
|
176
|
+
|
|
177
|
+
## Monitoring and Maintenance
|
|
178
|
+
|
|
179
|
+
### Performance Monitoring
|
|
180
|
+
- Query execution time tracking
|
|
181
|
+
- Index usage statistics
|
|
182
|
+
- Connection pool monitoring
|
|
183
|
+
- Slow query identification
|
|
184
|
+
|
|
185
|
+
### Data Quality
|
|
186
|
+
- Constraint violation monitoring
|
|
187
|
+
- Data consistency checks
|
|
188
|
+
- Reference integrity validation
|
|
189
|
+
- Business rule compliance
|
|
190
|
+
|
|
191
|
+
### Capacity Planning
|
|
192
|
+
- Table growth tracking
|
|
193
|
+
- Storage utilization monitoring
|
|
194
|
+
- Index size optimization
|
|
195
|
+
- Partition planning for large tables
|
|
196
|
+
|
|
197
|
+
## Future Enhancements
|
|
198
|
+
|
|
199
|
+
### Planned Improvements
|
|
200
|
+
- **Partitioning Strategy**: For large, time-series tables
|
|
201
|
+
- **Read Replicas**: For analytical workloads
|
|
202
|
+
- **Materialized Views**: For complex reporting queries
|
|
203
|
+
- **Archive Strategy**: For historical data management
|
|
204
|
+
|
|
205
|
+
### Scalability Roadmap
|
|
206
|
+
- **Horizontal Partitioning**: By tenant/store for massive scale
|
|
207
|
+
- **Service-Specific Databases**: When individual services require different storage strategies
|
|
208
|
+
- **Caching Strategy**: Redis integration for hot data
|
|
209
|
+
- **Event Sourcing**: For critical business events
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
export interface BaseServiceConfig {
|
|
2
|
+
serviceName: string;
|
|
3
|
+
port: number;
|
|
4
|
+
host: string;
|
|
5
|
+
environment: "development" | "staging" | "production";
|
|
6
|
+
cors: {
|
|
7
|
+
origins: string[];
|
|
8
|
+
credentials: boolean;
|
|
9
|
+
};
|
|
10
|
+
rateLimiting: {
|
|
11
|
+
max: number;
|
|
12
|
+
timeWindow: string;
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
export interface DatabaseConfig {
|
|
16
|
+
url: string;
|
|
17
|
+
host: string;
|
|
18
|
+
port: number;
|
|
19
|
+
user: string;
|
|
20
|
+
password: string;
|
|
21
|
+
database: string;
|
|
22
|
+
ssl: boolean;
|
|
23
|
+
poolSize: number;
|
|
24
|
+
}
|
|
25
|
+
export interface KafkaServiceConfig {
|
|
26
|
+
enabled: boolean;
|
|
27
|
+
clientId: string;
|
|
28
|
+
groupId: string;
|
|
29
|
+
topics: string[];
|
|
30
|
+
autoCommit: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface RedisConfig {
|
|
33
|
+
host: string;
|
|
34
|
+
port: number;
|
|
35
|
+
password?: string;
|
|
36
|
+
db: number;
|
|
37
|
+
ttl: number;
|
|
38
|
+
}
|
|
39
|
+
export interface AuditConfig {
|
|
40
|
+
enabled: boolean;
|
|
41
|
+
level: "minimal" | "standard" | "comprehensive";
|
|
42
|
+
bufferSize: number;
|
|
43
|
+
flushInterval: number;
|
|
44
|
+
sensitiveFieldMasking: boolean;
|
|
45
|
+
}
|
|
46
|
+
export interface ServiceProfile {
|
|
47
|
+
base: BaseServiceConfig;
|
|
48
|
+
database: DatabaseConfig;
|
|
49
|
+
kafka: KafkaServiceConfig;
|
|
50
|
+
redis?: RedisConfig;
|
|
51
|
+
audit: AuditConfig;
|
|
52
|
+
features: Record<string, boolean>;
|
|
53
|
+
customConfig?: Record<string, unknown>;
|
|
54
|
+
}
|
|
55
|
+
export declare const STORE_SERVICE_PROFILE: ServiceProfile;
|
|
56
|
+
export declare const COMPLIANCE_SERVICE_PROFILE: ServiceProfile;
|
|
57
|
+
export declare const PRODUCT_SERVICE_PROFILE: ServiceProfile;
|
|
58
|
+
export declare const INVENTORY_SERVICE_PROFILE: ServiceProfile;
|
|
59
|
+
export declare const ADMIN_API_SERVICE_PROFILE: ServiceProfile;
|
|
60
|
+
export declare const OXA_SERVICE_PROFILE: ServiceProfile;
|
|
61
|
+
export type ServiceName = "store-service" | "compliance-service" | "product-service" | "inventory-core-service" | "admin-api-service" | "oxa-service";
|
|
62
|
+
export declare const SERVICE_PROFILES: Record<ServiceName, ServiceProfile>;
|
|
63
|
+
/**
|
|
64
|
+
* Get configuration profile for a specific service
|
|
65
|
+
*/
|
|
66
|
+
export declare function getServiceProfile(serviceName: ServiceName): ServiceProfile;
|
|
67
|
+
/**
|
|
68
|
+
* Initialize service with its profile and return configured instances
|
|
69
|
+
*/
|
|
70
|
+
export declare function initializeServiceWithProfile(serviceName: ServiceName): Promise<{
|
|
71
|
+
profile: ServiceProfile;
|
|
72
|
+
kafkaConfig: import("../events/kafka").AxovaKafkaConfig;
|
|
73
|
+
serviceAuthConfig: import("../middleware/serviceAuth").ServiceAuthConfig;
|
|
74
|
+
isFeatureEnabled: (feature: string) => boolean;
|
|
75
|
+
getCustomConfig: (key: string) => unknown;
|
|
76
|
+
isDevelopment: () => boolean;
|
|
77
|
+
isProduction: () => boolean;
|
|
78
|
+
}>;
|
|
79
|
+
/**
|
|
80
|
+
* Validate service configuration
|
|
81
|
+
*/
|
|
82
|
+
export declare function validateServiceConfig(profile: ServiceProfile): {
|
|
83
|
+
valid: boolean;
|
|
84
|
+
errors: string[];
|
|
85
|
+
};
|