Refactor docs structure and update API env config

Moved documentation files into a new docs/ directory and added a documentation index (docs/README.md). Updated the main README with improved project and documentation details. Set explicit API environment variables in Dockerfile for production. Enhanced next.config.mjs with improved API_BASE_URL handling and logging for better deployment clarity.
This commit is contained in:
NotII
2025-09-01 16:48:42 +01:00
parent 57c2fbdf50
commit 5ce716d2ab
8 changed files with 70 additions and 6 deletions

329
docs/ANALYTICS.md Normal file
View File

@@ -0,0 +1,329 @@
# Analytics System Documentation
## Overview
The analytics system provides comprehensive insights into store performance, sales trends, customer behavior, and order management. It supports both vendors and staff users (sub-users) with appropriate access controls and server-side rendering for optimal performance.
## Features
### 🔐 Multi-User Support
- **Vendors**: Access their own store analytics automatically
- **Staff/Sub-Users**: Access store analytics by providing a `storeId` parameter via URL or cookies
- **Role-based Access**: Different permissions for different user types
- **Server-side Rendering**: Initial data fetched server-side for better performance
### 📊 Analytics Dashboard
- **Overview Metrics**: Total revenue, orders, customers, and products
- **Revenue Trends**: Time-based revenue analysis with interactive charts
- **Product Performance**: Top-selling products with stock status
- **Customer Insights**: Customer segmentation and behavior analysis
- **Order Analytics**: Order status distribution and processing times
### 🎯 Key Metrics
- Total and monthly revenue
- Order completion rates
- Customer acquisition and retention
- Product performance rankings
- Average order processing times
## API Endpoints
### Authentication
All endpoints require authentication using the new `protectStore` middleware:
```javascript
// For vendors (automatic store access)
GET /api/analytics/overview
// For staff users (requires storeId parameter)
GET /api/analytics/overview?storeId=store_id_here
```
### Available Endpoints
#### 1. Analytics Overview
```http
GET /api/analytics/overview
```
Returns comprehensive overview metrics including:
- Order statistics (total, completed, pending, completion rate)
- Revenue data (total, monthly, weekly, average order value)
- Product count
- Unique customer count
- User type (vendor/staff)
#### 2. Revenue Trends
```http
GET /api/analytics/revenue-trends?period=30&storeId=optional
```
Returns daily revenue and order trends for the specified period.
#### 3. Product Performance
```http
GET /api/analytics/product-performance?storeId=optional
```
Returns top-performing products with sales metrics and stock status.
#### 4. Customer Insights
```http
GET /api/analytics/customer-insights?storeId=optional
```
Returns customer segmentation and top customer analysis.
#### 5. Order Analytics
```http
GET /api/analytics/order-analytics?period=30&storeId=optional
```
Returns order status distribution and processing time analysis.
## Frontend Implementation
### Server-Side Rendering
The analytics page uses server-side rendering for optimal performance:
```typescript
// app/dashboard/analytics/page.tsx
export default async function AnalyticsPage({
searchParams,
}: {
searchParams: { storeId?: string };
}) {
const storeId = searchParams.storeId;
const initialData = await getAnalyticsOverviewServer(storeId);
return <AnalyticsDashboard initialData={initialData} />;
}
```
### Store Selection for Staff Users
Staff users can select which store to view analytics for:
```typescript
// URL-based store selection
/dashboard/analytics?storeId=store_id_here
// StoreSelector component for easy store switching
<StoreSelector />
```
### Components
#### AnalyticsDashboard
Main dashboard component with tabs for different analytics views.
**Props:**
- `initialData`: Initial analytics overview data (server-side fetched)
**Features:**
- Key metrics cards with trend indicators
- Tabbed interface for different analytics views
- Refresh functionality
- User type indicator (Vendor/Staff View)
#### StoreSelector
Client-side component for staff users to select stores.
**Features:**
- Input field for store ID
- URL-based navigation
- Current store display
- Error handling and validation
#### RevenueChart
Displays revenue trends over time with interactive charts.
**Props:**
- `timeRange`: Time period for analysis (7, 30, 90 days)
#### ProductPerformanceChart
Shows top-performing products in a table format.
#### CustomerInsightsChart
Displays customer segmentation and top customers.
#### OrderAnalyticsChart
Shows order status distribution and daily trends.
**Props:**
- `timeRange`: Time period for analysis
#### MetricsCard
Reusable component for displaying individual metrics.
**Props:**
- `title`: Metric title
- `value`: Metric value
- `description`: Metric description
- `icon`: Lucide icon component
- `trend`: Trend direction ("up", "down", "neutral")
- `trendValue`: Trend description
## Sub-User (Staff) Support
### Authentication Flow
1. Staff users authenticate using their staff credentials
2. When accessing analytics, they must provide a `storeId` parameter
3. The system verifies the store exists and grants access
4. All analytics data is filtered by the specified store
### Access Methods
Staff users can access store analytics in multiple ways:
1. **URL Parameter**: `/dashboard/analytics?storeId=store_id_here`
2. **Store Selector**: Use the StoreSelector component to choose a store
3. **Cookies**: Store ID can be stored in cookies for persistence
### Frontend Integration
The analytics service automatically handles both user types:
```typescript
// Server-side (for initial load)
const data = await getAnalyticsOverviewServer(storeId);
// Client-side (for refreshes and updates)
const data = await getAnalyticsOverviewWithStore();
```
## Usage Examples
### Basic Analytics Access
```typescript
// Server-side rendering
import { getAnalyticsOverviewServer } from '@/lib/server-api';
const overview = await getAnalyticsOverviewServer(storeId);
// Client-side updates
import { getAnalyticsOverviewWithStore } from '@/lib/services/analytics-service';
const overview = await getAnalyticsOverviewWithStore();
```
### Staff User with Specific Store
```typescript
// Navigate to analytics with store ID
router.push(`/dashboard/analytics?storeId=${storeId}`);
// Or use the store selector component
<StoreSelector />
```
### Revenue Trends with Time Range
```typescript
import { getRevenueTrendsWithStore } from '@/lib/services/analytics-service';
// Get 30-day revenue trends
const trends = await getRevenueTrendsWithStore('30');
```
## Data Structure
### AnalyticsOverview
```typescript
interface AnalyticsOverview {
orders: {
total: number;
completed: number;
pending: number;
completionRate: string;
};
revenue: {
total: number;
monthly: number;
weekly: number;
averageOrderValue: number;
};
products: {
total: number;
};
customers: {
unique: number;
};
userType?: 'vendor' | 'staff';
}
```
### RevenueData
```typescript
interface RevenueData {
_id: {
year: number;
month: number;
day: number;
};
revenue: number;
orders: number;
}
```
### ProductPerformance
```typescript
interface ProductPerformance {
productId: string;
name: string;
image: string;
unitType: string;
currentStock: number;
stockStatus: string;
totalSold: number;
totalRevenue: number;
orderCount: number;
averagePrice: number;
}
```
## Security Considerations
### Access Control
- Vendors can only access their own store data
- Staff users must provide valid storeId parameter
- All requests are authenticated and authorized
- Store ownership is verified for staff access
### Data Privacy
- Customer data is anonymized in analytics
- No sensitive information is exposed
- All data is filtered by store ownership
## Error Handling
The system provides comprehensive error handling:
- **401 Unauthorized**: Invalid or missing authentication → Redirect to login
- **400 Bad Request**: Missing storeId for staff users → Show store selector
- **403 Forbidden**: Access denied to specific store
- **404 Not Found**: Store not found
- **500 Server Error**: Internal server errors
All errors are displayed to users via toast notifications in the frontend.
## Performance Optimization
- **Server-side data fetching** for initial load
- **Client-side caching** for subsequent requests
- **Efficient database queries** with proper indexing
- **Pagination** for large datasets
- **Real-time data refresh** capabilities
- **Optimized rendering** with React Suspense
## Backend Implementation
### Middleware
- `protectStore`: Handles both vendors and staff users
- `protectVendorOnly`: Vendor-specific routes
- `protectStaffOnly`: Staff-specific routes
### Database Queries
- Uses `storeId` for consistent data filtering
- Aggregation pipelines for complex analytics
- Proper indexing for performance
- Time-based filtering for trends
## Future Enhancements
- Real-time analytics updates
- Export functionality for reports
- Advanced filtering and date range selection
- Custom dashboard configurations
- Email reports and notifications
- Comparative analytics (period-over-period)
- Predictive analytics and forecasting
- Multi-store comparison for staff users

