feat: Complete production deployment pipeline with admin dashboard
Some checks failed
ParentFlow CI/CD Pipeline / Backend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Frontend Tests (push) Has been cancelled
ParentFlow CI/CD Pipeline / Security Scanning (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-app/maternal-app-backend dockerfile:Dockerfile.production name:backend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Build Docker Images (map[context:maternal-web dockerfile:Dockerfile.production name:frontend]) (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Development (push) Has been cancelled
ParentFlow CI/CD Pipeline / Deploy to Production (push) Has been cancelled
CI/CD Pipeline / Lint and Test (push) Has been cancelled
CI/CD Pipeline / E2E Tests (push) Has been cancelled
CI/CD Pipeline / Build Application (push) Has been cancelled

- Add unified deployment script with Node.js 22 installation
- Create comprehensive database migration script (28 migrations + admin tables)
- Add production start/stop scripts for all services
- Integrate admin dashboard (parentflow-admin) into PM2 ecosystem
- Configure all services: Backend (3020), Frontend (3030), Admin (3335)
- Update ecosystem.config.js with admin dashboard configuration
- Add invite codes module for user registration management
This commit is contained in:
2025-10-06 22:43:28 +00:00
parent 560fd22023
commit 4e19b992df
37 changed files with 6767 additions and 675 deletions

View File

@@ -1,170 +0,0 @@
# 🚀 Deploy ParentFlow to Production - Step by Step
## Quick Deploy Instructions
### Step 1: Connect to Production Server
Open your terminal and connect via SSH:
```bash
ssh root@10.0.0.240
# Password: a3pq5t50yA@#
```
### Step 2: Download and Run Deployment Script
Once connected to the server, run these commands:
```bash
# Download the deployment script
wget https://git.noru1.ro/andrei/maternal-app/raw/branch/main/deploy-to-production.sh
# Make it executable
chmod +x deploy-to-production.sh
# Run the deployment
./deploy-to-production.sh
```
### Step 3: Edit Environment Variables (First Time Only)
The script will pause and ask you to edit `.env.production`.
You need to update these critical values:
```bash
# Edit the file
nano /root/maternal-app/.env.production
```
Key values to update:
- `JWT_SECRET` - Generate with: `openssl rand -base64 64`
- `JWT_REFRESH_SECRET` - Generate with: `openssl rand -base64 64`
- `OPENAI_API_KEY` - Your OpenAI API key for AI features
- Redis, MongoDB, MinIO passwords (keep defaults or change)
Press `Ctrl+X`, then `Y`, then `Enter` to save and exit.
Then press `Enter` in the deployment script to continue.
### Step 4: Verify Deployment
After the script completes, verify everything is running:
```bash
# Check PM2 processes
pm2 status
# Check Docker containers
docker ps
# Check if services are accessible
curl http://localhost:3020/api/health
curl http://localhost:3030
```
## What the Script Does
1. ✅ Clones the repository from Gitea
2. ✅ Installs Node.js 18, PM2, Docker, Docker Compose
3. ✅ Installs all npm dependencies
4. ✅ Builds backend and frontend
5. ✅ Starts Docker containers (Redis, MongoDB, MinIO)
6. ✅ Runs database migrations on 10.0.0.207
7. ✅ Starts PM2 processes for backend (3020) and frontend (3030)
8. ✅ Sets up PM2 to restart on system reboot
## After Deployment
### Test the Application
From your local machine:
1. Backend Health: http://10.0.0.240:3020/api/health
2. Frontend: http://10.0.0.240:3030
### Production URLs (Already configured in Nginx)
- API: https://api.parentflowapp.com
- Web: https://web.parentflowapp.com
### Management Commands
On the production server:
```bash
# View logs
pm2 logs
# Restart services
pm2 restart all
# Stop services
pm2 stop all
# View real-time metrics
pm2 monit
# Docker logs
docker logs parentflow-redis-prod
docker logs parentflow-mongodb-prod
```
## Troubleshooting
### If backend doesn't start:
```bash
pm2 logs parentflow-backend-prod --err
cd /root/maternal-app/maternal-app/maternal-app-backend
npm run build
pm2 restart parentflow-backend-prod
```
### If frontend doesn't start:
```bash
pm2 logs parentflow-frontend-prod --err
cd /root/maternal-app/maternal-web
npm run build
pm2 restart parentflow-frontend-prod
```
### If database connection fails:
```bash
# Test connection
PGPASSWORD=a3ppq psql -h 10.0.0.207 -p 5432 -U postgres -d parentflow -c "SELECT version();"
# Check migrations
cd /root/maternal-app/maternal-app/maternal-app-backend
./scripts/check-migrations.sh
```
### To update after changes:
```bash
cd /root/maternal-app
git pull origin main
cd maternal-app/maternal-app-backend
npm install
npm run build
cd ../../maternal-web
npm install
npm run build
pm2 restart all
```
## Success Indicators
You'll know deployment is successful when:
-`pm2 status` shows both processes as "online"
-`docker ps` shows 3 containers running
- ✅ Backend responds at http://10.0.0.240:3020/api/health
- ✅ Frontend loads at http://10.0.0.240:3030
- ✅ You can register/login at https://web.parentflowapp.com
## Support
If you encounter issues:
1. Check logs: `pm2 logs`
2. Check Docker: `docker ps` and `docker logs [container-name]`
3. Verify PostgreSQL connection to 10.0.0.207
4. Ensure ports 3020 and 3030 are not blocked
---
**Ready to deploy! Just SSH to the server and run the 3 commands in Step 2.**

View File

@@ -1,76 +0,0 @@
# Production Server Deployment Instructions
## Quick Deploy on Server 10.0.0.240
Since the repository has already been cloned, run these commands:
```bash
# Navigate to the project directory
cd /root/maternal-app
# Switch to the main branch (where all the code is)
git checkout main
git pull origin main
# Make deployment script executable and run it
chmod +x deploy-to-production.sh
./deploy-to-production.sh
```
## What the Deployment Script Does
1. **Installs System Dependencies**
- Node.js 20.x
- PM2 process manager
- Docker and Docker Compose
- PostgreSQL client tools
2. **Sets Up Database**
- Connects to PostgreSQL at 10.0.0.207
- Creates parentflow database if needed
- Runs all migrations in sequence
3. **Starts Services**
- Redis, MongoDB, MinIO via Docker Compose
- Backend API on port 3020 via PM2
- Frontend on port 3005 via PM2
4. **Configures PM2**
- Sets up auto-restart on system reboot
- Saves PM2 configuration
## Manual Commands if Needed
### Check out the main branch:
```bash
git checkout main
git pull origin main
```
### Start all services:
```bash
./start-production.sh
```
### Stop all services:
```bash
./stop-production.sh
```
### Check PM2 status:
```bash
pm2 status
pm2 logs
```
### Check Docker services:
```bash
docker-compose -f docker-compose.production.yml ps
docker-compose -f docker-compose.production.yml logs
```
## Important Notes
- **Database**: PostgreSQL is on dedicated server 10.0.0.207 (not in Docker)
- **Default branch issue**: The repository default branch is 'master' but all code is on 'main'
- **Always use main branch**: Make sure to checkout main branch after cloning

331
deploy-production.sh Executable file
View File

@@ -0,0 +1,331 @@
#!/bin/bash
# ParentFlow Production Deployment Pipeline
# This script deploys the complete ParentFlow application suite to production
# Run on production server 10.0.0.240 as root
set -e
# Configuration
REPO_URL="https://andrei:33edc%40%40NHY%5E%5E@git.noru1.ro/andrei/maternal-app.git"
DEPLOY_DIR="/root/parentflow-production"
DB_HOST="10.0.0.207"
DB_PORT="5432"
DB_USER="postgres"
DB_PASSWORD="a3ppq"
DB_NAME="parentflow"
DB_NAME_ADMIN="parentflowadmin"
# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color
# Logging function
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
exit 1
}
success() {
echo -e "${GREEN}${NC} $1"
}
warning() {
echo -e "${YELLOW}${NC} $1"
}
# Header
echo ""
echo "============================================"
echo " ParentFlow Production Deployment v2.0 "
echo "============================================"
echo ""
# Step 1: Install Node.js 22
log "${CYAN}Step 1: Installing Node.js 22...${NC}"
if ! command -v node &> /dev/null || [[ $(node -v | cut -d'v' -f2 | cut -d'.' -f1) -lt 22 ]]; then
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt-get install -y nodejs
success "Node.js $(node -v) installed"
else
success "Node.js $(node -v) already installed"
fi
# Step 2: Install PM2 globally
log "${CYAN}Step 2: Installing PM2...${NC}"
if ! command -v pm2 &> /dev/null; then
npm install -g pm2@latest
success "PM2 installed"
else
pm2 update
success "PM2 updated"
fi
# Step 3: Install Docker and Docker Compose
log "${CYAN}Step 3: Checking Docker installation...${NC}"
if ! command -v docker &> /dev/null; then
curl -fsSL https://get.docker.com | sh
success "Docker installed"
else
success "Docker already installed"
fi
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
success "Docker Compose installed"
else
success "Docker Compose already installed"
fi
# Step 4: Install PostgreSQL client
log "${CYAN}Step 4: Installing PostgreSQL client...${NC}"
if ! command -v psql &> /dev/null; then
apt-get update
apt-get install -y postgresql-client
success "PostgreSQL client installed"
else
success "PostgreSQL client already installed"
fi
# Step 5: Clone or update repository
log "${CYAN}Step 5: Fetching latest code from main branch...${NC}"
if [ -d "$DEPLOY_DIR" ]; then
warning "Deployment directory exists, pulling latest changes..."
cd "$DEPLOY_DIR"
git fetch origin main
git reset --hard origin/main
git clean -fd
else
log "Cloning repository..."
git clone -b main "$REPO_URL" "$DEPLOY_DIR"
cd "$DEPLOY_DIR"
fi
success "Repository updated to latest main branch"
# Step 6: Stop existing services
log "${CYAN}Step 6: Stopping existing services...${NC}"
if [ -f "./stop-production.sh" ]; then
./stop-production.sh || warning "No services were running"
else
warning "Stop script not found, continuing..."
fi
# Step 7: Install dependencies
log "${CYAN}Step 7: Installing application dependencies...${NC}"
# Backend
log "Installing backend dependencies..."
cd "$DEPLOY_DIR/maternal-app/maternal-app-backend"
rm -rf node_modules package-lock.json
npm install --production=false
npm update
success "Backend dependencies installed"
# Frontend
log "Installing frontend dependencies..."
cd "$DEPLOY_DIR/maternal-web"
rm -rf node_modules package-lock.json .next
npm install --production=false
npm update
success "Frontend dependencies installed"
# Admin Dashboard
log "Installing admin dashboard dependencies..."
cd "$DEPLOY_DIR/parentflow-admin"
rm -rf node_modules package-lock.json .next
npm install --production=false
npm update
success "Admin dashboard dependencies installed"
# Step 8: Set up environment files
log "${CYAN}Step 8: Configuring environment...${NC}"
cd "$DEPLOY_DIR"
# Backend .env
cat > "$DEPLOY_DIR/maternal-app/maternal-app-backend/.env.production" << EOF
# Production Environment Configuration
NODE_ENV=production
API_PORT=3020
API_URL=https://api.parentflowapp.com
# Database Configuration
DATABASE_HOST=${DB_HOST}
DATABASE_PORT=${DB_PORT}
DATABASE_NAME=${DB_NAME}
DATABASE_USER=${DB_USER}
DATABASE_PASSWORD=${DB_PASSWORD}
DATABASE_SSL=true
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_URL=redis://localhost:6379
# MongoDB Configuration
MONGODB_URI=mongodb://localhost:27017/parentflow_production
# MinIO Configuration
MINIO_ENDPOINT=localhost
MINIO_PORT=9000
MINIO_ACCESS_KEY=minioadmin
MINIO_SECRET_KEY=parentflow_minio_prod_2024
MINIO_BUCKET=parentflow-files
MINIO_USE_SSL=false
# JWT Configuration
JWT_SECRET=parentflow_jwt_secret_production_2024_secure
JWT_EXPIRATION=1h
JWT_REFRESH_SECRET=parentflow_refresh_secret_production_2024_secure
JWT_REFRESH_EXPIRATION=7d
# AI Services (copy from development .env)
AI_PROVIDER=azure
AZURE_OPENAI_ENABLED=true
AZURE_OPENAI_CHAT_ENDPOINT=https://footprints-open-ai.openai.azure.com
AZURE_OPENAI_CHAT_DEPLOYMENT=gpt-5-mini
AZURE_OPENAI_CHAT_API_VERSION=2025-04-01-preview
AZURE_OPENAI_CHAT_API_KEY=a5f7e3e70a454a399f9216853b45e18b
AZURE_OPENAI_CHAT_MAX_TOKENS=1000
AZURE_OPENAI_REASONING_EFFORT=medium
AZURE_OPENAI_WHISPER_ENDPOINT=https://footprints-ai.openai.azure.com
AZURE_OPENAI_WHISPER_DEPLOYMENT=whisper
AZURE_OPENAI_WHISPER_API_VERSION=2024-06-01
AZURE_OPENAI_WHISPER_API_KEY=42702a67a41547919877a2ab8e4837f9
AZURE_OPENAI_EMBEDDINGS_ENDPOINT=https://footprints-ai.openai.azure.com
AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT=Text-Embedding-ada-002-V2
AZURE_OPENAI_EMBEDDINGS_API_VERSION=2023-05-15
AZURE_OPENAI_EMBEDDINGS_API_KEY=42702a67a41547919877a2ab8e4837f9
# CORS Configuration
CORS_ORIGIN=https://web.parentflowapp.com,https://admin.parentflowapp.com
# Rate Limiting
RATE_LIMIT_TTL=60
RATE_LIMIT_MAX=100
# Email Service
MAILGUN_API_KEY=
MAILGUN_DOMAIN=
EMAIL_FROM=noreply@parentflowapp.com
EMAIL_FROM_NAME=ParentFlow
# Error Tracking
SENTRY_ENABLED=false
SENTRY_DSN=
EOF
# Frontend .env.production
cat > "$DEPLOY_DIR/maternal-web/.env.production" << EOF
# Frontend Production Configuration
NEXT_PUBLIC_API_URL=https://api.parentflowapp.com/api/v1
NEXT_PUBLIC_GRAPHQL_URL=https://api.parentflowapp.com/graphql
NEXT_PUBLIC_WS_URL=wss://api.parentflowapp.com
NEXT_PUBLIC_APP_URL=https://web.parentflowapp.com
NEXT_PUBLIC_APP_NAME=ParentFlow
NEXT_PUBLIC_ENABLE_PWA=true
NEXT_PUBLIC_ENABLE_ANALYTICS=true
EOF
# Admin Dashboard .env.production
cat > "$DEPLOY_DIR/parentflow-admin/.env.production" << EOF
# Admin Dashboard Production Configuration
NEXT_PUBLIC_API_URL=https://api.parentflowapp.com/api/v1
NEXT_PUBLIC_APP_URL=https://adminpf.parentflowapp.com
NEXT_PUBLIC_APP_NAME=ParentFlow Admin
EOF
success "Environment files configured"
# Step 9: Run database migrations
log "${CYAN}Step 9: Running database migrations...${NC}"
cd "$DEPLOY_DIR"
./migrate-production.sh || error "Database migration failed"
success "Database migrations completed"
# Step 10: Build applications
log "${CYAN}Step 10: Building applications for production...${NC}"
# Build backend
log "Building backend..."
cd "$DEPLOY_DIR/maternal-app/maternal-app-backend"
NODE_ENV=production npm run build
success "Backend built"
# Build frontend
log "Building frontend..."
cd "$DEPLOY_DIR/maternal-web"
NODE_ENV=production npm run build
success "Frontend built"
# Build admin dashboard
log "Building admin dashboard..."
cd "$DEPLOY_DIR/parentflow-admin"
NODE_ENV=production npm run build
success "Admin dashboard built"
# Step 11: Start Docker services
log "${CYAN}Step 11: Starting Docker services...${NC}"
cd "$DEPLOY_DIR"
if docker compose version &> /dev/null; then
docker compose -f docker-compose.production.yml up -d
else
docker-compose -f docker-compose.production.yml up -d
fi
success "Docker services started"
# Step 12: Start application services
log "${CYAN}Step 12: Starting application services...${NC}"
cd "$DEPLOY_DIR"
./start-production.sh || error "Failed to start services"
success "Application services started"
# Step 13: Verify deployment
log "${CYAN}Step 13: Verifying deployment...${NC}"
sleep 10
verify_service() {
local service=$1
local port=$2
if lsof -i:$port > /dev/null 2>&1; then
success "$service is running on port $port"
else
error "$service is not running on port $port"
fi
}
verify_service "Backend API" 3020
verify_service "Frontend" 3030
verify_service "Admin Dashboard" 3335
# Final summary
echo ""
echo "============================================"
echo -e "${GREEN} Deployment Completed Successfully! ${NC}"
echo "============================================"
echo ""
echo "Services running at:"
echo " Backend API: http://10.0.0.240:3020"
echo " Frontend: http://10.0.0.240:3030"
echo " Admin Dashboard: http://10.0.0.240:3335"
echo ""
echo "Configure your nginx proxy to route:"
echo " api.parentflowapp.com -> 10.0.0.240:3020"
echo " web.parentflowapp.com -> 10.0.0.240:3030"
echo " adminpf.parentflowapp.com -> 10.0.0.240:3335"
echo ""
echo "Management commands:"
echo " Start services: ./start-production.sh"
echo " Stop services: ./stop-production.sh"
echo " View logs: pm2 logs"
echo " Monitor: pm2 monit"
echo ""
log "Deployment completed at $(date)"

View File

@@ -1,197 +0,0 @@
#!/bin/bash
# ParentFlow Production Deployment Script
# Run this on server 10.0.0.240 as root
set -e
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
echo "=========================================="
echo "ParentFlow Production Deployment"
echo "=========================================="
echo ""
# Step 1: Check if already deployed
if [ -d "/root/maternal-app" ]; then
echo -e "${YELLOW}Repository already exists. Pulling latest changes...${NC}"
cd /root/maternal-app
git pull origin main
else
echo -e "${BLUE}Step 1: Cloning repository...${NC}"
cd /root
git clone https://git.noru1.ro/andrei/maternal-app.git
cd maternal-app
fi
echo -e "${GREEN}✓ Repository ready${NC}"
# Step 2: Install Node.js if not present
echo ""
echo -e "${BLUE}Step 2: Checking Node.js installation...${NC}"
if ! command -v node &> /dev/null; then
echo -e "${YELLOW}Installing Node.js 20...${NC}"
curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
apt-get install -y nodejs
fi
echo -e "${GREEN}✓ Node.js $(node -v)${NC}"
# Step 3: Install PM2 globally if not present
echo ""
echo -e "${BLUE}Step 3: Checking PM2 installation...${NC}"
if ! command -v pm2 &> /dev/null; then
echo -e "${YELLOW}Installing PM2...${NC}"
npm install -g pm2
fi
echo -e "${GREEN}✓ PM2 installed${NC}"
# Step 4: Install Docker and Docker Compose if not present
echo ""
echo -e "${BLUE}Step 4: Checking Docker installation...${NC}"
if ! command -v docker &> /dev/null; then
echo -e "${YELLOW}Installing Docker...${NC}"
curl -fsSL https://get.docker.com | sh
fi
echo -e "${GREEN}✓ Docker installed${NC}"
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
echo -e "${YELLOW}Installing Docker Compose...${NC}"
curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
chmod +x /usr/local/bin/docker-compose
fi
echo -e "${GREEN}✓ Docker Compose installed${NC}"
# Step 5: Install PostgreSQL client for migrations
echo ""
echo -e "${BLUE}Step 5: Installing PostgreSQL client...${NC}"
apt-get update
apt-get install -y postgresql-client
echo -e "${GREEN}✓ PostgreSQL client installed${NC}"
# Step 6: Install dependencies
echo ""
echo -e "${BLUE}Step 6: Installing application dependencies...${NC}"
echo -e "${YELLOW}Installing backend dependencies...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
npm install
echo -e "${YELLOW}Installing frontend dependencies...${NC}"
cd /root/maternal-app/maternal-web
npm install
echo -e "${GREEN}✓ Dependencies installed${NC}"
# Step 7: Build applications
echo ""
echo -e "${BLUE}Step 7: Building applications...${NC}"
echo -e "${YELLOW}Building backend...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
npm run build
echo -e "${YELLOW}Building frontend...${NC}"
cd /root/maternal-app/maternal-web
npm run build
echo -e "${GREEN}✓ Applications built${NC}"
# Step 8: Create .env.production if it doesn't exist
echo ""
echo -e "${BLUE}Step 8: Setting up environment variables...${NC}"
cd /root/maternal-app
if [ ! -f ".env.production" ]; then
cp .env.production.example .env.production
echo -e "${YELLOW}Created .env.production from example${NC}"
echo -e "${RED}IMPORTANT: Edit .env.production with your actual values!${NC}"
echo "Press Enter to continue after editing .env.production..."
read
fi
# Step 9: Start Docker services
echo ""
echo -e "${BLUE}Step 9: Starting Docker services...${NC}"
cd /root/maternal-app
if docker compose version &> /dev/null; then
docker compose -f docker-compose.production.yml up -d
else
docker-compose -f docker-compose.production.yml up -d
fi
echo -e "${GREEN}✓ Docker services started${NC}"
# Step 10: Run database migrations
echo ""
echo -e "${BLUE}Step 10: Running database migrations...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
chmod +x scripts/master-migration.sh scripts/check-migrations.sh
echo -e "${YELLOW}Testing database connection...${NC}"
PGPASSWORD=a3ppq psql -h 10.0.0.207 -p 5432 -U postgres -d parentflow -c "SELECT version();" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Database connection successful${NC}"
DATABASE_HOST=10.0.0.207 \
DATABASE_PORT=5432 \
DATABASE_NAME=parentflow \
DATABASE_USER=postgres \
DATABASE_PASSWORD=a3ppq \
./scripts/master-migration.sh
else
echo -e "${RED}✗ Cannot connect to database${NC}"
echo "Please check database server connectivity"
fi
# Step 11: Start PM2 processes
echo ""
echo -e "${BLUE}Step 11: Starting PM2 processes...${NC}"
cd /root/maternal-app
pm2 delete all 2>/dev/null || true
pm2 start ecosystem.config.js --env production
pm2 save
pm2 startup
echo -e "${GREEN}✓ PM2 processes started${NC}"
# Step 12: Verify deployment
echo ""
echo -e "${BLUE}Step 12: Verifying deployment...${NC}"
sleep 5
# Check if services are running
if lsof -i:3020 > /dev/null 2>&1; then
echo -e "${GREEN}✓ Backend is running on port 3020${NC}"
else
echo -e "${RED}✗ Backend not detected on port 3020${NC}"
fi
if lsof -i:3030 > /dev/null 2>&1; then
echo -e "${GREEN}✓ Frontend is running on port 3030${NC}"
else
echo -e "${RED}✗ Frontend not detected on port 3030${NC}"
fi
# Show status
echo ""
echo "=========================================="
echo -e "${GREEN}Deployment Complete!${NC}"
echo "=========================================="
echo ""
echo "Services:"
echo " Backend API: http://10.0.0.240:3020"
echo " Frontend: http://10.0.0.240:3030"
echo ""
echo "Public URLs (configure DNS/Nginx):"
echo " API: https://api.parentflowapp.com → 10.0.0.240:3020"
echo " Web: https://web.parentflowapp.com → 10.0.0.240:3030"
echo ""
echo "Management:"
echo " PM2 status: pm2 status"
echo " PM2 logs: pm2 logs"
echo " Docker status: docker ps"
echo ""
echo -e "${GREEN}✓ Production deployment successful!${NC}"

View File

@@ -94,5 +94,41 @@ module.exports = {
wait_ready: true, wait_ready: true,
listen_timeout: 30000 listen_timeout: 30000
}, },
{
name: 'parentflow-admin-prod',
cwd: './parentflow-admin',
script: 'node_modules/next/dist/bin/next',
args: 'start',
instances: 1,
exec_mode: 'fork',
autorestart: true,
watch: false,
max_memory_restart: '300M',
env: {
NODE_ENV: 'production',
PORT: 3335,
HOSTNAME: '0.0.0.0',
NEXT_PUBLIC_API_URL: 'https://api.parentflowapp.com/api/v1',
NEXT_PUBLIC_APP_URL: 'https://adminpf.parentflowapp.com',
NEXT_PUBLIC_APP_NAME: 'ParentFlow Admin',
},
env_production: {
NODE_ENV: 'production',
PORT: 3335,
HOSTNAME: '0.0.0.0',
NEXT_PUBLIC_API_URL: 'https://api.parentflowapp.com/api/v1',
NEXT_PUBLIC_APP_URL: 'https://adminpf.parentflowapp.com',
NEXT_PUBLIC_APP_NAME: 'ParentFlow Admin',
},
error_file: './logs/admin-error.log',
out_file: './logs/admin-out.log',
log_file: './logs/admin-combined.log',
time: true,
merge_logs: true,
node_args: '--max-old-space-size=300',
kill_timeout: 5000,
wait_ready: true,
listen_timeout: 30000
},
], ],
}; };

