--- title: CleanflowAI emoji: ๐Ÿณ colorFrom: blue colorTo: indigo sdk: docker app_port: 8000 pinned: false --- # ERP to CDF Transformation System v2.0 A high-performance Python system for converting ERP data exports into a standardized Common Data Frame (CDF) format using Polars and DuckDB. ## ๐ŸŒŸ Features - โšก **High-Performance Processing** with Polars and DuckDB - ๐Ÿ”„ **Template-driven mapping** with intelligent ERP auto-detection - ๐Ÿค– **AI-assisted mapping** for unknown ERP schemas - ๐Ÿ“Š **Multiple file formats**: CSV, Excel, JSON, SQL, Parquet - ๐Ÿš€ **FastAPI REST API** with comprehensive endpoints - ๐Ÿข **11 Enterprise ERP Systems** with 883+ field mappings - ๐Ÿ“ **Enhanced data models** with full address support (16 fields) - ๐ŸŽฏ **5 Entity Types**: Sales Orders, Customers, Invoices, Purchase Orders, Inventory Items - ๐Ÿ”ง **Production-ready** with data format consistency and error handling ## ๐Ÿš€ Quick Start ### Installation ```bash # Clone the repository git clone cd cleanflowai # Install dependencies pip install -r requirements.txt # Install high-performance dependencies pip install polars duckdb # Optional: Set up OpenAI API key for LLM fallback export OPENAI_API_KEY="your-api-key-here" ``` ### Option 1: API Server (Recommended) ```bash # Start the API server python app.py # API will be available at http://localhost:8000 # Interactive docs at http://localhost:8000/docs ``` ### Option 2: Python Package ```python from mapper import TransformationEngine, TransformationRequest # Create transformation engine engine = TransformationEngine() # Transform data with auto-detection request = TransformationRequest( auto_select_erp=True, auto_select_entity=True, file_data="sample.csv" ) result = engine.transform(request) print(f"Transformed {len(result.data)} records") ``` ### Option 3: Quick Transform ```python from mapper import quick_transform # One-liner transformation result = quick_transform( file_data="sample.csv", auto_detect=True ) if result.success: print(f"โœ… Converted {len(result.data)} records") print(f"๐Ÿ” Detected ERP: {result.detected_erp}") ``` ## ๐Ÿ“Š API Endpoints ### Core Transformation - `POST /transform` - Transform JSON data to CDF format - `POST /transform/file` - Transform uploaded files - `POST /transform/file/download` - Transform and download results ### Analysis & Validation - `POST /analyze` - Analyze data structure and suggest ERP/entity combinations - `POST /validate` - Validate file format and structure ### Information - `GET /health` - Health check - `GET /entities` - List supported entity types - `GET /erps` - List supported ERP systems - `GET /formats` - List supported file formats ### Template Inspection - `GET /template/erp/{erp}/entity/{entity}` - Get specific mapping - `GET /template/entity/{entity}/schema` - Get CDF schema ### Example API Usage ```bash # Transform JSON data curl -X POST "http://localhost:8000/transform" \ -H "Content-Type: application/json" \ -d '{ "auto_select_erp": true, "auto_select_entity": true, "data": [{"tranId": "SO1001", "total": 1249.0}] }' # Upload and transform file curl -X POST "http://localhost:8000/transform/file" \ -F "file=@sample.csv" \ -F "auto_select_erp=true" # Download transformed file curl -X POST "http://localhost:8000/transform/file/download" \ -F "file=@sample.csv" \ -F "output_format=csv" \ -o transformed_data.csv ``` ## ๐Ÿ—๏ธ Architecture ### Clean Project Structure ``` cleanflowai/ โ”œโ”€โ”€ app.py # Main FastAPI application โ”œโ”€โ”€ template.json # ERP mapping templates (883+ mappings) โ”œโ”€โ”€ requirements.txt # Dependencies โ”œโ”€โ”€ docs/ # Documentation โ”‚ โ”œโ”€โ”€ API_DOCUMENTATION.md # Complete API docs โ”‚ โ””โ”€โ”€ PROJECT_STRUCTURE.md # Architecture details โ””โ”€โ”€ mapper/ # Core transformation package โ”œโ”€โ”€ __init__.py # Package exports โ”œโ”€โ”€ transformation_engine.py # Main orchestrator (Polars/DuckDB) โ”œโ”€โ”€ data_processor.py # High-performance data processing โ”œโ”€โ”€ template_loader.py # Template management โ”œโ”€โ”€ erp_resolver.py # ERP auto-detection โ”œโ”€โ”€ llm_handler.py # AI integration โ””โ”€โ”€ models.py # Pydantic models & CDF schemas ``` ### Data Flow ``` Input Data โ†’ DataProcessor (Polars/DuckDB) โ†’ ERP Detection โ†’ Template Mapping โ†’ Transformation โ†’ CDF Output ``` ## ๐Ÿข Supported ERP Systems ### Enterprise Coverage (11 Systems) | ERP System | Status | Description | |------------|--------|-------------| | **Oracle Fusion** | โœ… Complete | Oracle's cloud ERP platform | | **SAP ERP** | โœ… Complete | SAP's enterprise resource planning | | **Microsoft Dynamics** | โœ… Complete | Microsoft business applications | | **NetSuite** | โœ… Complete | Oracle NetSuite cloud ERP | | **Workday** | โœ… Complete | Cloud HR and financial management | | **Infor M3** | โœ… Complete | Manufacturing and distribution ERP | | **Infor LN** | โœ… Complete | Enterprise manufacturing ERP | | **Epicor Kinetic** | โœ… Complete | Manufacturing ERP solution | | **QAD ERP** | โœ… Complete | Manufacturing ERP | | **IFS Cloud** | โœ… Complete | ERP and asset management | | **Sage Intacct** | โœ… Complete | Cloud financial management | ## ๐Ÿ“‹ Entity Types & CDF Schemas ### Sales Orders (13 fields) `order_id`, `order_date`, `customer_id`, `status`, `currency`, `total_amount`, `notes`, `item_id`, `description`, `quantity`, `unit_price`, `line_total`, `tax_code` ### Customers (16 fields with full address) **Core**: `customer_id`, `customer_name`, `contact_email`, `phone_number`, `alt_phone` **Business**: `is_company`, `status`, `currency`, `created_date`, `last_modified` **Address**: `address_type`, `address_line1`, `city`, `state`, `postal_code`, `country` ### Invoices (14 fields) `invoice_id`, `invoice_date`, `customer_id`, `status`, `currency`, `total_amount`, `due_date`, `notes`, `item_id`, `description`, `quantity`, `unit_price`, `line_total`, `tax_code` ### Purchase Orders (14 fields) `po_id`, `po_date`, `vendor_id`, `status`, `currency`, `total_amount`, `expected_receipt_date`, `notes`, `item_id`, `description`, `quantity`, `unit_price`, `line_total`, `tax_code` ### Inventory Items (12 fields) `item_id`, `item_name`, `description`, `purchase_description`, `sales_description`, `base_price`, `cost_price`, `unit_type`, `is_active`, `quantity_on_hand`, `reorder_point`, `preferred_vendor_id` ## ๐Ÿ“ File Format Support | Format | Extension | Description | |--------|-----------|-------------| | **CSV** | `.csv` | Comma-separated values | | **Excel** | `.xlsx`, `.xls` | Microsoft Excel files | | **JSON** | `.json` | JavaScript Object Notation | | **SQL** | `.sql` | SQL query results | | **Parquet** | `.parquet` | Columnar storage format | ## ๐Ÿ”ง Data Format Consistency ### Date Fields - **APIs/Database**: ISO `yyyy-MM-dd` format - **Human-readable**: `dd-MMMM-yyyy` format (e.g., `04-August-2025`) ### Decimal Fields - **Precision**: DECIMAL(18,2) for all currency and pricing - **Format**: Always 2 decimal places (e.g., `1249.00`) ### Boolean Fields - **JSON/API**: `true`/`false` - **Database**: `1`/`0` ### Text Fields - **Encoding**: UTF-8 with proper escaping - **Processing**: Trimmed and normalized ## โšก Performance ### Benchmarks - **Small files** (< 1MB): < 100ms processing time - **Medium files** (1-10MB): < 500ms processing time - **Large files** (10-100MB): < 2s processing time ### High-Performance Features - **Polars**: Lightning-fast DataFrame operations - **DuckDB**: Optimized SQL query execution - **Memory efficiency**: Streaming for large files - **Concurrent processing**: FastAPI async support ## ๐Ÿ” Advanced Usage ### Custom Configuration ```python from mapper import TransformationEngine # Custom engine with specific settings engine = TransformationEngine( template_path="custom-template.json", use_mock_llm=False, similarity_threshold=0.6 ) ``` ### Batch Processing ```python from pathlib import Path from mapper import create_transformation_engine engine = create_transformation_engine() # Process multiple files for file_path in Path("data").glob("*.csv"): request = TransformationRequest( auto_select_erp=True, auto_select_entity=True, file_data=str(file_path) ) result = engine.transform(request) if result.success: print(f"โœ… {file_path.name}: {len(result.data)} records") ``` ### Custom LLM Integration ```python from mapper import TransformationEngine, LLMHandler # Custom LLM configuration llm_handler = LLMHandler( model_name="gpt-4o", temperature=0.0, max_retries=3 ) engine = TransformationEngine(llm_handler=llm_handler) ``` ## ๐Ÿงช Testing ### System Validation ```bash # Test core components python -c " from mapper import TransformationEngine, DataProcessor, FileFormat engine = TransformationEngine(use_mock_llm=True) processor = DataProcessor() print('โœ… All components operational') " # Test API python -c " from app import app, transformation_engine print(f'โœ… API ready: {app.title} v{app.version}') " ``` ### API Testing ```bash # Start server python app.py # Test endpoints curl http://localhost:8000/health curl http://localhost:8000/entities curl http://localhost:8000/erps ``` ## ๐Ÿš€ Deployment ### Local Development ```bash python app.py # API available at http://localhost:8000 ``` ### Docker Deployment ```dockerfile FROM python:3.11-slim WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt COPY . . EXPOSE 8000 CMD ["python", "app.py"] ``` ### Production Considerations - Use production ASGI server (Gunicorn + Uvicorn) - Configure logging and monitoring - Implement authentication and rate limiting - Set up health checks and metrics ## ๐Ÿ”ง Configuration ### Environment Variables ```bash # Optional: OpenAI API key for LLM fallback OPENAI_API_KEY=your-api-key-here # Optional: Custom template file path TEMPLATE_PATH=./custom-template.json ``` ### Template Structure The `template.json` file defines ERP-to-CDF mappings: ```json { "NetSuite": { "sales_orders": { "tranId": "order_id", "trandate": "order_date", "entity": "customer_id", "total": "total_amount" } }, "CDF_META": { "sales_orders": [ "order_id", "order_date", "customer_id", "status", "currency", "total_amount", "notes", "item_id", "description", "quantity", "unit_price", "line_total", "tax_code" ] } } ``` ## ๐Ÿ“š Documentation - **[API Documentation](docs/API_DOCUMENTATION.md)** - Complete API reference - **[Project Structure](docs/PROJECT_STRUCTURE.md)** - Architecture details - **[ERP System Coverage](ERP_SYSTEM_COVERAGE.md)** - Mapping statistics - **[Data Format Guidelines](ERP-CDF-Mapping.md)** - Consistency rules - **[Changelog](CHANGELOG.md)** - Version history ## ๐Ÿ› ๏ธ Development ### Adding New ERP Systems 1. Update `template.json` with new mappings 2. Test with sample data 3. Update documentation ### Adding New Entity Types 1. Define new CDF model in `models.py` 2. Add to `EntityType` enum 3. Update template structure 4. Add validation logic ### Code Quality ```bash # Format code black mapper/ app.py # Sort imports isort mapper/ app.py # Type checking mypy mapper/ ``` ## ๐Ÿ› Troubleshooting ### Common Issues **Missing Dependencies** ```bash pip install polars duckdb ``` **LLM API Key Missing** ```bash export OPENAI_API_KEY="your-key-here" # or use mock LLM for testing ``` **Template File Not Found** ``` Ensure template.json exists in working directory ``` ### Debug Mode ```python import logging logging.basicConfig(level=logging.DEBUG) # Use mock LLM for testing engine = TransformationEngine(use_mock_llm=True) ``` ## ๐Ÿค Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests for new functionality 5. Submit a pull request ## ๐Ÿ“„ License This project is licensed under the MIT License. ## ๐Ÿ†˜ Support For questions, issues, or feature requests: 1. Check the [API Documentation](docs/API_DOCUMENTATION.md) 2. Review the [Project Structure](docs/PROJECT_STRUCTURE.md) 3. Search existing issues 4. Create a new issue with detailed information 5. For API questions, check interactive docs at `/docs` --- **๐Ÿš€ Built for Enterprise-Grade ERP Data Integration** **โšก Powered by Polars + DuckDB for Maximum Performance** **๐ŸŽฏ Version 2.0.0 - Clean, Fast, Production-Ready**