View File

@@ -0,0 +1,74 @@
# CapRover Deployment Fix for 500 Errors
## 🚨 Issue
The domain privacy changes require specific environment variables to be set in CapRover. Missing these causes 500 errors during deployment.
## ✅ Required Environment Variables in CapRover
### **Step 1: Set Environment Variables**
In your CapRover app settings, add these environment variables:
```bash
# Required for API routing
API_BASE_URL=https://your-backend-domain.com
API_HOSTNAME=your-backend-domain.com
SERVER_API_URL=https://your-backend-domain.com/api
# Client-side API URL (should already be set)
NEXT_PUBLIC_API_URL=/api
```
### **Step 2: Example Configuration**
Replace `your-backend-domain.com` with your actual backend domain:
```bash
# For production deployment
API_BASE_URL=https://internal-api.inboxi.ng
API_HOSTNAME=internal-api.inboxi.ng
SERVER_API_URL=https://internal-api.inboxi.ng/api
NEXT_PUBLIC_API_URL=/api
```
### **Step 3: Alternative - Use Internal Service Names**
If using CapRover's internal networking:
```bash
# Using CapRover internal service names
API_BASE_URL=http://srv-captain--your-backend-app-name
API_HOSTNAME=srv-captain--your-backend-app-name
SERVER_API_URL=http://srv-captain--your-backend-app-name/api
NEXT_PUBLIC_API_URL=/api
```
## 🔧 Troubleshooting
### **Check Environment Variables**
In CapRover app logs, you should see:
```
Building with environment:
- API_BASE_URL: https://your-domain.com
- API_HOSTNAME: your-domain.com
- SERVER_API_URL: https://your-domain.com/api
```
### **Common Issues**
1. **Undefined variables**: Set all required variables in CapRover
2. **Invalid URLs**: Ensure no trailing slashes in API_BASE_URL
3. **HTTPS vs HTTP**: Match your backend's protocol
### **Verification**
After deployment, check:
1. App starts without 500 errors
2. API requests work correctly
3. No console warnings about undefined variables
## 🚀 Deploy Steps
1. Set environment variables in CapRover
2. Commit and push changes
3. Redeploy the app
4. Check logs for successful startup
## 📝 Notes
- The `next.config.mjs` now has safer fallbacks to prevent 500 errors
- Missing variables will log warnings but won't crash the app
- For local development, use the `.env` file as before