View File

@@ -0,0 +1,32 @@
const bcrypt = require('bcrypt');
async function createAdminUser() {
// Password to hash
const password = 'admin123';
// Generate salt and hash
const saltRounds = 10;
const hash = await bcrypt.hash(password, saltRounds);
console.log('Password:', password);
console.log('Hash:', hash);
// SQL command
const sql = `
INSERT INTO admin_users (email, password_hash, name, role)
VALUES (
'admin@parentflowapp.com',
'${hash}',
'System Administrator',
'super_admin'
) ON CONFLICT (email)
DO UPDATE SET
password_hash = '${hash}',
updated_at = CURRENT_TIMESTAMP;
`;
console.log('\nSQL Command:');
console.log(sql);
}
createAdminUser().catch(console.error);

View File

@@ -22,6 +22,7 @@ import { AnalyticsModule } from './modules/analytics/analytics.module';
import { FeedbackModule } from './modules/feedback/feedback.module'; import { FeedbackModule } from './modules/feedback/feedback.module';
import { PhotosModule } from './modules/photos/photos.module'; import { PhotosModule } from './modules/photos/photos.module';
import { ComplianceModule } from './modules/compliance/compliance.module'; import { ComplianceModule } from './modules/compliance/compliance.module';
import { InviteCodesModule } from './modules/invite-codes/invite-codes.module';
import { GraphQLCustomModule } from './graphql/graphql.module'; import { GraphQLCustomModule } from './graphql/graphql.module';
import { JwtAuthGuard } from './modules/auth/guards/jwt-auth.guard'; import { JwtAuthGuard } from './modules/auth/guards/jwt-auth.guard';
import { ErrorTrackingService } from './common/services/error-tracking.service'; import { ErrorTrackingService } from './common/services/error-tracking.service';
@@ -72,6 +73,7 @@ import { HealthController } from './common/controllers/health.controller';
FeedbackModule, FeedbackModule,
PhotosModule, PhotosModule,
ComplianceModule, ComplianceModule,
InviteCodesModule,
GraphQLCustomModule, GraphQLCustomModule,
], ],
controllers: [AppController, HealthController], controllers: [AppController, HealthController],

