# FlutterFlow-Supabase Sync Middleware

A comprehensive middleware server solution for FlutterFlow-Supabase synchronization with a built-in dashboard for monitoring and management.

## 🚀 Features

- **Middleware Server**: Centralized sync processing with Express.js and Socket.IO
- **Offline-First Architecture**: Local MySQL storage with automatic sync
- **Real-time Dashboard**: Web-based monitoring and management interface
- **FlutterFlow Integration**: Easy-to-use client library for FlutterFlow apps
- **Multi-tenant Support**: Complex user and store-based data isolation
- **Conflict Resolution**: Intelligent handling of data conflicts
- **Comprehensive Logging**: Detailed sync logs and system monitoring
- **Health Monitoring**: Real-time system health checks
- **Rate Limiting**: Built-in API protection
- **Security**: JWT authentication and session management
- **File Upload Support**: Image and document upload with processing
- **Image Processing**: Automatic resizing, thumbnails, and optimization
- **File Management**: Upload, download, and delete files with sync

## 📋 Prerequisites

- Node.js 18+ 
- MySQL 8.0+
- Redis 6.0+
- Supabase account
- FlutterFlow project

## 🛠️ Installation

### 1. Clone the Repository

```bash
git clone <repository-url>
cd flutterflow_sync
```

### 2. Install Server Dependencies

```bash
cd server
npm install
```

### 3. Install Dashboard Dependencies

```bash
cd ../dashboard
npm install
```

### 4. Install Client Dependencies

```bash
cd ../client
flutter pub get
```

## ⚙️ Configuration

### 1. Environment Setup

Copy the example environment file and configure your settings:

```bash
cp env.example .env
```

Edit `.env` with your configuration:

```env
# Server Configuration
PORT=3000
NODE_ENV=development

# Supabase Configuration
SUPABASE_URL=your_supabase_url
SUPABASE_SERVICE_KEY=your_supabase_service_key
SUPABASE_ANON_KEY=your_supabase_anon_key

# Database Configuration
DB_HOST=localhost
DB_PORT=3306
DB_NAME=flutterflow_sync
DB_USER=root
DB_PASSWORD=your_password

# Redis Configuration
REDIS_URL=redis://localhost:6379

# Dashboard Configuration
DASHBOARD_USERNAME=admin
DASHBOARD_PASSWORD=admin123
```

### 2. Supabase Setup

#### Create Required Functions

Execute these SQL commands in your Supabase SQL editor:

```sql
-- Create function to execute sync queries
CREATE OR REPLACE FUNCTION execute_sync_query(query text)
RETURNS json
LANGUAGE plpgsql
SECURITY DEFINER
AS $$
DECLARE
    result json;
BEGIN
    EXECUTE 'SELECT json_agg(row_to_json(t)) FROM (' || query || ') t' INTO result;
    RETURN COALESCE(result, '[]'::json);
END;
$$;

-- Grant execute permission
GRANT EXECUTE ON FUNCTION execute_sync_query(text) TO authenticated;

-- Create health check table
CREATE TABLE IF NOT EXISTS _health_check (
    id SERIAL PRIMARY KEY,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Enable RLS on your tables
ALTER TABLE store_user_link ENABLE ROW LEVEL SECURITY;

-- Create policies (example)
CREATE POLICY "Users can view their own store links" ON store_user_link
    FOR SELECT USING (auth.uid() = user_id);
```

### 3. Database Setup

Create the MySQL database:

```sql
CREATE DATABASE flutterflow_sync;
```

The server will automatically create the required tables on startup.

## 🚀 Running the Application

### 1. Start the Server

```bash
cd server
npm start
```

For development with auto-reload:

```bash
npm run dev
```

### 2. Build and Serve Dashboard

```bash
cd dashboard
npm run build
```

The dashboard will be served at `http://localhost:3000/dashboard`

### 3. Access the Dashboard

- URL: `http://localhost:3000/dashboard`
- Default credentials: `admin` / `admin123`

## 📱 FlutterFlow Integration

### 1. Add Client Library

Add the client library to your FlutterFlow project:

```dart
// In your FlutterFlow custom actions
import 'package:flutterflow_sync_client/flutterflow_sync_client.dart';
```

### 2. Initialize Sync Client

```dart
// Initialize in your app startup
await FlutterFlowSyncActions.initializeSync(
  serverUrl: 'http://localhost:3000',
  supabaseUrl: 'your_supabase_url',
  supabaseAnonKey: 'your_supabase_anon_key',
);
```

### 3. Use Sync Actions

```dart
// Read data
final stores = await FlutterFlowSyncActions.readData(
  tableName: 'store_user_link',
  where: 'user_id = ?',
  whereArgs: [currentUserId],
);

// Write data
await FlutterFlowSyncActions.writeData(
  tableName: 'survey_responses',
  operation: 'INSERT',
  data: {
    'id': 'unique_id',
    'store_code': 'STORE001',
    'response': 'Answer text',
  },
);

// Trigger sync
await FlutterFlowSyncActions.performSync();
```

### 4. Use Sync Widgets

```dart
// Sync status indicator
FlutterFlowSyncWidgets.syncStatusIndicator()

// Manual sync button
FlutterFlowSyncWidgets.syncButton()

// Connection status
FlutterFlowSyncWidgets.connectionStatus()

// Data list with sync
FlutterFlowSyncWidgets.syncDataList(
  tableName: 'store_user_link',
  itemBuilder: (context, item) => ListTile(
    title: Text(item['name']),
  ),
)

// File upload widget
FlutterFlowSyncWidgets.fileUploadWidget(
  onFileSelected: (file) async {
    final result = await FlutterFlowSyncActions.uploadFile(file: file);
    print('File uploaded: ${result['fileUrl']}');
  },
)

// Image upload widget
FlutterFlowSyncWidgets.imageUploadWidget(
  onImageSelected: (image) async {
    final result = await FlutterFlowSyncActions.uploadImage(imageFile: image);
    print('Image uploaded: ${result['fileUrl']}');
  },
)

// Image gallery widget
FlutterFlowSyncWidgets.imageGalleryWidget(
  tableName: 'product_images',
  imageBuilder: (context, image) => Image.network(image['fileUrl']),
)
```