72
docs/OPTIMIZED-BUILD.md Normal file
View File

@@ -0,0 +1,72 @@
# Optimized Builds for Slower CPUs
This document provides instructions for building the project on slower CPUs or resource-constrained environments.
## Quick Start
Run the optimized build using:
```bash
npm run build:optimized
```
## Optimization Features
The following optimizations have been implemented to improve build performance:
1. **Memory Limit Control**: Sets Node.js memory limit to prevent crashes on memory-constrained systems
2. **Build Cache Management**: Automatically cleans up caches to prevent bloat
3. **TypeScript/ESLint Skip**: Skips type checking and linting during production builds
4. **Code Splitting**: Implements React.lazy() for code splitting and lazy loading
5. **Source Map Disabling**: Disables source maps in production for faster builds
## Manual Optimization Steps
If you need to manually optimize the build process:
### 1. Clean the caches
```bash
npm run clean
```
### 2. Set Node.js memory limit
```bash
export NODE_OPTIONS="--max-old-space-size=4096"
```
### 3. Skip non-essential checks
```bash
NEXT_SKIP_LINT=1 NEXT_SKIP_TS_CHECK=1 npm run build
```
### 4. Use SWC compiler with optimized settings
```bash
NEXT_TELEMETRY_DISABLED=1 npm run build:fast
```
## Configuration Files
The following configuration files have been optimized:
- **next.config.mjs**: Contains SWC optimizations and standalone output
- **.npmrc**: Configures Node.js memory limits and disables notifications
- **.env.production**: Sets environment variables for production builds
## Troubleshooting
### Out of Memory Errors
If you encounter "JavaScript heap out of memory" errors, try:
```bash
export NODE_OPTIONS="--max-old-space-size=2048"
npm run build:fast
```
### Slow Builds
If builds are still slow:
1. Try running with lower memory settings
2. Disable unnecessary parts of the app temporarily
3. Build incrementally using `next build --no-lint`