View File

@@ -0,0 +1,189 @@
-- V028: Create invite codes system for controlled registration
-- Purpose: Implement invite-based registration to control app access during beta/launch
-- Create invite codes table
CREATE TABLE IF NOT EXISTS invite_codes (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
code VARCHAR(20) NOT NULL UNIQUE,
created_by VARCHAR(36) REFERENCES users(id),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
-- Usage tracking
uses INTEGER DEFAULT 0,
max_uses INTEGER, -- NULL means unlimited
-- Validity
expires_at TIMESTAMP WITH TIME ZONE,
is_active BOOLEAN DEFAULT true,
-- Metadata
description TEXT,
metadata JSONB DEFAULT '{}',
-- Constraints
CONSTRAINT check_uses CHECK (uses >= 0),
CONSTRAINT check_max_uses CHECK (max_uses IS NULL OR max_uses > 0),
CONSTRAINT check_code_format CHECK (code ~ '^[A-Z0-9\-]+$')
);
-- Create index for fast code lookup
CREATE INDEX idx_invite_codes_code ON invite_codes(code) WHERE is_active = true;
CREATE INDEX idx_invite_codes_expires ON invite_codes(expires_at) WHERE expires_at IS NOT NULL;
CREATE INDEX idx_invite_codes_created_by ON invite_codes(created_by);
-- Create invite code usage tracking table
CREATE TABLE IF NOT EXISTS invite_code_uses (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
invite_code_id VARCHAR(36) REFERENCES invite_codes(id) ON DELETE CASCADE,
used_by VARCHAR(36) REFERENCES users(id),
used_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
user_email VARCHAR(255),
user_ip VARCHAR(45),
user_agent TEXT,
-- Ensure one use per user
UNIQUE(invite_code_id, used_by)
);
CREATE INDEX idx_invite_code_uses_code ON invite_code_uses(invite_code_id);
CREATE INDEX idx_invite_code_uses_user ON invite_code_uses(used_by);
-- Create admin users table for admin dashboard access
CREATE TABLE IF NOT EXISTS admin_users (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
name VARCHAR(100),
role VARCHAR(50) DEFAULT 'admin',
-- Status
is_active BOOLEAN DEFAULT true,
last_login_at TIMESTAMP WITH TIME ZONE,
-- Timestamps
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
-- Permissions (JSON array of permission strings)
permissions JSONB DEFAULT '["users:read", "users:write", "invites:read", "invites:write", "analytics:read"]',
-- Two-factor auth
two_factor_secret VARCHAR(255),
two_factor_enabled BOOLEAN DEFAULT false
);
CREATE INDEX idx_admin_users_email ON admin_users(email);
-- Create admin sessions table
CREATE TABLE IF NOT EXISTS admin_sessions (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
admin_user_id VARCHAR(36) REFERENCES admin_users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL UNIQUE,
ip_address VARCHAR(45),
user_agent TEXT,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
last_activity_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_admin_sessions_token ON admin_sessions(token_hash);
CREATE INDEX idx_admin_sessions_admin ON admin_sessions(admin_user_id);
CREATE INDEX idx_admin_sessions_expires ON admin_sessions(expires_at);
-- Create audit log for admin actions
CREATE TABLE IF NOT EXISTS admin_audit_logs (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
admin_user_id VARCHAR(36) REFERENCES admin_users(id),
action VARCHAR(100) NOT NULL,
entity_type VARCHAR(50),
entity_id VARCHAR(36),
details JSONB DEFAULT '{}',
ip_address VARCHAR(45),
user_agent TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_admin_audit_logs_admin ON admin_audit_logs(admin_user_id);
CREATE INDEX idx_admin_audit_logs_entity ON admin_audit_logs(entity_type, entity_id);
CREATE INDEX idx_admin_audit_logs_created ON admin_audit_logs(created_at);
-- Function to increment invite code uses
CREATE OR REPLACE FUNCTION increment_invite_code_uses()
RETURNS TRIGGER AS $$
BEGIN
UPDATE invite_codes
SET uses = uses + 1
WHERE id = NEW.invite_code_id;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger to automatically increment uses
CREATE TRIGGER trigger_increment_invite_uses
AFTER INSERT ON invite_code_uses
FOR EACH ROW
EXECUTE FUNCTION increment_invite_code_uses();
-- Function to check if invite code is valid
CREATE OR REPLACE FUNCTION is_invite_code_valid(
p_code VARCHAR(20)
) RETURNS TABLE (
is_valid BOOLEAN,
reason VARCHAR(100)
) AS $$
DECLARE
v_invite RECORD;
BEGIN
-- Find the invite code
SELECT * INTO v_invite
FROM invite_codes
WHERE code = p_code AND is_active = true;
-- Check if code exists
IF NOT FOUND THEN
RETURN QUERY SELECT false, 'Invalid invite code';
RETURN;
END IF;
-- Check if expired
IF v_invite.expires_at IS NOT NULL AND v_invite.expires_at < CURRENT_TIMESTAMP THEN
RETURN QUERY SELECT false, 'Invite code has expired';
RETURN;
END IF;
-- Check if max uses reached
IF v_invite.max_uses IS NOT NULL AND v_invite.uses >= v_invite.max_uses THEN
RETURN QUERY SELECT false, 'Invite code has reached maximum uses';
RETURN;
END IF;
-- Code is valid
RETURN QUERY SELECT true, 'Valid';
END;
$$ LANGUAGE plpgsql;
-- Insert default admin user (password: admin123 - CHANGE THIS!)
-- Password hash is for 'admin123' using bcrypt
INSERT INTO admin_users (email, password_hash, name, role)
VALUES (
'admin@parentflowapp.com',
'$2b$10$YourHashHere', -- Replace with actual bcrypt hash
'System Administrator',
'super_admin'
) ON CONFLICT (email) DO NOTHING;
-- Insert some sample invite codes for testing
INSERT INTO invite_codes (code, description, max_uses) VALUES
('BETA2024', 'Beta testing invite', 100),
('LAUNCH50', 'Launch promotion - 50% off', 50),
('FRIENDS', 'Friends and family', NULL)
ON CONFLICT (code) DO NOTHING;
-- Add invite_code_used column to users table to track which code was used
ALTER TABLE users ADD COLUMN IF NOT EXISTS invite_code_used VARCHAR(20);
ALTER TABLE users ADD COLUMN IF NOT EXISTS registered_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP;
-- Create index for analytics
CREATE INDEX IF NOT EXISTS idx_users_invite_code ON users(invite_code_used);
CREATE INDEX IF NOT EXISTS idx_users_registered_at ON users(registered_at);

View File

@@ -0,0 +1,80 @@
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
Query,
UseGuards,
Request,
} from '@nestjs/common';
import { InviteCodesService } from './invite-codes.service';
import { CreateInviteCodeDto, UpdateInviteCodeDto } from './invite-codes.dto';
@Controller('api/v1/admin/invite-codes')
export class InviteCodesController {
constructor(private readonly inviteCodesService: InviteCodesService) {}
@Post()
async create(@Body() dto: CreateInviteCodeDto, @Request() req: any) {
// For now, we'll pass undefined for createdBy until we implement admin auth
return this.inviteCodesService.create(dto, req.user?.id);
}
@Get()
async findAll(
@Query('page') page?: string,
@Query('limit') limit?: string,
@Query('status') status?: string,
) {
return this.inviteCodesService.findAll({
page: page ? parseInt(page, 10) : undefined,
limit: limit ? parseInt(limit, 10) : undefined,
status,
});
}
@Get('generate')
async generateCode() {
const code = await this.inviteCodesService.generateRandomCode();
return { code };
}
@Get(':id')
async findOne(@Param('id') id: string) {
return this.inviteCodesService.findOne(id);
}
@Get(':id/stats')
async getStats(@Param('id') id: string) {
return this.inviteCodesService.getUsageStats(id);
}
@Put(':id')
async update(@Param('id') id: string, @Body() dto: UpdateInviteCodeDto) {
return this.inviteCodesService.update(id, dto);
}
@Delete(':id')
async remove(@Param('id') id: string) {
await this.inviteCodesService.delete(id);
return { message: 'Invite code deleted successfully' };
}
}
// Public controller for validating invite codes during registration
@Controller('api/v1/invite-codes')
export class PublicInviteCodesController {
constructor(private readonly inviteCodesService: InviteCodesService) {}
@Post('validate')
async validate(@Body('code') code: string) {
const result = await this.inviteCodesService.validateCode(code);
return {
isValid: result.isValid,
reason: result.reason,
};
}
}

View File

@@ -0,0 +1,57 @@
import { IsString, IsOptional, IsNumber, IsBoolean, IsDateString, IsJSON, Matches, Min } from 'class-validator';
export class CreateInviteCodeDto {
@IsString()
@Matches(/^[A-Z0-9\-]+$/, { message: 'Code must contain only uppercase letters, numbers, and hyphens' })
code: string;
@IsOptional()
@IsNumber()
@Min(1)
maxUses?: number;
@IsOptional()
@IsDateString()
expiresAt?: string;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsJSON()
metadata?: any;
}
export class UpdateInviteCodeDto {
@IsOptional()
@IsString()
@Matches(/^[A-Z0-9\-]+$/, { message: 'Code must contain only uppercase letters, numbers, and hyphens' })
code?: string;
@IsOptional()
@IsNumber()
@Min(1)
maxUses?: number;
@IsOptional()
@IsDateString()
expiresAt?: string;
@IsOptional()
@IsBoolean()
isActive?: boolean;
@IsOptional()
@IsString()
description?: string;
@IsOptional()
@IsJSON()
metadata?: any;
}
export class UseInviteCodeDto {
@IsString()
code: string;
}

View File

@@ -0,0 +1,113 @@
import { Entity, Column, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn, ManyToOne, OneToMany } from 'typeorm';
import { User } from '../../database/entities/user.entity';
@Entity('invite_codes')
export class InviteCode {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true, length: 20 })
code: string;
@Column({ name: 'created_by', nullable: true })
createdBy: string;
@ManyToOne(() => User, { nullable: true })
creator?: User;
@Column({ default: 0 })
uses: number;
@Column({ name: 'max_uses', nullable: true })
maxUses: number | null;
@Column({ name: 'expires_at', type: 'timestamptz', nullable: true })
expiresAt: Date | null;
@Column({ name: 'is_active', default: true })
isActive: boolean;
@Column({ type: 'text', nullable: true })
description: string;
@Column({ type: 'jsonb', default: {} })
metadata: any;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
@OneToMany(() => InviteCodeUse, use => use.inviteCode)
usages: InviteCodeUse[];
}
@Entity('invite_code_uses')
export class InviteCodeUse {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ name: 'invite_code_id' })
inviteCodeId: string;
@ManyToOne(() => InviteCode, code => code.usages)
inviteCode: InviteCode;
@Column({ name: 'used_by' })
usedBy: string;
@ManyToOne(() => User)
user: User;
@Column({ name: 'user_email' })
userEmail: string;
@Column({ name: 'user_ip', nullable: true })
userIp: string;
@Column({ name: 'user_agent', type: 'text', nullable: true })
userAgent: string;
@CreateDateColumn({ name: 'used_at' })
usedAt: Date;
}
@Entity('admin_users')
export class AdminUser {
@PrimaryGeneratedColumn('uuid')
id: string;
@Column({ unique: true })
email: string;
@Column({ name: 'password_hash' })
passwordHash: string;
@Column({ nullable: true })
name: string;
@Column({ default: 'admin' })
role: string;
@Column({ name: 'is_active', default: true })
isActive: boolean;
@Column({ name: 'last_login_at', type: 'timestamptz', nullable: true })
lastLoginAt: Date;
@Column({ type: 'jsonb', default: [] })
permissions: string[];
@Column({ name: 'two_factor_secret', nullable: true })
twoFactorSecret: string;
@Column({ name: 'two_factor_enabled', default: false })
twoFactorEnabled: boolean;
@CreateDateColumn({ name: 'created_at' })
createdAt: Date;
@UpdateDateColumn({ name: 'updated_at' })
updatedAt: Date;
}

View File

@@ -0,0 +1,13 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { InviteCode, InviteCodeUse, AdminUser } from './invite-codes.entity';
import { InviteCodesService } from './invite-codes.service';
import { InviteCodesController, PublicInviteCodesController } from './invite-codes.controller';
@Module({
imports: [TypeOrmModule.forFeature([InviteCode, InviteCodeUse, AdminUser])],
controllers: [InviteCodesController, PublicInviteCodesController],
providers: [InviteCodesService],
exports: [InviteCodesService],
})
export class InviteCodesModule {}

