File size: 12,732 Bytes
0187a6e
 
 
 
e3ecac1
0187a6e
 
 
 
 
5a65404
d448413
5a65404
d448413
5a65404
d448413
5a65404
 
 
 
 
 
 
 
 
d448413
5a65404
d448413
 
 
 
 
 
 
 
 
 
 
5a65404
 
 
d448413
 
 
 
5a65404
d448413
5a65404
 
 
d448413
5a65404
 
d448413
 
5a65404
d448413
5a65404
 
d448413
5a65404
 
d448413
5a65404
 
 
 
 
 
d448413
5a65404
 
d448413
 
5a65404
d448413
5a65404
 
 
 
 
 
 
 
d448413
5a65404
 
 
d448413
 
5a65404
d448413
5a65404
 
 
 
d448413
5a65404
 
 
d448413
 
5a65404
d448413
 
5a65404
 
 
 
 
d448413
 
 
 
5a65404
 
d448413
 
5a65404
 
 
d448413
 
5a65404
 
 
 
 
 
 
d448413
5a65404
 
d448413
 
5a65404
d448413
5a65404
d448413
 
5a65404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d448413
 
 
 
5a65404
 
 
 
d448413
5a65404
d448413
5a65404
d448413
5a65404
 
 
 
 
 
 
 
 
 
 
 
 
d448413
5a65404
ab76221
5a65404
 
ab76221
5a65404
 
 
 
ab76221
5a65404
 
ab76221
5a65404
 
ab76221
5a65404
 
ab76221
5a65404
d448413
5a65404
 
 
 
 
 
 
d448413
5a65404
d448413
5a65404
 
 
d448413
5a65404
 
 
d448413
5a65404
 
 
d448413
5a65404
 
 
d448413
5a65404
 
 
 
 
 
d448413
5a65404
 
 
 
 
d448413
5a65404
 
 
d448413
 
5a65404
d448413
5a65404
 
 
 
 
d448413
 
 
 
 
 
 
5a65404
d448413
5a65404
d448413
 
5a65404
 
 
 
 
 
d448413
5a65404
d448413
5a65404
d448413
 
5a65404
d448413
 
5a65404
d448413
5a65404
 
 
 
 
d448413
5a65404
 
d448413
 
5a65404
d448413
5a65404
d448413
 
5a65404
 
 
 
 
 
 
 
 
 
 
 
 
d448413
 
5a65404
d448413
 
 
5a65404
d448413
 
 
 
 
 
 
5a65404
d448413
5a65404
d448413
5a65404
 
 
d448413
5a65404
 
 
d448413
5a65404
 
 
 
 
 
 
 
d448413
 
5a65404
 
 
 
 
 
 
 
 
 
 
 
 
d448413
5a65404
 
 
 
 
 
 
d448413
 
 
5a65404
d448413
5a65404
 
 
 
d448413
5a65404
 
 
 
 
 
 
d448413
 
 
 
5a65404
d448413
5a65404
 
 
 
 
d448413
5a65404
d448413
5a65404
d448413
5a65404
 
 
d448413
5a65404
d448413
5a65404
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d448413
 
5a65404
 
 
 
 
 
 
d448413
5a65404
 
 
 
 
d448413
 
5a65404
d448413
5a65404
d448413
 
 
 
 
 
 
 
 
5a65404
d448413
 
5a65404
d448413
 
 
 
 
5a65404
d448413
5a65404
d448413
5a65404
d448413
5a65404
d448413
 
 
5a65404
 
 
 
 
d448413
 
 
5a65404
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
---
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 <repository-url>
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**