51
docs/README.md Normal file
View File

@@ -0,0 +1,51 @@
# 📚 Ember Market Frontend Documentation
Welcome to the Ember Market Frontend documentation. This folder contains all technical documentation, guides, and references for the project.
## 📋 Documentation Index
### 🚀 Deployment & Infrastructure
- **[CapRover Deployment Fix](./CAPROVER-DEPLOYMENT-FIX.md)** - Fixes for 500 errors and environment variable configuration
- **[Optimized Build](./OPTIMIZED-BUILD.md)** - Build optimization strategies and performance improvements
### 📊 Features & Analytics
- **[Analytics](./ANALYTICS.md)** - Analytics implementation and data insights documentation
### 🛠️ Development
- **[Lib Documentation](./lib-readme.md)** - Library utilities and helper functions
## 🏗️ Project Structure
```
docs/
├── README.md # This index file
├── CAPROVER-DEPLOYMENT-FIX.md # Deployment troubleshooting
├── ANALYTICS.md # Analytics documentation
├── OPTIMIZED-BUILD.md # Build optimization guide
└── lib-readme.md # Library utilities guide
```
## 🔗 Related Documentation
- **[Main README](../README.md)** - Project overview and setup instructions
- **[Backend Documentation](../../ember-market-backend/README.md)** - Backend API documentation
- **[Payments Documentation](../../ember-market-payments/README.md)** - Payment system documentation
## 📝 Contributing to Documentation
When adding new documentation:
1. Create `.md` files in this `docs/` folder
2. Update this README.md index
3. Use clear, descriptive filenames
4. Include relevant emojis for easy scanning
5. Cross-reference related documents
## 🏷️ Document Categories
- **🚀 Deployment** - CapRover, Docker, environment setup
- **📊 Analytics** - Data tracking, insights, reporting
- **🛠️ Development** - Code guides, utilities, best practices
- **🔧 Configuration** - Environment variables, API setup
- **🐛 Troubleshooting** - Common issues and fixes

82
docs/lib-readme.md Normal file
View File

@@ -0,0 +1,82 @@
# API & Utilities Organization
This directory contains the API client and utility functions used throughout the application.
## Directory Structure
```
lib/
├─ api.ts # Main API entry point
├─ api-client.ts # Client-side API functions
├─ server-api.ts # Server-side API functions
├─ services/ # Service modules
│ ├─ index.ts # Service re-exports
│ ├─ product-service.ts # Product API
│ ├─ shipping-service.ts # Shipping API
│ └─ stats-service.ts # Statistics API
├─ utils/ # Utility functions
│ └─ index.ts # Utility re-exports
├─ types.ts # Common TypeScript types
├─ utils.ts # General utilities
├─ auth-utils.ts # Authentication utilities
└─ styles.ts # Styling utilities
```
## API Structure
- `api.ts` - The main API entry point that re-exports all API functionality
- `api-client.ts` - Client-side API functions and types
- `server-api.ts` - Server-side API functions (for server components in the app/ directory)
## How to Use
### In Client Components
```typescript
// Import what you need from the main API module
import { clientFetch, getCustomers, getProducts } from '@/lib/api';
// Example usage
const customers = await getCustomers(1, 25);
const products = await getProducts(1, 10);
```
### In Server Components (app/ directory only)
```typescript
// Server functions only work in Server Components in the app/ directory
import { getCustomersServer } from '@/lib/api';
// In a Server Component
export default async function Page() {
const customers = await getCustomersServer(1, 25);
// ...
}
```
## Server Components Compatibility
The server-side API functions (`fetchServer`, `getCustomersServer`, etc.) can **only** be used in Server Components within the app/ directory. They will throw an error if used in:
- Client Components
- The pages/ directory
- Any code that runs in the browser
This is because they rely on Next.js server-only features like the `cookies()` function from `next/headers`.
## Utilities
For utilities, you can either import specific functions or use the utils index:
```typescript
// Import specific utilities
import { cn } from '@/lib/utils';
import { getAuthToken } from '@/lib/auth-utils';
// Or import from the utils index
import { cn, getAuthToken } from '@/lib/utils';
```
## Backward Compatibility
For backward compatibility, many functions are also re-exported from their original locations.