View File

@@ -0,0 +1,204 @@
import { Injectable, BadRequestException, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { InviteCode, InviteCodeUse } from './invite-codes.entity';
import { CreateInviteCodeDto, UpdateInviteCodeDto } from './invite-codes.dto';
@Injectable()
export class InviteCodesService {
constructor(
@InjectRepository(InviteCode)
private inviteCodeRepository: Repository<InviteCode>,
@InjectRepository(InviteCodeUse)
private inviteCodeUseRepository: Repository<InviteCodeUse>,
) {}
async create(dto: CreateInviteCodeDto, createdBy?: string): Promise<InviteCode> {
// Validate code format
if (!/^[A-Z0-9\-]+$/.test(dto.code)) {
throw new BadRequestException('Code must contain only uppercase letters, numbers, and hyphens');
}
// Check if code already exists
const existing = await this.inviteCodeRepository.findOne({ where: { code: dto.code } });
if (existing) {
throw new BadRequestException('Invite code already exists');
}
const inviteCode = this.inviteCodeRepository.create({
...dto,
createdBy,
});
return this.inviteCodeRepository.save(inviteCode);
}
async findAll(params?: {
page?: number;
limit?: number;
status?: string
}): Promise<{ codes: InviteCode[]; total: number }> {
const query = this.inviteCodeRepository.createQueryBuilder('invite_code');
if (params?.status === 'active') {
query.where('invite_code.is_active = :isActive', { isActive: true })
.andWhere('(invite_code.expires_at IS NULL OR invite_code.expires_at > NOW())')
.andWhere('(invite_code.max_uses IS NULL OR invite_code.uses < invite_code.max_uses)');
} else if (params?.status === 'inactive') {
query.where('invite_code.is_active = :isActive', { isActive: false });
} else if (params?.status === 'expired') {
query.where('invite_code.expires_at <= NOW()');
} else if (params?.status === 'exhausted') {
query.where('invite_code.max_uses IS NOT NULL AND invite_code.uses >= invite_code.max_uses');
}
const page = params?.page || 1;
const limit = params?.limit || 10;
const skip = (page - 1) * limit;
query.orderBy('invite_code.created_at', 'DESC')
.skip(skip)
.take(limit);
const [codes, total] = await query.getManyAndCount();
return { codes, total };
}
async findOne(id: string): Promise<InviteCode> {
const inviteCode = await this.inviteCodeRepository.findOne({
where: { id },
relations: ['usages'],
});
if (!inviteCode) {
throw new NotFoundException('Invite code not found');
}
return inviteCode;
}
async findByCode(code: string): Promise<InviteCode> {
const inviteCode = await this.inviteCodeRepository.findOne({
where: { code },
});
if (!inviteCode) {
throw new NotFoundException('Invite code not found');
}
return inviteCode;
}
async update(id: string, dto: UpdateInviteCodeDto): Promise<InviteCode> {
const inviteCode = await this.findOne(id);
if (dto.code && dto.code !== inviteCode.code) {
// Check if new code already exists
const existing = await this.inviteCodeRepository.findOne({ where: { code: dto.code } });
if (existing) {
throw new BadRequestException('Invite code already exists');
}
}
Object.assign(inviteCode, dto);
return this.inviteCodeRepository.save(inviteCode);
}
async delete(id: string): Promise<void> {
const inviteCode = await this.findOne(id);
await this.inviteCodeRepository.remove(inviteCode);
}
async validateCode(code: string): Promise<{
isValid: boolean;
reason?: string;
inviteCode?: InviteCode;
}> {
const inviteCode = await this.inviteCodeRepository.findOne({
where: { code, isActive: true },
});
if (!inviteCode) {
return { isValid: false, reason: 'Invalid invite code' };
}
// Check if expired
if (inviteCode.expiresAt && inviteCode.expiresAt < new Date()) {
return { isValid: false, reason: 'Invite code has expired' };
}
// Check if max uses reached
if (inviteCode.maxUses && inviteCode.uses >= inviteCode.maxUses) {
return { isValid: false, reason: 'Invite code has reached maximum uses' };
}
return { isValid: true, inviteCode };
}
async useCode(code: string, userId: string, userEmail: string, ipAddress?: string, userAgent?: string): Promise<void> {
const validation = await this.validateCode(code);
if (!validation.isValid || !validation.inviteCode) {
throw new BadRequestException(validation.reason || 'Invalid invite code');
}
// Check if user already used this code
const existingUse = await this.inviteCodeUseRepository.findOne({
where: {
inviteCodeId: validation.inviteCode.id,
usedBy: userId,
},
});
if (existingUse) {
throw new BadRequestException('You have already used this invite code');
}
// Record the use
const use = this.inviteCodeUseRepository.create({
inviteCodeId: validation.inviteCode.id,
usedBy: userId,
userEmail,
userIp: ipAddress,
userAgent,
});
await this.inviteCodeUseRepository.save(use);
}
async getUsageStats(inviteCodeId: string): Promise<{
totalUses: number;
recentUses: InviteCodeUse[];
}> {
const [recentUses, totalUses] = await Promise.all([
this.inviteCodeUseRepository.find({
where: { inviteCodeId },
order: { usedAt: 'DESC' },
take: 10,
relations: ['user'],
}),
this.inviteCodeUseRepository.count({ where: { inviteCodeId } }),
]);
return { totalUses, recentUses };
}
async generateRandomCode(): Promise<string> {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (let i = 0; i < 8; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
if (i === 3) code += '-';
}
// Check if code exists and regenerate if needed
const existing = await this.inviteCodeRepository.findOne({ where: { code } });
if (existing) {
return this.generateRandomCode();
}
return code;
}
}

278
migrate-production.sh Executable file
View File

@@ -0,0 +1,278 @@
#!/bin/bash
# ParentFlow Production Database Migration Script
# Runs all database migrations for both main app and admin dashboard
set -e
# Configuration
DB_HOST="10.0.0.207"
DB_PORT="5432"
DB_USER="postgres"
DB_PASSWORD="a3ppq"
DB_NAME="parentflow"
DB_NAME_ADMIN="parentflowadmin"
# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
exit 1
}
success() {
echo -e "${GREEN}${NC} $1"
}
warning() {
echo -e "${YELLOW}${NC} $1"
}
# Header
echo ""
echo "=========================================="
echo " Database Migration for Production "
echo "=========================================="
echo ""
# Check PostgreSQL client
if ! command -v psql &> /dev/null; then
error "PostgreSQL client not installed. Run: apt-get install postgresql-client"
fi
# Test database connection
log "Testing database connection..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres -c "SELECT version();" > /dev/null 2>&1
if [ $? -ne 0 ]; then
error "Cannot connect to database at $DB_HOST:$DB_PORT"
fi
success "Database connection successful"
# Create databases if they don't exist
log "Ensuring databases exist..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d postgres << EOF
-- Create main database
SELECT 'CREATE DATABASE ${DB_NAME}'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${DB_NAME}')\\gexec
-- Create admin database
SELECT 'CREATE DATABASE ${DB_NAME_ADMIN}'
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '${DB_NAME_ADMIN}')\\gexec
EOF
success "Databases verified"
# Enable extensions
log "Enabling required extensions..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -c "CREATE EXTENSION IF NOT EXISTS vector;"
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME_ADMIN -c "CREATE EXTENSION IF NOT EXISTS \"uuid-ossp\";"
success "Extensions enabled"
# Find migration directory
MIGRATION_DIR="$(dirname "$0")/maternal-app/maternal-app-backend/src/database/migrations"
if [ ! -d "$MIGRATION_DIR" ]; then
error "Migration directory not found: $MIGRATION_DIR"
fi
# Create migration tracking table
log "Creating migration tracking table..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME << 'EOF'
CREATE TABLE IF NOT EXISTS schema_migrations (
id SERIAL PRIMARY KEY,
version VARCHAR(255) NOT NULL UNIQUE,
executed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
execution_time_ms INTEGER,
success BOOLEAN DEFAULT true,
error_message TEXT,
checksum VARCHAR(64)
);
CREATE INDEX IF NOT EXISTS idx_schema_migrations_version ON schema_migrations(version);
CREATE INDEX IF NOT EXISTS idx_schema_migrations_executed ON schema_migrations(executed_at);
EOF
success "Migration tracking table ready"
# Define all migrations in order
MIGRATIONS=(
"V001_create_core_auth.sql"
"V002_create_family_structure.sql"
"V003_create_child_entities.sql"
"V004_create_activity_tables.sql"
"V005_create_notification_system.sql"
"V006_create_audit_log.sql"
"V007_create_analytics_tables.sql"
"V008_add_verification_system.sql"
"V008_add_eula_fields.sql"
"V009_add_family_preferences.sql"
"V009_add_multi_child_preferences.sql"
"V010_enhance_notifications.sql"
"V010_add_ai_conversations.sql"
"V011_add_tracking_enhancements.sql"
"V011_create_photos_module.sql"
"V012_add_device_registry.sql"
"V013_add_mfa_support.sql"
"V014_add_refresh_token_rotation.sql"
"V015_add_audit_fields.sql"
"V016_add_webauthn_support.sql"
"V017_add_gdpr_compliance.sql"
"V018_add_ai_embeddings.sql"
"V019_add_voice_feedback.sql"
"V020_add_indexes_optimization.sql"
"V021_add_timezone_support.sql"
"V022_add_data_archiving.sql"
"V028_create_invite_codes.sql"
)
# Function to calculate file checksum
calculate_checksum() {
local file=$1
if command -v sha256sum &> /dev/null; then
sha256sum "$file" | cut -d' ' -f1
else
echo "no-checksum"
fi
}
# Run migrations
log "Running migrations for main database..."
TOTAL=${#MIGRATIONS[@]}
CURRENT=0
SKIPPED=0
EXECUTED=0
for migration in "${MIGRATIONS[@]}"; do
CURRENT=$((CURRENT + 1))
MIGRATION_FILE="$MIGRATION_DIR/$migration"
if [ ! -f "$MIGRATION_FILE" ]; then
warning "[$CURRENT/$TOTAL] Migration file not found: $migration"
continue
fi
# Check if migration was already executed
VERSION=$(echo $migration | cut -d'_' -f1)
ALREADY_RUN=$(PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -tAc \
"SELECT COUNT(*) FROM schema_migrations WHERE version = '$VERSION';")
if [ "$ALREADY_RUN" = "1" ]; then
echo -e "${YELLOW}[$CURRENT/$TOTAL]${NC} Skipping $migration (already applied)"
SKIPPED=$((SKIPPED + 1))
continue
fi
echo -e "${BLUE}[$CURRENT/$TOTAL]${NC} Applying $migration..."
START_TIME=$(date +%s%3N)
CHECKSUM=$(calculate_checksum "$MIGRATION_FILE")
# Run migration
if PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -f "$MIGRATION_FILE" > /dev/null 2>&1; then
END_TIME=$(date +%s%3N)
EXEC_TIME=$((END_TIME - START_TIME))
# Record successful migration
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME << EOF
INSERT INTO schema_migrations (version, execution_time_ms, checksum)
VALUES ('$VERSION', $EXEC_TIME, '$CHECKSUM');
EOF
success "Applied $migration (${EXEC_TIME}ms)"
EXECUTED=$((EXECUTED + 1))
else
error "Failed to apply migration: $migration"
fi
done
log "Migration summary: $EXECUTED executed, $SKIPPED skipped, $TOTAL total"
# Run admin-specific migrations if needed
log "Setting up admin database..."
PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME_ADMIN << 'EOF'
-- Admin users table (if not exists from main DB)
CREATE TABLE IF NOT EXISTS admin_users (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
name VARCHAR(100),
role VARCHAR(50) DEFAULT 'admin',
is_active BOOLEAN DEFAULT true,
last_login_at TIMESTAMP WITH TIME ZONE,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
permissions JSONB DEFAULT '["users:read", "users:write", "invites:read", "invites:write", "analytics:read"]',
two_factor_secret VARCHAR(255),
two_factor_enabled BOOLEAN DEFAULT false
);
-- Admin sessions
CREATE TABLE IF NOT EXISTS admin_sessions (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
admin_user_id VARCHAR(36) REFERENCES admin_users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL UNIQUE,
ip_address VARCHAR(45),
user_agent TEXT,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
last_activity_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Admin audit logs
CREATE TABLE IF NOT EXISTS admin_audit_logs (
id VARCHAR(36) PRIMARY KEY DEFAULT gen_random_uuid()::text,
admin_user_id VARCHAR(36) REFERENCES admin_users(id),
action VARCHAR(100) NOT NULL,
entity_type VARCHAR(50),
entity_id VARCHAR(36),
details JSONB DEFAULT '{}',
ip_address VARCHAR(45),
user_agent TEXT,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Create indexes
CREATE INDEX IF NOT EXISTS idx_admin_users_email ON admin_users(email);
CREATE INDEX IF NOT EXISTS idx_admin_sessions_token ON admin_sessions(token_hash);
CREATE INDEX IF NOT EXISTS idx_admin_sessions_admin ON admin_sessions(admin_user_id);
CREATE INDEX IF NOT EXISTS idx_admin_audit_logs_admin ON admin_audit_logs(admin_user_id);
CREATE INDEX IF NOT EXISTS idx_admin_audit_logs_created ON admin_audit_logs(created_at);
-- Insert default admin user if not exists (password: admin123)
INSERT INTO admin_users (email, password_hash, name, role)
VALUES (
'admin@parentflowapp.com',
'$2b$10$H5hw3/iwkCichU5dpVIMqe5Me7WV9jz.qWRm0V4JyGF9smgxgFBxm',
'System Administrator',
'super_admin'
) ON CONFLICT (email) DO NOTHING;
EOF
success "Admin database configured"
# Verify migration status
log "Verifying migration status..."
TOTAL_APPLIED=$(PGPASSWORD=$DB_PASSWORD psql -h $DB_HOST -p $DB_PORT -U $DB_USER -d $DB_NAME -tAc \
"SELECT COUNT(*) FROM schema_migrations WHERE success = true;")
echo ""
echo "=========================================="
echo -e "${GREEN} Database Migration Completed! ${NC}"
echo "=========================================="
echo ""
echo "Summary:"
echo " Total migrations: $TOTAL"
echo " Applied in this run: $EXECUTED"
echo " Previously applied: $SKIPPED"
echo " Total in database: $TOTAL_APPLIED"
echo ""
echo "Databases ready:"
echo " Main: $DB_NAME at $DB_HOST:$DB_PORT"
echo " Admin: $DB_NAME_ADMIN at $DB_HOST:$DB_PORT"
echo ""
success "All migrations completed successfully"

41
parentflow-admin/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

View File

@@ -0,0 +1,36 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file.
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.

View File

@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;

3564
parentflow-admin/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,34 @@
{
"name": "parentflow-admin",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev -p 3335 -H 0.0.0.0",
"build": "next build",
"start": "next start -p 3335"
},
"dependencies": {
"@emotion/react": "^11.14.0",
"@emotion/styled": "^11.14.1",
"@mui/icons-material": "^7.3.4",
"@mui/material": "^7.3.4",
"@mui/material-nextjs": "^7.3.3",
"@mui/x-charts": "^8.13.1",
"@mui/x-data-grid": "^8.13.1",
"@tanstack/react-query": "^5.90.2",
"axios": "^1.12.2",
"date-fns": "^4.1.0",
"next": "15.5.4",
"react": "19.1.0",
"react-dom": "19.1.0",
"recharts": "^3.2.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"tailwindcss": "^4",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;

View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,26 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}

View File

@@ -0,0 +1,393 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Paper,
Button,
Typography,
IconButton,
Chip,
Dialog,
DialogTitle,
DialogContent,
DialogActions,
TextField,
FormControlLabel,
Switch,
Alert,
Tooltip,
Grid,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import {
Add,
Edit,
Delete,
ContentCopy,
Refresh,
} from '@mui/icons-material';
import { format } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
interface InviteCode {
id: string;
code: string;
uses: number;
maxUses: number | null;
expiresAt: string | null;
createdAt: string;
createdBy: string;
isActive: boolean;
metadata?: any;
}
export default function InviteCodesPage() {
const [inviteCodes, setInviteCodes] = useState<InviteCode[]>([]);
const [loading, setLoading] = useState(true);
const [openDialog, setOpenDialog] = useState(false);
const [editingCode, setEditingCode] = useState<InviteCode | null>(null);
const [copied, setCopied] = useState<string | null>(null);
// Form state
const [formData, setFormData] = useState({
code: '',
maxUses: '',
hasExpiry: false,
expiresAt: '',
description: '',
});
const fetchInviteCodes = async () => {
setLoading(true);
try {
const data = await apiClient.getInviteCodes();
setInviteCodes(data.codes || []);
} catch (error) {
console.error('Failed to fetch invite codes:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchInviteCodes();
}, []);
const generateRandomCode = () => {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
let code = '';
for (let i = 0; i < 8; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
if (i === 3) code += '-';
}
setFormData({ ...formData, code });
};
const handleCopyCode = (code: string) => {
navigator.clipboard.writeText(code);
setCopied(code);
setTimeout(() => setCopied(null), 2000);
};
const handleSubmit = async () => {
try {
const payload = {
code: formData.code,
maxUses: formData.maxUses ? parseInt(formData.maxUses) : undefined,
expiresAt: formData.hasExpiry ? formData.expiresAt : undefined,
metadata: formData.description ? { description: formData.description } : undefined,
};
if (editingCode) {
await apiClient.updateInviteCode(editingCode.id, payload);
} else {
await apiClient.createInviteCode(payload);
}
fetchInviteCodes();
handleCloseDialog();
} catch (error) {
console.error('Failed to save invite code:', error);
}
};
const handleDelete = async (id: string) => {
if (confirm('Are you sure you want to delete this invite code?')) {
try {
await apiClient.deleteInviteCode(id);
fetchInviteCodes();
} catch (error) {
console.error('Failed to delete invite code:', error);
}
}
};
const handleCloseDialog = () => {
setOpenDialog(false);
setEditingCode(null);
setFormData({
code: '',
maxUses: '',
hasExpiry: false,
expiresAt: '',
description: '',
});
};
const columns: GridColDef[] = [
{
field: 'code',
headerName: 'Code',
width: 150,
renderCell: (params) => (
<Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
<Typography variant="body2" sx={{ fontFamily: 'monospace', fontWeight: 500 }}>
{params.value}
</Typography>
<Tooltip title={copied === params.value ? 'Copied!' : 'Copy code'}>
<IconButton size="small" onClick={() => handleCopyCode(params.value)}>
<ContentCopy fontSize="small" />
</IconButton>
</Tooltip>
</Box>
),
},
{
field: 'status',
headerName: 'Status',
width: 120,
renderCell: (params) => {
const isExpired = params.row.expiresAt && new Date(params.row.expiresAt) < new Date();
const isMaxedOut = params.row.maxUses && params.row.uses >= params.row.maxUses;
if (!params.row.isActive) {
return <Chip label="Inactive" size="small" color="default" />;
} else if (isExpired) {
return <Chip label="Expired" size="small" color="error" />;
} else if (isMaxedOut) {
return <Chip label="Used Up" size="small" color="warning" />;
}
return <Chip label="Active" size="small" color="success" />;
},
},
{
field: 'uses',
headerName: 'Uses',
width: 100,
renderCell: (params) => (
<Typography variant="body2">
{params.value} / {params.row.maxUses || '∞'}
</Typography>
),
},
{
field: 'expiresAt',
headerName: 'Expires',
width: 150,
renderCell: (params) => (
<Typography variant="body2">
{params.value ? format(new Date(params.value), 'MMM dd, yyyy') : 'Never'}
</Typography>
),
},
{
field: 'createdAt',
headerName: 'Created',
width: 150,
renderCell: (params) => (
<Typography variant="body2">
{format(new Date(params.value), 'MMM dd, yyyy')}
</Typography>
),
},
{
field: 'actions',
headerName: 'Actions',
width: 100,
sortable: false,
renderCell: (params) => (
<Box>
<IconButton size="small" onClick={() => {
setEditingCode(params.row);
setFormData({
code: params.row.code,
maxUses: params.row.maxUses?.toString() || '',
hasExpiry: !!params.row.expiresAt,
expiresAt: params.row.expiresAt || '',
description: params.row.metadata?.description || '',
});
setOpenDialog(true);
}}>
<Edit fontSize="small" />
</IconButton>
<IconButton size="small" onClick={() => handleDelete(params.row.id)} color="error">
<Delete fontSize="small" />
</IconButton>
</Box>
),
},
];
return (
<AdminLayout>
<Box>
<Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Typography variant="h5" fontWeight={600}>
Invite Codes Management
</Typography>
<Box sx={{ display: 'flex', gap: 1 }}>
<Button
startIcon={<Refresh />}
onClick={fetchInviteCodes}
variant="outlined"
>
Refresh
</Button>
<Button
startIcon={<Add />}
variant="contained"
onClick={() => setOpenDialog(true)}
>
Create Invite Code
</Button>
</Box>
</Box>
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Total Codes
</Typography>
<Typography variant="h4">{inviteCodes.length}</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Active Codes
</Typography>
<Typography variant="h4">
{inviteCodes.filter(c => c.isActive).length}
</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Total Uses
</Typography>
<Typography variant="h4">
{inviteCodes.reduce((sum, c) => sum + c.uses, 0)}
</Typography>
</Paper>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<Paper sx={{ p: 2 }}>
<Typography variant="body2" color="text.secondary" gutterBottom>
Available
</Typography>
<Typography variant="h4">
{inviteCodes.filter(c => {
const isExpired = c.expiresAt && new Date(c.expiresAt) < new Date();
const isMaxedOut = c.maxUses && c.uses >= c.maxUses;
return c.isActive && !isExpired && !isMaxedOut;
}).length}
</Typography>
</Paper>
</Grid>
</Grid>
<Paper sx={{ p: 2 }}>
<DataGrid
rows={inviteCodes}
columns={columns}
loading={loading}
pageSizeOptions={[10, 25, 50]}
initialState={{
pagination: { paginationModel: { pageSize: 10 } },
}}
disableRowSelectionOnClick
autoHeight
/>
</Paper>
<Dialog open={openDialog} onClose={handleCloseDialog} maxWidth="sm" fullWidth>
<DialogTitle>
{editingCode ? 'Edit Invite Code' : 'Create New Invite Code'}
</DialogTitle>
<DialogContent>
<Box sx={{ display: 'flex', flexDirection: 'column', gap: 2, pt: 1 }}>
<Box sx={{ display: 'flex', gap: 1 }}>
<TextField
label="Invite Code"
value={formData.code}
onChange={(e) => setFormData({ ...formData, code: e.target.value })}
fullWidth
required
placeholder="ABCD-1234"
/>
<Button onClick={generateRandomCode} variant="outlined">
Generate
</Button>
</Box>
<TextField
label="Max Uses (leave empty for unlimited)"
type="number"
value={formData.maxUses}
onChange={(e) => setFormData({ ...formData, maxUses: e.target.value })}
fullWidth
InputProps={{ inputProps: { min: 1 } }}
/>
<FormControlLabel
control={
<Switch
checked={formData.hasExpiry}
onChange={(e) => setFormData({ ...formData, hasExpiry: e.target.checked })}
/>
}
label="Set expiration date"
/>
{formData.hasExpiry && (
<TextField
label="Expires At"
type="datetime-local"
value={formData.expiresAt}
onChange={(e) => setFormData({ ...formData, expiresAt: e.target.value })}
fullWidth
InputLabelProps={{ shrink: true }}
/>
)}
<TextField
label="Description (optional)"
value={formData.description}
onChange={(e) => setFormData({ ...formData, description: e.target.value })}
fullWidth
multiline
rows={2}
placeholder="e.g., Beta testers group"
/>
<Alert severity="info">
Share this code with users to allow them to register.
The code can be used during the signup process.
</Alert>
</Box>
</DialogContent>
<DialogActions>
<Button onClick={handleCloseDialog}>Cancel</Button>
<Button onClick={handleSubmit} variant="contained" disabled={!formData.code}>
{editingCode ? 'Update' : 'Create'}
</Button>
</DialogActions>
</Dialog>
</Box>
</AdminLayout>
);
}

View File

@@ -0,0 +1,30 @@
import type { Metadata } from 'next';
import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
import { ThemeProvider } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import theme from '@/lib/theme';
import './globals.css';
export const metadata: Metadata = {
title: 'ParentFlow Admin Dashboard',
description: 'Admin dashboard for managing ParentFlow application',
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body>
<AppRouterCacheProvider>
<ThemeProvider theme={theme}>
<CssBaseline />
{children}
</ThemeProvider>
</AppRouterCacheProvider>
</body>
</html>
);
}

View File

@@ -0,0 +1,105 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import {
Container,
Paper,
TextField,
Button,
Typography,
Box,
Alert,
CircularProgress,
} from '@mui/material';
import { LockOutlined } from '@mui/icons-material';
import apiClient from '@/lib/api-client';
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
setLoading(true);
try {
await apiClient.login(email, password);
router.push('/');
} catch (err: any) {
setError(err.response?.data?.message || 'Login failed. Please check your credentials.');
} finally {
setLoading(false);
}
};
return (
<Container component="main" maxWidth="sm" sx={{ minHeight: '100vh', display: 'flex', alignItems: 'center' }}>
<Paper elevation={3} sx={{ p: 4, width: '100%', borderRadius: 2 }}>
<Box sx={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Box sx={{ mb: 2, p: 1.5, borderRadius: '50%', bgcolor: 'primary.main' }}>
<LockOutlined sx={{ color: 'white', fontSize: 30 }} />
</Box>
<Typography component="h1" variant="h4" sx={{ mb: 1, fontWeight: 600 }}>
Admin Login
</Typography>
<Typography variant="body2" color="text.secondary" sx={{ mb: 3 }}>
ParentFlow Admin Dashboard
</Typography>
{error && (
<Alert severity="error" sx={{ width: '100%', mb: 2 }}>
{error}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit} sx={{ width: '100%' }}>
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={loading}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
value={password}
onChange={(e) => setPassword(e.target.value)}
disabled={loading}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2, py: 1.5 }}
disabled={loading}
>
{loading ? <CircularProgress size={24} /> : 'Sign In'}
</Button>
</Box>
</Box>
</Paper>
</Container>
);
}

View File

@@ -0,0 +1,393 @@
'use client';
import { useState, useEffect } from 'react';
import {
Box,
Grid,
Paper,
Typography,
Card,
CardContent,
LinearProgress,
List,
ListItem,
ListItemText,
ListItemAvatar,
Avatar,
Chip,
IconButton,
} from '@mui/material';
import {
People,
FamilyRestroom,
ChildCare,
TrendingUp,
Warning,
CheckCircle,
Refresh,
AccessTime,
} from '@mui/icons-material';
import { LineChart, Line, AreaChart, Area, BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, PieChart, Pie, Cell } from 'recharts';
import { format, subDays, startOfDay } from 'date-fns';
import AdminLayout from '@/components/AdminLayout';
import apiClient from '@/lib/api-client';
interface DashboardStats {
totalUsers: number;
totalFamilies: number;
totalChildren: number;
activeUsers: number;
newUsersToday: number;
activitiesLogged: number;
aiQueriesTotal: number;
systemStatus: 'healthy' | 'warning' | 'error';
}
const COLORS = ['#FF8B7D', '#FFB5A0', '#FFD4CC', '#81C784', '#FFB74D'];
export default function DashboardPage() {
const [stats, setStats] = useState<DashboardStats>({
totalUsers: 0,
totalFamilies: 0,
totalChildren: 0,
activeUsers: 0,
newUsersToday: 0,
activitiesLogged: 0,
aiQueriesTotal: 0,
systemStatus: 'healthy',
});
const [loading, setLoading] = useState(true);
const [userGrowthData, setUserGrowthData] = useState<any[]>([]);
const [activityData, setActivityData] = useState<any[]>([]);
const [recentUsers, setRecentUsers] = useState<any[]>([]);
const fetchDashboardData = async () => {
setLoading(true);
try {
// Simulate API calls - replace with actual calls
const analyticsData = await apiClient.getAnalytics();
const growthData = await apiClient.getUserGrowth();
const activityStats = await apiClient.getActivityStats();
// Mock data for now - replace with actual API response
setStats({
totalUsers: 1250,
totalFamilies: 420,
totalChildren: 680,
activeUsers: 890,
newUsersToday: 23,
activitiesLogged: 15420,
aiQueriesTotal: 3250,
systemStatus: 'healthy',
});
// Mock user growth data
const mockGrowthData = Array.from({ length: 30 }, (_, i) => {
const date = subDays(new Date(), 29 - i);
return {
date: format(date, 'MMM dd'),
users: Math.floor(Math.random() * 50) + 20,
activities: Math.floor(Math.random() * 200) + 100,
};
});
setUserGrowthData(mockGrowthData);
// Mock activity distribution
setActivityData([
{ name: 'Feeding', value: 4500, color: '#FF8B7D' },
{ name: 'Sleep', value: 3200, color: '#FFB5A0' },
{ name: 'Diapers', value: 2800, color: '#FFD4CC' },
{ name: 'Milestones', value: 1200, color: '#81C784' },
{ name: 'Other', value: 3720, color: '#FFB74D' },
]);
// Mock recent users
setRecentUsers([
{ id: 1, name: 'Sarah Johnson', email: 'sarah@example.com', joinedAt: new Date() },
{ id: 2, name: 'Mike Chen', email: 'mike@example.com', joinedAt: new Date() },
{ id: 3, name: 'Emma Davis', email: 'emma@example.com', joinedAt: new Date() },
]);
} catch (error) {
console.error('Failed to fetch dashboard data:', error);
// Use mock data even on error for development
setStats({
totalUsers: 1250,
totalFamilies: 420,
totalChildren: 680,
activeUsers: 890,
newUsersToday: 23,
activitiesLogged: 15420,
aiQueriesTotal: 3250,
systemStatus: 'healthy',
});
const mockGrowthData = Array.from({ length: 30 }, (_, i) => {
const date = subDays(new Date(), 29 - i);
return {
date: format(date, 'MMM dd'),
users: Math.floor(Math.random() * 50) + 20,
activities: Math.floor(Math.random() * 200) + 100,
};
});
setUserGrowthData(mockGrowthData);
setActivityData([
{ name: 'Feeding', value: 4500, color: '#FF8B7D' },
{ name: 'Sleep', value: 3200, color: '#FFB5A0' },
{ name: 'Diapers', value: 2800, color: '#FFD4CC' },
{ name: 'Milestones', value: 1200, color: '#81C784' },
{ name: 'Other', value: 3720, color: '#FFB74D' },
]);
setRecentUsers([
{ id: 1, name: 'Sarah Johnson', email: 'sarah@example.com', joinedAt: new Date() },
{ id: 2, name: 'Mike Chen', email: 'mike@example.com', joinedAt: new Date() },
{ id: 3, name: 'Emma Davis', email: 'emma@example.com', joinedAt: new Date() },
]);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchDashboardData();
}, []);
const StatCard = ({ icon, title, value, change, color }: any) => (
<Card sx={{ height: '100%' }}>
<CardContent>
<Box sx={{ display: 'flex', alignItems: 'center', mb: 2 }}>
<Avatar sx={{ bgcolor: `${color}.light`, color: `${color}.main`, mr: 2 }}>
{icon}
</Avatar>
<Box sx={{ flexGrow: 1 }}>
<Typography color="text.secondary" variant="body2">
{title}
</Typography>
<Typography variant="h4" fontWeight={600}>
{value.toLocaleString()}
</Typography>
{change && (
<Typography
variant="caption"
sx={{ color: change > 0 ? 'success.main' : 'error.main' }}
>
{change > 0 ? '+' : ''}{change}% from yesterday
</Typography>
)}
</Box>
</Box>
</CardContent>
</Card>
);
if (loading) {
return (
<AdminLayout>
<LinearProgress />
</AdminLayout>
);
}
return (
<AdminLayout>
<Box>
<Box sx={{ mb: 3, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<Box>
<Typography variant="h5" fontWeight={600}>
Dashboard Overview
</Typography>
<Typography variant="body2" color="text.secondary">
Welcome back! Here's what's happening with ParentFlow today.
</Typography>
</Box>
<IconButton onClick={fetchDashboardData}>
<Refresh />
</IconButton>
</Box>
{/* Stats Cards */}
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<People />}
title="Total Users"
value={stats.totalUsers}
change={5.2}
color="primary"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<FamilyRestroom />}
title="Families"
value={stats.totalFamilies}
change={3.1}
color="secondary"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<ChildCare />}
title="Children"
value={stats.totalChildren}
change={4.5}
color="info"
/>
</Grid>
<Grid item xs={12} sm={6} md={3}>
<StatCard
icon={<TrendingUp />}
title="Activities Today"
value={stats.activitiesLogged}
change={12.3}
color="success"
/>
</Grid>
</Grid>
{/* Charts Row */}
<Grid container spacing={3} sx={{ mb: 3 }}>
<Grid item xs={12} md={8}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
User Growth (Last 30 Days)
</Typography>
<ResponsiveContainer width="100%" height={300}>
<AreaChart data={userGrowthData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Area
type="monotone"
dataKey="users"
stroke="#FF8B7D"
fill="#FFB5A0"
fillOpacity={0.6}
/>
</AreaChart>
</ResponsiveContainer>
</Paper>
</Grid>
<Grid item xs={12} md={4}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Activity Distribution
</Typography>
<ResponsiveContainer width="100%" height={300}>
<PieChart>
<Pie
data={activityData}
cx="50%"
cy="50%"
labelLine={false}
label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{activityData.map((entry, index) => (
<Cell key={`cell-${index}`} fill={entry.color} />
))}
</Pie>
<Tooltip />
</PieChart>
</ResponsiveContainer>
</Paper>
</Grid>
</Grid>
{/* Recent Activity and System Status */}
<Grid container spacing={3}>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
Recent Users
</Typography>
<List>
{recentUsers.map((user) => (
<ListItem key={user.id}>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'primary.main' }}>
{user.name.charAt(0)}
</Avatar>
</ListItemAvatar>
<ListItemText
primary={user.name}
secondary={user.email}
/>
<Chip
icon={<AccessTime />}
label="New"
size="small"
color="success"
variant="outlined"
/>
</ListItem>
))}
</List>
</Paper>
</Grid>
<Grid item xs={12} md={6}>
<Paper sx={{ p: 3 }}>
<Typography variant="h6" gutterBottom>
System Status
</Typography>
<List>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="API Server"
secondary="Responding normally"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="Database"
secondary="10.0.0.207 - Connected"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'success.light' }}>
<CheckCircle color="success" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="Redis Cache"
secondary="Active connections: 12"
/>
<Chip label="Healthy" color="success" size="small" />
</ListItem>
<ListItem>
<ListItemAvatar>
<Avatar sx={{ bgcolor: 'warning.light' }}>
<Warning color="warning" />
</Avatar>
</ListItemAvatar>
<ListItemText
primary="AI Service"
secondary="High usage - 85% of quota"
/>
<Chip label="Warning" color="warning" size="small" />
</ListItem>
</List>
</Paper>
</Grid>
</Grid>
</Box>
</AdminLayout>
);
}