## 📊 Dashboard Features

### Overview
- Real-time sync statistics
- System health monitoring
- Performance metrics
- Active user tracking

### Sync Status
- Monitor sync operations across all users
- View sync history and errors
- Trigger manual syncs
- Track sync performance

### Logs
- Comprehensive sync logs
- Filter by user, level, date range
- Export logs to CSV
- Real-time log updates

### Users
- User management interface
- Sync statistics per user
- Manual sync triggers
- User activity monitoring

### Health
- System component status
- Database connectivity
- Redis status
- Memory usage monitoring

## 🔧 API Endpoints

### Authentication
- `POST /api/auth/health` - Auth service health check

### Sync Operations
- `POST /api/sync/trigger` - Trigger manual sync
- `GET /api/sync/status` - Get sync status
- `GET /api/sync/history` - Get sync history

### Data Operations
- `GET /api/data/:tableName` - Read data
- `POST /api/data/:tableName` - Write data

### File Upload Operations
- `POST /api/upload/single` - Upload single file
- `POST /api/upload/multiple` - Upload multiple files
- `GET /api/upload/files` - Get uploaded files
- `DELETE /api/upload/files/:fileId` - Delete uploaded file
- `GET /uploads/:filename` - Serve uploaded files

### Dashboard API
- `POST /dashboard/api/login` - Dashboard login
- `GET /dashboard/api/stats` - Dashboard statistics
- `GET /dashboard/api/logs` - Sync logs
- `GET /dashboard/api/health` - System health

## 🔒 Security Features

- **JWT Authentication**: Secure API access
- **Rate Limiting**: API protection against abuse
- **CORS Configuration**: Controlled cross-origin access
- **Session Management**: Secure dashboard sessions
- **Row Level Security**: Supabase RLS integration
- **Input Validation**: Data sanitization and validation

## 📈 Monitoring & Logging

- **Winston Logging**: Structured logging with multiple transports
- **Log Rotation**: Automatic log file management
- **Performance Metrics**: Sync duration and throughput tracking
- **Error Tracking**: Comprehensive error logging and reporting
- **Health Checks**: Automated system health monitoring

## 🚀 Deployment

### Production Setup

1. **Environment Configuration**
   ```bash
   NODE_ENV=production
   PORT=3000
   # ... other production settings
   ```

2. **Database Setup**
   - Use production MySQL instance
   - Configure Redis cluster
   - Set up Supabase production project

3. **Security**
   - Use strong passwords and secrets
   - Enable HTTPS
   - Configure firewall rules
   - Set up monitoring

4. **Process Management**
   ```bash
   # Using PM2
   npm install -g pm2
   pm2 start src/server.js --name "sync-middleware"
   ```

### Docker Deployment

```dockerfile
# Dockerfile example
FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
RUN npm run build
EXPOSE 3000
CMD ["npm", "start"]
```

## 🧪 Testing

### Server Tests
```bash
cd server
npm test
```

### Client Tests
```bash
cd client
flutter test
```

## 📝 Sync Rules Configuration

The sync rules are defined in `server/src/config/syncConfig.js` and support:

- **Global Data**: Shared across all users
- **User Data**: User-specific information
- **Store Data**: Store-based data with user permissions
- **Complex Queries**: Multi-table joins and filtering
- **Parameterized Queries**: Dynamic user context

## 🔄 Sync Process

1. **Client Request**: FlutterFlow app requests sync
2. **Authentication**: Verify user credentials
3. **Query Execution**: Run sync queries on Supabase
4. **Data Processing**: Store results in local MySQL
5. **Conflict Resolution**: Handle data conflicts
6. **Real-time Updates**: Notify clients via WebSocket
7. **Logging**: Record sync operations

## 🆘 Troubleshooting

### Common Issues

1. **Connection Errors**
   - Check Supabase credentials
   - Verify database connectivity
   - Ensure Redis is running

2. **Sync Failures**
   - Check RLS policies
   - Verify query permissions
   - Review error logs

3. **Dashboard Issues**
   - Clear browser cache
   - Check session configuration
   - Verify authentication

### Debug Mode

Enable debug logging:

```env
LOG_LEVEL=debug
```

### Log Files

- `logs/error.log` - Error logs
- `logs/combined.log` - All logs
- `logs/sync.log` - Sync-specific logs

## 📚 Documentation

- [FlutterFlow Setup Guide](docs/flutterflow-setup-guide.md) - Complete setup guide for FlutterFlow integration
- [Existing App Integration Guide](docs/existing-app-integration.md) - Integrate sync library into existing FlutterFlow apps
- [FlutterFlow Custom Actions Reference](docs/flutterflow-custom-actions.md) - All available custom actions
- [FlutterFlow Widgets Guide](docs/flutterflow-widgets-guide.md) - Custom widgets for rich UIs
- [API Documentation](docs/api.md)
- [Deployment Guide](docs/deployment.md)
- [Troubleshooting Guide](docs/troubleshooting.md)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests
5. Submit a pull request

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🆘 Support

- Create an issue for bugs or feature requests
- Check the documentation
- Review the troubleshooting guide
- Contact support for enterprise assistance

---

**Built with ❤️ for the FlutterFlow community**