View File

@@ -0,0 +1,196 @@
'use client';
import { useState, ReactNode } from 'react';
import { useRouter, usePathname } from 'next/navigation';
import {
Box,
Drawer,
AppBar,
Toolbar,
List,
Typography,
IconButton,
ListItem,
ListItemButton,
ListItemIcon,
ListItemText,
Avatar,
Menu,
MenuItem,
Divider,
Chip,
} from '@mui/material';
import {
Menu as MenuIcon,
Dashboard,
People,
ConfirmationNumber,
Analytics,
Settings,
Logout,
FamilyRestroom,
HealthAndSafety,
} from '@mui/icons-material';
import apiClient from '@/lib/api-client';
const drawerWidth = 240;
interface AdminLayoutProps {
children: ReactNode;
}
export default function AdminLayout({ children }: AdminLayoutProps) {
const router = useRouter();
const pathname = usePathname();
const [mobileOpen, setMobileOpen] = useState(false);
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const handleDrawerToggle = () => {
setMobileOpen(!mobileOpen);
};
const handleLogout = async () => {
await apiClient.logout();
router.push('/login');
};
const menuItems = [
{ text: 'Dashboard', icon: <Dashboard />, path: '/' },
{ text: 'Users', icon: <People />, path: '/users' },
{ text: 'Families', icon: <FamilyRestroom />, path: '/families' },
{ text: 'Invite Codes', icon: <ConfirmationNumber />, path: '/invite-codes' },
{ text: 'Analytics', icon: <Analytics />, path: '/analytics' },
{ text: 'System Health', icon: <HealthAndSafety />, path: '/health' },
{ text: 'Settings', icon: <Settings />, path: '/settings' },
];
const drawer = (
<Box>
<Toolbar sx={{ justifyContent: 'center', py: 2 }}>
<Typography variant="h6" noWrap sx={{ fontWeight: 600, color: 'primary.main' }}>
ParentFlow Admin
</Typography>
</Toolbar>
<Divider />
<List>
{menuItems.map((item) => (
<ListItem key={item.text} disablePadding>
<ListItemButton
onClick={() => router.push(item.path)}
selected={pathname === item.path}
sx={{
'&.Mui-selected': {
backgroundColor: 'primary.light',
'&:hover': {
backgroundColor: 'primary.light',
},
},
}}
>
<ListItemIcon sx={{ color: pathname === item.path ? 'primary.main' : 'inherit' }}>
{item.icon}
</ListItemIcon>
<ListItemText primary={item.text} />
</ListItemButton>
</ListItem>
))}
</List>
</Box>
);
return (
<Box sx={{ display: 'flex' }}>
<AppBar
position="fixed"
sx={{
width: { sm: `calc(100% - ${drawerWidth}px)` },
ml: { sm: `${drawerWidth}px` },
backgroundColor: 'white',
color: 'text.primary',
}}
elevation={1}
>
<Toolbar>
<IconButton
color="inherit"
aria-label="open drawer"
edge="start"
onClick={handleDrawerToggle}
sx={{ mr: 2, display: { sm: 'none' } }}
>
<MenuIcon />
</IconButton>
<Box sx={{ flexGrow: 1 }}>
<Typography variant="h6" noWrap component="div">
{menuItems.find(item => item.path === pathname)?.text || 'Dashboard'}
</Typography>
</Box>
<Chip label="Admin" color="primary" size="small" sx={{ mr: 2 }} />
<IconButton onClick={(e) => setAnchorEl(e.currentTarget)}>
<Avatar sx={{ bgcolor: 'primary.main', width: 32, height: 32 }}>A</Avatar>
</IconButton>
<Menu
anchorEl={anchorEl}
open={Boolean(anchorEl)}
onClose={() => setAnchorEl(null)}
>
<MenuItem onClick={handleLogout}>
<ListItemIcon>
<Logout fontSize="small" />
</ListItemIcon>
Logout
</MenuItem>
</Menu>
</Toolbar>
</AppBar>
<Box
component="nav"
sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}
>
<Drawer
variant="temporary"
open={mobileOpen}
onClose={handleDrawerToggle}
ModalProps={{
keepMounted: true, // Better open performance on mobile
}}
sx={{
display: { xs: 'block', sm: 'none' },
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
>
{drawer}
</Drawer>
<Drawer
variant="permanent"
sx={{
display: { xs: 'none', sm: 'block' },
'& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
}}
open
>
{drawer}
</Drawer>
</Box>
<Box
component="main"
sx={{
flexGrow: 1,
p: 3,
width: { sm: `calc(100% - ${drawerWidth}px)` },
mt: 8,
backgroundColor: 'background.default',
minHeight: '100vh',
}}
>
{children}
</Box>
</Box>
);
}

View File

@@ -0,0 +1,183 @@
import axios from 'axios';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3020/api/v1';
class ApiClient {
private token: string | null = null;
private refreshToken: string | null = null;
constructor() {
// Initialize tokens from localStorage if available
if (typeof window !== 'undefined') {
this.token = localStorage.getItem('admin_access_token');
this.refreshToken = localStorage.getItem('admin_refresh_token');
}
}
setTokens(accessToken: string, refreshToken: string) {
this.token = accessToken;
this.refreshToken = refreshToken;
if (typeof window !== 'undefined') {
localStorage.setItem('admin_access_token', accessToken);
localStorage.setItem('admin_refresh_token', refreshToken);
}
}
clearTokens() {
this.token = null;
this.refreshToken = null;
if (typeof window !== 'undefined') {
localStorage.removeItem('admin_access_token');
localStorage.removeItem('admin_refresh_token');
}
}
private async request(method: string, endpoint: string, data?: any, options?: any) {
const config = {
method,
url: `${API_BASE_URL}${endpoint}`,
headers: {
'Content-Type': 'application/json',
...(this.token ? { Authorization: `Bearer ${this.token}` } : {}),
...options?.headers,
},
...options,
};
if (data) {
config.data = data;
}
try {
const response = await axios(config);
return response.data;
} catch (error: any) {
// Handle token refresh
if (error.response?.status === 401 && this.refreshToken) {
try {
const refreshResponse = await axios.post(`${API_BASE_URL}/auth/refresh`, {
refreshToken: this.refreshToken,
});
this.setTokens(refreshResponse.data.accessToken, refreshResponse.data.refreshToken);
// Retry original request
config.headers.Authorization = `Bearer ${this.token}`;
const response = await axios(config);
return response.data;
} catch (refreshError) {
this.clearTokens();
window.location.href = '/login';
throw refreshError;
}
}
throw error;
}
}
// Auth endpoints
async login(email: string, password: string) {
const response = await this.request('POST', '/admin/auth/login', { email, password });
this.setTokens(response.accessToken, response.refreshToken);
return response;
}
async logout() {
try {
await this.request('POST', '/admin/auth/logout');
} finally {
this.clearTokens();
}
}
async getCurrentAdmin() {
return this.request('GET', '/admin/auth/me');
}
// User management endpoints
async getUsers(params?: { page?: number; limit?: number; search?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/users${queryString}`);
}
async getUserById(id: string) {
return this.request('GET', `/admin/users/${id}`);
}
async updateUser(id: string, data: any) {
return this.request('PATCH', `/admin/users/${id}`, data);
}
async deleteUser(id: string) {
return this.request('DELETE', `/admin/users/${id}`);
}
// Invite code endpoints
async getInviteCodes(params?: { page?: number; limit?: number; status?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/invite-codes${queryString}`);
}
async createInviteCode(data: {
code: string;
maxUses?: number;
expiresAt?: string;
metadata?: any;
}) {
return this.request('POST', '/admin/invite-codes', data);
}
async updateInviteCode(id: string, data: any) {
return this.request('PATCH', `/admin/invite-codes/${id}`, data);
}
async deleteInviteCode(id: string) {
return this.request('DELETE', `/admin/invite-codes/${id}`);
}
// Analytics endpoints
async getAnalytics(params?: { startDate?: string; endDate?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/analytics${queryString}`);
}
async getUserGrowth() {
return this.request('GET', '/admin/analytics/user-growth');
}
async getActivityStats() {
return this.request('GET', '/admin/analytics/activity-stats');
}
async getSystemHealth() {
return this.request('GET', '/admin/analytics/system-health');
}
// Family management
async getFamilies(params?: { page?: number; limit?: number; search?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/families${queryString}`);
}
async getFamilyById(id: string) {
return this.request('GET', `/admin/families/${id}`);
}
// Activity logs
async getActivityLogs(params?: { page?: number; limit?: number; userId?: string }) {
const queryString = params ? '?' + new URLSearchParams(params as any).toString() : '';
return this.request('GET', `/admin/logs${queryString}`);
}
// System settings
async getSettings() {
return this.request('GET', '/admin/settings');
}
async updateSettings(data: any) {
return this.request('PATCH', '/admin/settings', data);
}
}
export const apiClient = new ApiClient();
export default apiClient;

View File

@@ -0,0 +1,106 @@
import { createTheme } from '@mui/material/styles';
const theme = createTheme({
palette: {
mode: 'light',
primary: {
main: '#FF8B7D',
light: '#FFB5A0',
dark: '#FF6B59',
contrastText: '#FFFFFF',
},
secondary: {
main: '#FFD4CC',
light: '#FFE8E4',
dark: '#FFB5A0',
contrastText: '#2C2C2C',
},
success: {
main: '#81C784',
light: '#A5D6A7',
dark: '#66BB6A',
},
warning: {
main: '#FFB74D',
light: '#FFCC80',
dark: '#FFA726',
},
error: {
main: '#FF8A80',
light: '#FFAB91',
dark: '#FF7961',
},
background: {
default: '#FFF8F5',
paper: '#FFFFFF',
},
text: {
primary: '#2C2C2C',
secondary: '#5E5E5E',
},
},
typography: {
fontFamily: '"Inter", "Roboto", "Helvetica", "Arial", sans-serif',
h1: {
fontSize: '2.5rem',
fontWeight: 600,
lineHeight: 1.2,
},
h2: {
fontSize: '2rem',
fontWeight: 600,
lineHeight: 1.3,
},
h3: {
fontSize: '1.75rem',
fontWeight: 500,
lineHeight: 1.4,
},
h4: {
fontSize: '1.5rem',
fontWeight: 500,
lineHeight: 1.4,
},
h5: {
fontSize: '1.25rem',
fontWeight: 500,
lineHeight: 1.5,
},
h6: {
fontSize: '1rem',
fontWeight: 500,
lineHeight: 1.6,
},
},
shape: {
borderRadius: 12,
},
components: {
MuiButton: {
styleOverrides: {
root: {
textTransform: 'none',
borderRadius: 8,
fontWeight: 500,
},
},
},
MuiCard: {
styleOverrides: {
root: {
borderRadius: 12,
boxShadow: '0 2px 8px rgba(0, 0, 0, 0.08)',
},
},
},
MuiPaper: {
styleOverrides: {
root: {
borderRadius: 12,
},
},
},
},
});
export default theme;

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./src/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}

View File

@@ -1,235 +1,214 @@
#!/bin/bash #!/bin/bash
# ParentFlow Production Startup Script # ParentFlow Production Start Script
# Uses PM2 for frontend/backend, Docker for databases # Starts all production services including backend, frontend, and admin dashboard
# Ports: Backend 3020, Frontend 3030
# Server: 10.0.0.240 (or localhost for local production testing)
set -e # Exit on any error set -e
# Configuration
DEPLOY_DIR="/root/parentflow-production"
DB_HOST="10.0.0.207"
DB_PORT="5432"
# Color codes # Color codes
RED='\033[0;31m' RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
YELLOW='\033[1;33m' YELLOW='\033[1;33m'
BLUE='\033[0;34m' BLUE='\033[0;34m'
NC='\033[0m' # No Color CYAN='\033[0;36m'
NC='\033[0m'
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
exit 1
}
success() {
echo -e "${GREEN}${NC} $1"
}
warning() {
echo -e "${YELLOW}${NC} $1"
}
# Header
echo ""
echo "==========================================" echo "=========================================="
echo "ParentFlow Production Startup" echo " Starting ParentFlow Production "
echo "==========================================" echo "=========================================="
echo "" echo ""
# Check if PM2 is installed # Check if we're in the right directory
if ! command -v pm2 &> /dev/null; then if [ "$PWD" != "$DEPLOY_DIR" ] && [ -d "$DEPLOY_DIR" ]; then
echo -e "${RED}ERROR: PM2 is not installed!${NC}" cd "$DEPLOY_DIR"
echo "Install PM2 globally with: npm install -g pm2"
exit 1
fi fi
# Check if Docker is installed # Step 1: Check database connectivity
if ! command -v docker &> /dev/null; then log "${CYAN}Step 1: Checking database connectivity...${NC}"
echo -e "${RED}ERROR: Docker is not installed!${NC}" PGPASSWORD=a3ppq psql -h $DB_HOST -p $DB_PORT -U postgres -d parentflow \
exit 1 -c "SELECT version();" > /dev/null 2>&1
if [ $? -eq 0 ]; then
success "Database connection successful"
else
error "Cannot connect to database at $DB_HOST:$DB_PORT"
fi fi
# Check if docker-compose is installed # Step 2: Start Docker services
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then log "${CYAN}Step 2: Starting Docker services...${NC}"
echo -e "${RED}ERROR: Docker Compose is not installed!${NC}" if [ -f "docker-compose.production.yml" ]; then
exit 1 if docker compose version &> /dev/null; then
fi
# Step 1: Start Docker services (databases)
echo -e "${BLUE}Step 1: Starting Docker services (databases)...${NC}"
if docker compose version &> /dev/null; then
docker compose -f docker-compose.production.yml up -d docker compose -f docker-compose.production.yml up -d
else else
docker-compose -f docker-compose.production.yml up -d docker-compose -f docker-compose.production.yml up -d
fi
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Docker services started${NC}"
else
echo -e "${RED}✗ Failed to start Docker services${NC}"
exit 1
fi
# Wait for databases to be ready
echo -e "${YELLOW}Waiting for databases to be healthy...${NC}"
sleep 10
# Check PostgreSQL connectivity (dedicated server)
echo -e "${BLUE}Checking PostgreSQL connectivity on 10.0.0.207...${NC}"
PGPASSWORD=a3ppq psql -h 10.0.0.207 -p 5432 -U postgres -d parentflow -c "SELECT version();" > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ PostgreSQL connection successful${NC}"
else
echo -e "${RED}✗ Cannot connect to PostgreSQL on 10.0.0.207${NC}"
echo "Please ensure PostgreSQL is running and accessible"
exit 1
fi
# Check Docker services health
echo -e "${BLUE}Checking Docker services health...${NC}"
MAX_RETRIES=30
RETRY_COUNT=0
while [ $RETRY_COUNT -lt $MAX_RETRIES ]; do
REDIS_HEALTHY=$(docker inspect parentflow-redis-prod --format='{{.State.Health.Status}}' 2>/dev/null || echo "starting")
MONGO_HEALTHY=$(docker inspect parentflow-mongodb-prod --format='{{.State.Health.Status}}' 2>/dev/null || echo "starting")
MINIO_HEALTHY=$(docker inspect parentflow-minio-prod --format='{{.State.Health.Status}}' 2>/dev/null || echo "starting")
if [ "$REDIS_HEALTHY" = "healthy" ] && [ "$MONGO_HEALTHY" = "healthy" ] && [ "$MINIO_HEALTHY" = "healthy" ]; then
echo -e "${GREEN}✓ All Docker services are healthy${NC}"
break
fi fi
sleep 5
echo -e "${YELLOW}Waiting for Docker services... ($RETRY_COUNT/$MAX_RETRIES)${NC}" success "Docker services started (Redis, MongoDB, MinIO)"
sleep 2
((RETRY_COUNT++))
done
if [ $RETRY_COUNT -eq $MAX_RETRIES ]; then
echo -e "${RED}✗ Docker services failed to become healthy${NC}"
echo "Check Docker logs with: docker logs parentflow-redis-prod"
exit 1
fi
# Step 2: Run database migrations
echo ""
echo -e "${BLUE}Step 2: Running database migrations...${NC}"
cd /root/maternal-app/maternal-app/maternal-app-backend
# Check if migration script exists
if [ -f "./scripts/master-migration.sh" ]; then
echo -e "${YELLOW}Running master migration script...${NC}"
DATABASE_HOST=10.0.0.207 \
DATABASE_PORT=5432 \
DATABASE_NAME=parentflow \
DATABASE_USER=postgres \
DATABASE_PASSWORD=a3ppq \
./scripts/master-migration.sh || {
echo -e "${YELLOW}Warning: Migrations may have partially failed. Continuing...${NC}"
}
else else
echo -e "${YELLOW}Warning: Migration script not found. Skipping migrations.${NC}" warning "Docker compose file not found, skipping..."
fi fi
# Step 3: Build backend (if needed) # Step 3: Verify Docker services
echo "" log "${CYAN}Step 3: Verifying Docker services...${NC}"
echo -e "${BLUE}Step 3: Building backend...${NC}" docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep -E "redis|mongo|minio" || warning "Some Docker services may not be running"
cd /root/maternal-app/maternal-app/maternal-app-backend
if [ ! -d "dist" ]; then # Step 4: Start PM2 processes
echo -e "${YELLOW}Building backend for the first time...${NC}" log "${CYAN}Step 4: Starting PM2 application services...${NC}"
npm run build
if [ $? -ne 0 ]; then
echo -e "${RED}✗ Backend build failed${NC}"
exit 1
fi
echo -e "${GREEN}✓ Backend built successfully${NC}"
else
echo -e "${GREEN}✓ Backend dist directory exists${NC}"
fi
# Step 4: Build frontend (if needed) # Delete any existing PM2 processes
echo ""
echo -e "${BLUE}Step 4: Building frontend...${NC}"
cd /root/maternal-app/maternal-web
if [ ! -d ".next" ]; then
echo -e "${YELLOW}Building frontend for the first time...${NC}"
npm run build
if [ $? -ne 0 ]; then
echo -e "${RED}✗ Frontend build failed${NC}"
exit 1
fi
echo -e "${GREEN}✓ Frontend built successfully${NC}"
else
echo -e "${GREEN}✓ Frontend .next directory exists${NC}"
fi
# Step 5: Start PM2 processes
echo ""
echo -e "${BLUE}Step 5: Starting PM2 processes...${NC}"
# Check if ecosystem.config.js exists
if [ ! -f "/root/maternal-app/ecosystem.config.js" ]; then
echo -e "${RED}✗ ecosystem.config.js not found${NC}"
exit 1
fi
# Stop any existing PM2 processes
echo -e "${YELLOW}Stopping any existing PM2 processes...${NC}"
pm2 delete all 2>/dev/null || true pm2 delete all 2>/dev/null || true
# Start PM2 with ecosystem config (production environment) # Start using ecosystem file
cd /root/maternal-app if [ -f "ecosystem.config.js" ]; then
pm2 start ecosystem.config.js --env production pm2 start ecosystem.config.js --env production
success "PM2 services started from ecosystem config"
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ PM2 processes started${NC}"
else else
echo -e "${RED}✗ Failed to start PM2 processes${NC}" warning "PM2 ecosystem config not found, starting services manually..."
exit 1
# Start Backend API
log "Starting Backend API..."
cd "$DEPLOY_DIR/maternal-app/maternal-app-backend"
pm2 start dist/main.js \
--name "parentflow-api" \
--instances 2 \
--exec-mode cluster \
--env production \
--max-memory-restart 500M \
--error /var/log/parentflow/api-error.log \
--output /var/log/parentflow/api-out.log \
--merge-logs \
--time \
-- --port 3020
# Start Frontend
log "Starting Frontend..."
cd "$DEPLOY_DIR/maternal-web"
pm2 start npm \
--name "parentflow-frontend" \
--instances 2 \
--exec-mode cluster \
--max-memory-restart 400M \
--error /var/log/parentflow/frontend-error.log \
--output /var/log/parentflow/frontend-out.log \
--merge-logs \
--time \
-- run start
# Start Admin Dashboard
log "Starting Admin Dashboard..."
cd "$DEPLOY_DIR/parentflow-admin"
pm2 start npm \
--name "parentflow-admin" \
--instances 1 \
--max-memory-restart 300M \
--error /var/log/parentflow/admin-error.log \
--output /var/log/parentflow/admin-out.log \
--merge-logs \
--time \
-- run start
fi fi
# Save PM2 process list # Save PM2 configuration
pm2 save pm2 save
pm2 startup systemd -u root --hp /root || true
# Step 5: Wait for services to start
log "${CYAN}Step 5: Waiting for services to initialize...${NC}"
sleep 10
# Step 6: Verify services are running # Step 6: Verify services are running
echo "" log "${CYAN}Step 6: Verifying services...${NC}"
echo -e "${BLUE}Step 6: Verifying services...${NC}"
sleep 5
# Check PM2 status verify_service() {
echo -e "${YELLOW}PM2 Status:${NC}" local name=$1
local port=$2
if lsof -i:$port > /dev/null 2>&1; then
success "$name is running on port $port"
return 0
else
warning "$name is not detected on port $port"
return 1
fi
}
# Check each service
ALL_GOOD=true
verify_service "Backend API" 3020 || ALL_GOOD=false
verify_service "Frontend" 3030 || ALL_GOOD=false
verify_service "Admin Dashboard" 3335 || ALL_GOOD=false
verify_service "Redis" 6379 || ALL_GOOD=false
verify_service "MongoDB" 27017 || ALL_GOOD=false
verify_service "MinIO" 9000 || ALL_GOOD=false
# Step 7: Show PM2 status
log "${CYAN}Step 7: PM2 Process Status${NC}"
echo ""
pm2 list pm2 list
# Check if ports are listening
echo "" echo ""
echo -e "${YELLOW}Port Status:${NC}"
if lsof -i:3020 > /dev/null 2>&1; then # Step 8: Test API health
echo -e "${GREEN}✓ Backend is running on port 3020${NC}" log "${CYAN}Step 8: Testing API health endpoint...${NC}"
sleep 3
if curl -s -o /dev/null -w "%{http_code}" http://localhost:3020/health | grep -q "200\|401"; then
success "API is responding"
else else
echo -e "${RED}✗ Backend not detected on port 3020${NC}" warning "API health check failed - may still be starting"
fi fi
if lsof -i:3030 > /dev/null 2>&1; then # Final summary
echo -e "${GREEN}✓ Frontend is running on port 3030${NC}" echo ""
echo "=========================================="
if [ "$ALL_GOOD" = true ]; then
echo -e "${GREEN} All Services Started Successfully! ${NC}"
else else
echo -e "${RED}✗ Frontend not detected on port 3030${NC}" echo -e "${YELLOW} Services Started (Check Warnings) ${NC}"
fi fi
# Check Docker containers
echo ""
echo -e "${YELLOW}Docker Containers:${NC}"
docker ps --filter name=parentflow --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"
# Summary
echo ""
echo "=========================================="
echo -e "${GREEN}Production Environment Started!${NC}"
echo "==========================================" echo "=========================================="
echo "" echo ""
echo "Services:" echo "Service URLs:"
echo " Backend API: http://localhost:3020" echo " Backend API: http://localhost:3020"
echo " Frontend: http://localhost:3030" echo " Frontend: http://localhost:3030"
echo " PostgreSQL: localhost:5432" echo " Admin Dashboard: http://localhost:3335"
echo " Redis: localhost:6379" echo " MinIO Console: http://localhost:9001"
echo " MongoDB: localhost:27017"
echo " MinIO: localhost:9000"
echo " MinIO Console: localhost:9001"
echo "" echo ""
echo "Management Commands:" echo "Management Commands:"
echo " PM2 status: pm2 status" echo " View logs: pm2 logs"
echo " PM2 logs: pm2 logs" echo " Monitor: pm2 monit"
echo " PM2 restart: pm2 restart all" echo " List processes: pm2 list"
echo " PM2 stop: pm2 stop all" echo " Restart all: pm2 restart all"
echo " Docker logs: docker logs parentflow-postgres-prod" echo " Stop all: ./stop-production.sh"
echo " Stop all: pm2 stop all && docker-compose -f docker-compose.production.yml down"
echo "" echo ""
echo "Domains (configure in Nginx/DNS):" echo "Log files:"
echo " Frontend: web.parentflowapp.com → localhost:3030" echo " /var/log/parentflow/api-*.log"
echo " Backend: api.parentflowapp.com → localhost:3020" echo " /var/log/parentflow/frontend-*.log"
echo " /var/log/parentflow/admin-*.log"
echo "" echo ""
echo -e "${GREEN}✓ Startup complete!${NC}"
# Create log directory if it doesn't exist
mkdir -p /var/log/parentflow
log "Services started at $(date)"

View File

@@ -1,7 +1,7 @@
#!/bin/bash #!/bin/bash
# ParentFlow Production Stop Script # ParentFlow Production Stop Script
# Stops PM2 processes and Docker containers gracefully # Stops all production services gracefully
set -e set -e
@@ -10,68 +10,138 @@ RED='\033[0;31m'
GREEN='\033[0;32m' GREEN='\033[0;32m'
YELLOW='\033[1;33m' YELLOW='\033[1;33m'
BLUE='\033[0;34m' BLUE='\033[0;34m'
NC='\033[0m' # No Color CYAN='\033[0;36m'
NC='\033[0m'
log() {
echo -e "${BLUE}[$(date +'%Y-%m-%d %H:%M:%S')]${NC} $1"
}
error() {
echo -e "${RED}[ERROR]${NC} $1" >&2
}
success() {
echo -e "${GREEN}${NC} $1"
}
warning() {
echo -e "${YELLOW}${NC} $1"
}
# Header
echo ""
echo "==========================================" echo "=========================================="
echo "Stopping ParentFlow Production" echo " Stopping ParentFlow Production "
echo "==========================================" echo "=========================================="
echo "" echo ""
# Step 1: Stop PM2 processes # Step 1: Stop PM2 processes
echo -e "${BLUE}Step 1: Stopping PM2 processes...${NC}" log "${CYAN}Step 1: Stopping PM2 services...${NC}"
if command -v pm2 &> /dev/null; then if command -v pm2 &> /dev/null; then
pm2 stop all 2>/dev/null || true # Show current status
echo -e "${GREEN}✓ PM2 processes stopped${NC}" echo "Current PM2 processes:"
pm2 list
# Stop all PM2 processes
pm2 stop all 2>/dev/null || warning "No PM2 processes were running"
# Delete all PM2 processes
pm2 delete all 2>/dev/null || warning "No PM2 processes to delete"
# Kill PM2 daemon
pm2 kill
success "PM2 services stopped"
else else
echo -e "${YELLOW}Warning: PM2 not found${NC}" warning "PM2 not found"
fi fi
# Step 2: Stop Docker containers # Step 2: Stop Docker services
echo "" log "${CYAN}Step 2: Stopping Docker services...${NC}"
echo -e "${BLUE}Step 2: Stopping Docker containers...${NC}" DEPLOY_DIR="/root/parentflow-production"
if docker compose version &> /dev/null; then
# Try to find docker-compose file
if [ -f "$DEPLOY_DIR/docker-compose.production.yml" ]; then
cd "$DEPLOY_DIR"
if docker compose version &> /dev/null; then
docker compose -f docker-compose.production.yml down docker compose -f docker-compose.production.yml down
else
docker-compose -f docker-compose.production.yml down 2>/dev/null || true
fi
if [ $? -eq 0 ]; then
echo -e "${GREEN}✓ Docker containers stopped${NC}"
else
echo -e "${YELLOW}Warning: Failed to stop some Docker containers${NC}"
fi
# Verify everything is stopped
echo ""
echo -e "${BLUE}Verification:${NC}"
# Check PM2
if command -v pm2 &> /dev/null; then
RUNNING_PROCESSES=$(pm2 jlist 2>/dev/null | jq -r '.[] | select(.pm2_env.status == "online") | .name' | wc -l)
if [ "$RUNNING_PROCESSES" -eq 0 ]; then
echo -e "${GREEN}✓ No PM2 processes running${NC}"
else else
echo -e "${YELLOW}Warning: $RUNNING_PROCESSES PM2 processes still running${NC}" docker-compose -f docker-compose.production.yml down
fi fi
fi success "Docker services stopped"
elif [ -f "./docker-compose.production.yml" ]; then
# Check Docker if docker compose version &> /dev/null; then
RUNNING_CONTAINERS=$(docker ps --filter name=parentflow --format "{{.Names}}" | wc -l) docker compose -f docker-compose.production.yml down
if [ "$RUNNING_CONTAINERS" -eq 0 ]; then else
echo -e "${GREEN}✓ No ParentFlow Docker containers running${NC}" docker-compose -f docker-compose.production.yml down
fi
success "Docker services stopped"
else else
echo -e "${YELLOW}Warning: $RUNNING_CONTAINERS containers still running${NC}" warning "Docker compose file not found, skipping..."
docker ps --filter name=parentflow
fi fi
# Step 3: Kill any remaining Node processes on production ports
log "${CYAN}Step 3: Cleaning up remaining processes...${NC}"
kill_port() {
local port=$1
local name=$2
if lsof -i:$port > /dev/null 2>&1; then
log "Stopping $name on port $port..."
lsof -ti:$port | xargs -r kill -9
success "$name stopped"
else
echo " $name not running on port $port"
fi
}
kill_port 3020 "Backend API"
kill_port 3030 "Frontend"
kill_port 3335 "Admin Dashboard"
# Step 4: Clean up temporary files
log "${CYAN}Step 4: Cleaning up temporary files...${NC}"
rm -rf /tmp/pm2-* 2>/dev/null || true
rm -rf /tmp/next-* 2>/dev/null || true
success "Temporary files cleaned"
# Step 5: Verify all services are stopped
log "${CYAN}Step 5: Verifying all services are stopped...${NC}"
check_port() {
local port=$1
local name=$2
if lsof -i:$port > /dev/null 2>&1; then
warning "$name still running on port $port"
return 1
else
success "$name stopped (port $port free)"
return 0
fi
}
ALL_STOPPED=true
check_port 3020 "Backend API" || ALL_STOPPED=false
check_port 3030 "Frontend" || ALL_STOPPED=false
check_port 3335 "Admin Dashboard" || ALL_STOPPED=false
check_port 6379 "Redis" || true # Redis might be used by other services
check_port 27017 "MongoDB" || true # MongoDB might be used by other services
check_port 9000 "MinIO" || true # MinIO might be used by other services
# Final summary
echo "" echo ""
echo "==========================================" echo "=========================================="
echo -e "${GREEN}Production environment stopped${NC}" if [ "$ALL_STOPPED" = true ]; then
echo -e "${GREEN} All Services Stopped Successfully! ${NC}"
else
echo -e "${YELLOW} Services Stopped (Check Warnings) ${NC}"
fi
echo "==========================================" echo "=========================================="
echo "" echo ""
echo "To completely remove Docker volumes (WARNING: deletes data):" echo "To restart services, run:"
echo " docker-compose -f docker-compose.production.yml down -v" echo " ./start-production.sh"
echo "" echo ""
echo "To remove PM2 processes from startup:" log "Services stopped at $(date)"
echo " pm2 delete all"
echo " pm2 save"