MrTechie commited on
Commit
d448413
·
0 Parent(s):

Initial AI done

Browse files
.gitignore ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be added to the global gitignore or merged into this project gitignore. For a PyCharm
158
+ # project, it is recommended to ignore the entire .idea directory.
159
+ .idea/
160
+
161
+ # VS Code
162
+ .vscode/
163
+ *.code-workspace
164
+
165
+ # Project-specific files
166
+ # API keys and secrets
167
+ .env.local
168
+ .env.production
169
+ .env.development
170
+ secrets.json
171
+ config.json
172
+
173
+ # Data files
174
+ data/
175
+ *.csv
176
+ *.json
177
+ *.xlsx
178
+ *.xls
179
+ !template.json
180
+ !template*.json
181
+
182
+ # Output directories
183
+ output/
184
+ converted/
185
+ results/
186
+ exports/
187
+
188
+ # Log files
189
+ *.log
190
+ logs/
191
+
192
+ # Temporary files
193
+ temp/
194
+ tmp/
195
+ *.tmp
196
+ *.temp
197
+
198
+ # OS generated files
199
+ .DS_Store
200
+ .DS_Store?
201
+ ._*
202
+ .Spotlight-V100
203
+ .Trashes
204
+ ehthumbs.db
205
+ Thumbs.db
206
+
207
+ # Windows
208
+ *.lnk
209
+
210
+ # FastAPI specific
211
+ .pytest_cache/
212
+ test_*.db
213
+
214
+ # Machine learning models
215
+ *.pkl
216
+ *.joblib
217
+ *.model
218
+ models/
219
+
220
+ # Jupyter notebooks (optional - uncomment if you don't want to track notebooks)
221
+ # *.ipynb
222
+
223
+ # Documentation builds
224
+ docs/build/
225
+ site/
226
+
227
+ # Local development
228
+ local_config.py
229
+ dev_settings.py
230
+
231
+ # Database files
232
+ *.db
233
+ *.sqlite
234
+ *.sqlite3
235
+
236
+ # Backup files
237
+ *.bak
238
+ *.backup
239
+ *~
240
+
241
+ # IDE files
242
+ *.swp
243
+ *.swo
244
+ *~
245
+
246
+ # Custom template files (keep the main template.json but ignore custom ones)
247
+ custom-template*.json
248
+ local-template*.json
249
+
250
+ # Test output
251
+ test_output/
252
+ test_results/
253
+
254
+ # Coverage reports
255
+ htmlcov/
256
+ .coverage
257
+ coverage.xml
258
+
259
+ # Profiling
260
+ *.prof
261
+
262
+ # Memory dumps
263
+ *.hprof
ERP-CDF-Mapping.md ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### ERP to Common Data Frame (CDF) Entity Mapping
2
+
3
+ To ensure **data consistency across formats** (like JSON, CSV, Excel, APIs, and databases), follow these format guidelines:
4
+
5
+ * **Date fields** should follow ISO `yyyy-MM-dd` in APIs and databases, but for human-readable files (CSV, Excel), use `dd-MMMM-yyyy` (e.g., `04-August-2025`).
6
+ * **Decimal fields** (currency, unit prices, totals) must retain two decimal places (e.g., `1249.00`) and use `DECIMAL(18,2)` in DBs.
7
+ * **Boolean fields** should be stored as `true/false` (JSON), `1/0` (DBs), and consistently mapped.
8
+ * **Text fields** should be UTF-8 encoded and escaped properly for CSV/JSON.
9
+ * Use **JSON Schema or OpenAPI spec** to validate and enforce formats in APIs.
10
+ * In **Excel**, enforce field formatting using cell templates.
11
+ * Always maintain a **data dictionary** like this document to describe field purpose, formats, and types.
12
+
13
+ This document outlines the field names used for each entity across different ERP systems, displayed in a side-by-side column layout per entity.
14
+
15
+ ---
16
+
17
+ ### 🛒 Sales Orders Fields Comparison
18
+
19
+ | Oracle Fusion | Infor M3 | Infor LN | Epicor Kinetic | Workday | QAD ERP | NetSuite | Microsoft Dynamics | SAP ERP | IFS Cloud | Sage Intacct | ➡️ CDF Field |
20
+ | ----------------------- | -------- | ------------- | -------------- | ---------------------- | ----------------------- | -------------------- | ------------------ | ------------------ | ----------------- | ------------ | ------------- |
21
+ | OrderKey | ORNO | tdsls400.orno | OrderNum | Customer\_Contract\_ID | so\_mstr.so\_nbr | tranId | SalesId | VBAK.VBELN | OrderNo | SO\_NO | order\_id |
22
+ | CreationDate | ORDT | tdsls400.odat | OrderDate | Contract\_Start\_Date | so\_mstr.so\_ord\_date | trandate | CreatedDateTime | VBAK.ERDAT | OrderDate | ORDER\_DATE | order\_date |
23
+ | BuyingPartyId | CUNO | tdsls400.otbp | CustNum | Customer\_ID | so\_mstr.so\_cust | entity | CustAccount | VBAK.KUNNR | CustomerId | CUSTOMERID | customer\_id |
24
+ | StatusCode | — | tdsls400.stat | OrderHeld | Contract\_Status\_Name | so\_mstr.so\_stat | status | SalesStatus | VBAK.AUART | OrderStatus | STATUS | status |
25
+ | TransactionCurrencyCode | CUCD | tdsls400.curr | CurrencyCode | Currency\_Code | so\_mstr.so\_curr | currency | CurrencyCode | VBAK.WAERK | CurrencyCode | CURRENCY | currency |
26
+ | TransactionAmount | — | tdsls400.oamt | OrderAmt | Total\_Contract\_Value | so\_mstr.so\_total\_amt | total | TotalAmount | VBAK.NETWR | TotalAmount | TOTALAMOUNT | total\_amount |
27
+ | memo | WHLO | — | RequestDate | CustomerReference | — | memo | — | VBAK.BSTNK | CustomerReference | CUSTPO | notes |
28
+ | item\_id (lines) | ITNO | tdsls401.item | PartNum | Item\_ID | sod\_det.sod\_part | itemList.item | ItemId | VBAP.MATNR | PartNo | ITEMID | item\_id |
29
+ | description | ITDS | tdsls401.dsca | LineDesc | Item\_Descriptor | sod\_det.sod\_desc | itemList.description | Name | VBAP.ARKTX | Description | DESCRIPTION | description |
30
+ | quantity | ORQA | tdsls401.qoor | OrderQty | Quantity | sod\_det.sod\_qty\_ord | itemList.quantity | SalesQty | VBAP.KWMENG | QtyOrdered | QTY\_ORDERED | quantity |
31
+ | unit\_price | SAPR | tdsls401.pric | UnitPrice | Unit\_Price | sod\_det.sod\_price | itemList.rate | SalesPrice | VBAP.WAERK (price) | SalesPrice | UNITPRICE | unit\_price |
32
+ | line\_total | LNAM | tdsls401.oamt | DocExtPrice | Extended\_Amount | — | itemList.amount | LineAmount | VBAP.NETWR | LineAmount | AMOUNT | line\_total |
33
+ | tax\_code | VTCD | — | TaxCatID | Tax\_Code\_ID | sod\_det.sod\_taxc | itemList.taxCode | SalesTaxGroup | — | TaxCode | TAXDETAILID | tax\_code |
34
+
35
+ ➡️ **CDF Fields & SQL Types:**
36
+
37
+ * `order_id` – VARCHAR(64)
38
+ * `order_date` – DATE
39
+ * `customer_id` – VARCHAR(64)
40
+ * `status` – VARCHAR(32)
41
+ * `currency` – VARCHAR(8)
42
+ * `total_amount` – DECIMAL(18,2)
43
+ * `notes` – TEXT
44
+ * `item_id` – VARCHAR(64)
45
+ * `description` – TEXT
46
+ * `quantity` – INT
47
+ * `unit_price` – DECIMAL(18,2)
48
+ * `line_total` – DECIMAL(18,2)
49
+ * `tax_code` – VARCHAR(32)
50
+
51
+ ---
52
+
53
+ ### 👥 Customers Fields Comparison
54
+
55
+ | Oracle Fusion | Infor M3 | Infor LN | Epicor Kinetic | Workday | QAD ERP | NetSuite | Microsoft Dynamics | SAP ERP | IFS Cloud | Sage Intacct | ➡️ CDF Field |
56
+ | --------------------------------------------- | -------- | ------------- | -------------- | -------------------------------- | ---------------------- | ------------ | ------------------ | --------------- | ------------------ | ------------ | -------------- |
57
+ | HZ\_CUST\_ACCOUNTS.ACCOUNT\_NUMBER | CUNO | tccom100.bpid | CustID | Customer\_Reference.Customer\_ID | cm\_mstr.cm\_addr | entityId | AccountNum | KNA1.KUNNR | CustomerId | CUSTOMERID | customer\_id |
58
+ | HZ\_PARTIES.PARTY\_NAME | CUNM | tccom100.nama | Name | Customer\_Data.Customer\_Name | cm\_mstr.cm\_name | companyName | Name | KNA1.NAME1 | CustomerName | NAME | customer\_name |
59
+ | HZ\_PARTIES.EMAIL\_ADDRESS | EMAL | tccom100.emal | EmailAddress | Email\_Address | cm\_mstr.cm\_contact2 | email | Email | ADRC.SMTP\_ADDR | EmailAddress | EMAIL | contact\_email |
60
+ | HZ\_PARTIES.PRIMARY\_PHONE\_NUMBER | PHNO | tccom100.tele | PhoneNum | Phone\_Number | cm\_mstr.cm\_phone | phone | Phone | KNA1.TELF1 | PhoneNo | PHONE | phone\_number |
61
+ | — | YREF | — | FaxNum | — | cm\_mstr.cm\_fax | altPhone | TeleFax | KNA1.TELFX | FaxNo | FAX | alt\_phone |
62
+ | HZ\_PARTIES.PARTY\_TYPE | — | — | CustomerType | Customer\_is\_Organization | cm\_mstr.cm\_type | isPerson | PartyType | KNA1.KTOKD | CustomerType | TYPE | is\_company |
63
+ | HZ\_CUST\_ACCOUNTS.STATUS | STAT | tccom100.stat | CreditHold | Customer\_Status\_Name | cm\_mstr.cm\_sort | status | Blocked | KNA1.SPERR | BlockedForDelivery | STATUS | status |
64
+ | HZ\_CUST\_ACCOUNTS.PREFERRED\_CURRENCY | CUCD | — | CurrencyCode | Currency\_Code | cm\_mstr.cm\_curr | currency | Currency | KNB1.WAERS | CurrencyCode | CURRENCY | currency |
65
+ | HZ\_CUST\_ACCOUNTS.ACCOUNT\_ESTABLISHED\_DATE | RGDT | tccom100.crdt | EstDate | Create\_Date\_Time | cm\_mstr.cm\_cr\_date | dateCreated | CreatedDateTime | KNA1.ERDAT | CreatedDate | CREATEDDATE | created\_date |
66
+ | HZ\_PARTIES.LAST\_UPDATE\_DATE | LMDT | tccom100.aedt | SysRevID | Update\_Date\_Time | cm\_mstr.cm\_mod\_date | lastModified | ModifiedDateTime | KNA1.AEDAT | LastUpdatedDate | MODIFIEDDATE | last\_modified |
67
+ | HZ\_CUST\_ACCT\_SITES\_ALL.SITE\_USE\_CODE | — | — | — | Type\_Reference | — | — | Type | — | — | — | address\_type |
68
+ | HZ\_LOCATIONS.ADDRESS1 | CUA1 | — | — | Address\_Line\_Data | cm\_mstr.cm\_line1 | — | Address | — | — | — | address\_line1 |
69
+ | HZ\_LOCATIONS.CITY | — | tccom131.namc | — | City | cm\_mstr.cm\_city | — | City | — | City | CITY | city |
70
+ | HZ\_LOCATIONS.STATE | — | — | — | State\_Reference | cm\_mstr.cm\_state | — | State | — | State | STATE | state |
71
+ | HZ\_LOCATIONS.POSTAL\_CODE | — | — | — | Postal\_Code | cm\_mstr.cm\_zip | — | ZipCode | — | ZipCode | ZIP | postal\_code |
72
+ | HZ\_LOCATIONS.COUNTRY | — | — | — | Country\_Code | cm\_mstr.cm\_country | — | CountryRegionId | — | CountryRegionId | COUNTRY | country |
73
+
74
+ ➡️ **CDF Fields & SQL Types:**
75
+
76
+ * `customer_id` – VARCHAR(64)
77
+ * `customer_name` – VARCHAR(255)
78
+ * `contact_email` – VARCHAR(255)
79
+ * `phone_number` – VARCHAR(32)
80
+ * `alt_phone` – VARCHAR(32)
81
+ * `is_company` – BOOLEAN
82
+ * `status` – VARCHAR(32)
83
+ * `currency` – VARCHAR(8)
84
+ * `created_date` – DATETIME
85
+ * `last_modified` – DATETIME
86
+ * `address_type` – VARCHAR(32)
87
+ * `address_line1` – VARCHAR(255)
88
+ * `city` – VARCHAR(128)
89
+ * `state` – VARCHAR(64)
90
+ * `postal_code` – VARCHAR(20)
91
+ * `country` – VARCHAR(64)
92
+
93
+ ### 🧾 Invoices Fields Comparison
94
+
95
+ | Oracle Fusion | Infor M3 | Infor LN | Epicor Kinetic | Workday | QAD ERP | NetSuite | Microsoft Dynamics | SAP ERP | IFS Cloud | Sage Intacct | ➡️ CDF Field |
96
+ | -------------------- | -------- | ------------- | -------------- | ----------------------- | --------------------------- | -------------------- | ------------------ | ---------- | --------------- | ------------ | ------------- |
97
+ | TransactionNumber | IVNO | tfacp100.invn | InvoiceNum | Invoice\_Number | ih\_hist.ih\_inv\_nbr | tranId | InvoiceId | VBRK.VBELN | InvoiceNo | INVOICE\_NO | invoice\_id |
98
+ | TransactionDate | IVDT | tfacp100.indt | InvoiceDate | Invoice\_Date | ih\_hist.ih\_inv\_date | trandate | InvoiceDate | VBRK.FKDAT | InvoiceDate | INVOICEDATE | invoice\_date |
99
+ | BillToCustomerNumber | CUNO | tfacp100.ibp | CustNum | Customer\_ID | ih\_hist.ih\_cust | entity | CustAccount | VBRK.KUNAG | CustomerId | CUSTOMERID | customer\_id |
100
+ | InvoiceStatus | — | tfacp100.stat | OpenInvoice | Invoice\_Status\_Name | ih\_hist.ih\_stat | status | InvoiceStatus | VBRK.FKSTO | InvoiceStatus | STATUS | status |
101
+ | InvoiceCurrencyCode | CUCD | tfacp100.cucd | CurrencyCode | Currency\_Code | ih\_hist.ih\_curr | currency | CurrencyCode | VBRK.WAERK | CurrencyCode | CURRENCY | currency |
102
+ | InvoiceBalanceAmount | IVAM | tfacp100.amti | InvoiceAmt | Total\_Invoice\_Amount | ih\_hist.ih\_amt | total | AmountCur | VBRK.NETWR | GrossAmount | TOTALDUE | total\_amount |
103
+ | DueDate | DUDT | tfacp100.dudt | DueDate | Due\_Date | ih\_hist.ih\_due\_date | dueDate | DueDate | VBRK.ZFBDT | DueDate | DUEDATE | due\_date |
104
+ | Comments | — | — | InvoiceComment | Memo | — | memo | Description | VBRK.BSTNK | Remarks | NOTES | notes |
105
+ | item\_id (lines) | ITNO | — | PartNum | Sales\_Item\_Reference | id\_hist.id\_part | itemList.item | ItemId | VBRP.MATNR | PartNo | ITEMID | item\_id |
106
+ | description | ITDS | — | Description | Line\_Item\_Description | id\_hist.id\_desc | itemList.description | Name | VBRP.ARKTX | PartDescription | DESCRIPTION | description |
107
+ | quantity | — | — | SellingShipQty | Quantity | id\_hist.id\_qty\_inv | itemList.quantity | Qty | VBRP.FKIMG | Quantity | QTY | quantity |
108
+ | unit\_price | — | — | UnitPrice | Unit\_Cost | id\_hist.id\_price | itemList.rate | SalesPrice | — | UnitPrice | UNITPRICE | unit\_price |
109
+ | line\_total | — | — | ExtPrice | Extended\_Amount | (id\_qty\_inv \* id\_price) | itemList.amount | LineAmount | VBRP.NETWR | LineAmount | AMOUNT | line\_total |
110
+ | tax\_code | — | — | TaxCatID | Tax\_Code\_ID | id\_hist.id\_taxc | itemList.taxCode | TaxGroup | VBRP.MWSKZ | TaxCode | TAXDETAILID | tax\_code |
111
+
112
+ ➡️ **CDF Fields & SQL Types:**
113
+
114
+ * `invoice_id` – VARCHAR(64)
115
+ * `invoice_date` – DATE
116
+ * `customer_id` – VARCHAR(64)
117
+ * `status` – VARCHAR(32)
118
+ * `currency` – VARCHAR(8)
119
+ * `total_amount` – DECIMAL(18,2)
120
+ * `due_date` – DATE
121
+ * `notes` – TEXT
122
+ * `item_id` – VARCHAR(64)
123
+ * `description` – TEXT
124
+ * `quantity` – INT
125
+ * `unit_price` – DECIMAL(18,2)
126
+ * `line_total` – DECIMAL(18,2)
127
+ * `tax_code` – VARCHAR(32)
128
+
129
+ ### 📦 Purchase Orders Fields Comparison
130
+
131
+ | Oracle Fusion | Infor M3 | Infor LN | Epicor Kinetic | Workday | QAD ERP | NetSuite | Microsoft Dynamics | SAP ERP | IFS Cloud | Sage Intacct | ➡️ CDF Field |
132
+ | -------------------- | ----------------- | ------------- | -------------- | ------------------- | ------------------------ | -------------------- | ------------------ | ---------- | ------------------- | ---------------- | ----------------------- |
133
+ | SEGMENT1 | PUNO | tdpur400.orno | PONUM | Purchase\_Order\_ID | poh\_hist.poh\_nbr | tranId | PurchId | EKKO.EBELN | OrderNo | PO\_NO | po\_id |
134
+ | CREATION\_DATE | PUDT | tdpur400.odat | OrderDate | Document\_Date | poh\_hist.poh\_ord\_date | trandate | CreatedDateTime | EKKO.BEDAT | OrderDate | ORDERDATE | po\_date |
135
+ | VENDOR\_ID | SUNO | tdpur400.suno | VendorNum | Supplier\_ID | poh\_hist.poh\_vend | entity | OrderAccount | EKKO.LIFNR | SupplierId | VENDORID | vendor\_id |
136
+ | DOCUMENT\_STATUS | — | tdpur400.stat | OpenOrder | Status\_Name | poh\_hist.poh\_stat | status | DocumentStatus | EKKO.BSTYP | OrderStatus | STATUS | status |
137
+ | CURRENCY\_CODE | CUCD | tdpur400.cucd | CurrencyCode | Currency\_Code | poh\_hist.poh\_curr | currency | CurrencyCode | EKKO.WAERS | CurrencyCode | CURRENCY | currency |
138
+ | total\_amount (calc) | — | — | TotalOrder | Total\_Amount | — | total | Amount | EKKO.NETWR | GrossAmount | TOTALAMOUNT | total\_amount |
139
+ | NEED\_BY\_DATE | RELD | tdpur401.ddte | DueDate | Deliver\_To\_Date | pod\_det.pod\_due\_date | expectedReceiptDate | DeliveryDate | EKET.EINDT | PlannedDeliveryDate | EXPECTEDSHIPDATE | expected\_receipt\_date |
140
+ | COMMENTS | WHLO | — | CommentText | Memo | poh\_hist.poh\_comment | memo | PurchName | EKKO.BSTNK | Notes | MEMO | notes |
141
+ | item\_id (lines) | ITEM\_ID | tdipu001.item | PartNum | Item\_Descriptor | pod\_det.pod\_part | itemList.item | ItemId | EKPO.MATNR | PartNo | ITEMID | item\_id |
142
+ | description | ITEM\_DESCRIPTION | tdipu001.dsca | LineDesc | Item\_Description | pod\_det.pod\_desc1 | itemList.description | Name | EKPO.TXZ01 | Description | DESCRIPTION | description |
143
+ | quantity | QUANTITY | tdipu001.qoor | OrderQty | Quantity | pod\_det.pod\_qty\_ord | itemList.quantity | PurchQty | EKPO.MENGE | QtyOrdered | QTYORDERED | quantity |
144
+ | unit\_price | UNIT\_PRICE | tdipu001.pric | UnitCost | Unit\_Cost | pod\_det.pod\_pur\_cost | itemList.rate | PurchPrice | EKPO.NETPR | BuyUnitPrice | UNITCOST | unit\_price |
145
+ | line\_total | AMOUNT | tdipu001.amt | DocExtCost | Extended\_Amount | (qty \* pur\_cost) | itemList.amount | LineAmount | EKPO.NETWR | LineAmount | AMOUNT | line\_total |
146
+ | tax\_code | — | — | TaxCatID | Tax\_Code\_ID | pod\_det.pod\_taxc | itemList.taxCode | TaxGroup | EKPO.MWSKZ | TaxCode | TAXDETAILID | tax\_code |
147
+
148
+ ➡️ **CDF Fields & SQL Types:**
149
+
150
+ * `po_id` – VARCHAR(64)
151
+ * `po_date` – DATE
152
+ * `vendor_id` – VARCHAR(64)
153
+ * `status` – VARCHAR(32)
154
+ * `currency` – VARCHAR(8)
155
+ * `total_amount` – DECIMAL(18,2)
156
+ * `expected_receipt_date` – DATE
157
+ * `notes` – TEXT
158
+ * `item_id` – VARCHAR(64)
159
+ * `description` – TEXT
160
+ * `quantity` – INT
161
+ * `unit_price` – DECIMAL(18,2)
162
+ * `line_total` – DECIMAL(18,2)
163
+ * `tax_code` – VARCHAR(32)
164
+
165
+ ### 🏷️ Inventory Items Fields Comparison
166
+
167
+ | Oracle Fusion | Infor M3 | Infor LN | Epicor Kinetic | Workday | QAD ERP | NetSuite | Microsoft Dynamics | SAP ERP | IFS Cloud | Sage Intacct | ➡️ CDF Field |
168
+ | ---------------------- | -------- | ------------- | --------------- | --------------------------- | ---------------------------- | ------------------- | ------------------ | ------------------- | ------------------- | ------------------- | --------------------- |
169
+ | ITEM\_NUMBER | ITNO | tcibd001.item | PartNum | Item\_Identifier | pt\_mstr.pt\_part | itemId | ItemId | MARA.MATNR | PartNo | ITEMID | item\_id |
170
+ | DESCRIPTION | ITDS | tcibd001.dsca | PartDescription | Item\_Description | pt\_mstr.pt\_desc1 | displayName | Name | MAKT.MAKTX | Description | NAME | item\_name |
171
+ | LONG\_DESCRIPTION | FUDS | — | SearchWord | Extended\_Item\_Description | pt\_mstr.pt\_desc2 | description | ProductName | MAKT.MAKTX | DetailedDescription | DESCRIPTION | description |
172
+ | PURCHASING\_ITEM\_FLAG | — | — | BuyToOrder | — | — | purchaseDescription | — | — | PurchaseDescription | PURCHASEDESCRIPTION | purchase\_description |
173
+ | CUSTOMER\_ORDER\_FLAG | — | — | Sellable | — | — | salesDescription | — | — | SalesDescription | SALEDESCRIPTION | sales\_description |
174
+ | LIST\_PRICE | SAPR | tcibd001.sapr | UnitPrice | — | pt\_mstr.pt\_price | basePrice | Price | MBEW\.STPRS | SalesPrice | PRICE | base\_price |
175
+ | UNIT\_COST | PUPR | tcibd001.copr | AvgMaterialCost | Unit\_Cost | pt\_mstr.pt\_pur\_price | cost | CostPrice | MBEW\.VPRSV | StandardCost | UNITCOST | cost\_price |
176
+ | PRIMARY\_UOM\_CODE | UNMS | tcibd001.cuni | IUM | Unit\_of\_Measure\_Name | pt\_mstr.pt\_um | unitsType | UnitId | MARM.MEINH | UnitOfMeasure | UOM | unit\_type |
177
+ | ITEM\_STATUS\_CODE | STAT | tcibd001.itst | InActive | Item\_Inactive | pt\_mstr.pt\_status (invert) | isInactive | Stopped | MARA.MSTAE (invert) | Obsolete | INACTIVE | is\_active |
178
+ | (Calculated Qty) | — | — | — | On\_Hand\_Stock\_Quantity | — | quantityOnHand | InventQtyAvail | MARD.LABST | QtyOnHand | QTYONHAND | quantity\_on\_hand |
179
+ | MIN\_MINMAX\_QUANTITY | REOP | tcibd001.safa | MinOrderQty | Reorder\_Point\_Quantity | pt\_mstr.pt\_rop | reorderPoint | ReorderPoint | MARC.BESGR | ReorderPoint | REORDERPOINT | reorder\_point |
180
+ | DEFAULT\_BUYER\_ID | SUNO | tdipu001.suno | PrimPRec | Default\_Supplier\_ID | pt\_mstr.pt\_vend | preferredVendor | PreferredVendor | EINA.LIFNR | PreferredSupplierId | PREFERREDVENDORID | preferred\_vendor\_id |
181
+
182
+ ➡️ **CDF Fields & SQL Types:**
183
+
184
+ * `item_id` – VARCHAR(64)
185
+ * `item_name` – VARCHAR(255)
186
+ * `description` – TEXT
187
+ * `purchase_description` – TEXT
188
+ * `sales_description` – TEXT
189
+ * `base_price` – DECIMAL(18,2)
190
+ * `cost_price` – DECIMAL(18,2)
191
+ * `unit_type` – VARCHAR(32)
192
+ * `is_active` – BOOLEAN
193
+ * `quantity_on_hand` – INT
194
+ * `reorder_point` – INT
195
+ * `preferred_vendor_id` – VARCHAR(64)
README.md ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GDF to CDF Converter
2
+
3
+ A modular Python + FastAPI-based codebase to convert General Data Frames (GDFs) from ERP exports into a normalized Common Data Frame (CDF) format.
4
+
5
+ ## Features
6
+
7
+ - 🔄 **Template-driven mapping** with ERP auto-detection using Jaccard similarity
8
+ - 🤖 **LLM fallback** using LLaMA-3-70B-Instruct for unknown ERP schemas
9
+ - 📊 **Pydantic models** for input/output validation
10
+ - 🚀 **FastAPI backend** with REST API endpoints
11
+ - 💻 **CLI tool** for batch processing CSV/JSON files
12
+ - 🎯 **Support for 5 entity types**: sales_orders, customers, invoices, purchase_orders, inventory_items
13
+ - 🏢 **Multi-ERP support** with extensible template system
14
+
15
+ ## Quick Start
16
+
17
+ ### Installation
18
+
19
+ ```bash
20
+ # Clone the repository
21
+ git clone <repository-url>
22
+ cd cleanflowai
23
+
24
+ # Install dependencies
25
+ pip install -r requirements.txt
26
+
27
+ # Optional: Set up OpenAI API key for LLM fallback
28
+ export OPENAI_API_KEY="your-api-key-here"
29
+ ```
30
+
31
+ ### Basic Usage
32
+
33
+ #### Python API
34
+
35
+ ```python
36
+ from mapper import GDFToCDFConverter, EntityType
37
+
38
+ # Create converter
39
+ converter = GDFToCDFConverter()
40
+
41
+ # Convert data
42
+ sample_data = [
43
+ {
44
+ "tranId": "SO1001",
45
+ "trandate": "2025-08-04",
46
+ "entity": "CUST01",
47
+ "total": 1249.0
48
+ }
49
+ ]
50
+
51
+ result = converter.convert(
52
+ gdf_data=sample_data,
53
+ entity=EntityType.SALES_ORDERS,
54
+ erp="NetSuite" # Optional - will auto-detect if omitted
55
+ )
56
+
57
+ print(result.data) # Converted CDF data
58
+ ```
59
+
60
+ #### CLI Tool
61
+
62
+ ```bash
63
+ # Convert single file
64
+ python main.py convert sales_orders input.csv -o output.csv
65
+
66
+ # Batch convert multiple files
67
+ python main.py batch sales_orders *.csv --output-dir ./converted/
68
+
69
+ # Analyze file without conversion
70
+ python main.py analyze sales_orders sample.csv --verbose
71
+
72
+ # List supported entities and ERPs
73
+ python main.py list-entities
74
+ python main.py list-erps
75
+ ```
76
+
77
+ #### FastAPI Server
78
+
79
+ ```bash
80
+ # Start the API server
81
+ python api.py
82
+ # or
83
+ uvicorn api:app --reload
84
+
85
+ # Access API documentation at http://localhost:8000/docs
86
+ ```
87
+
88
+ ## API Endpoints
89
+
90
+ ### Core Conversion
91
+
92
+ - `POST /convert` - Convert JSON data to CDF format
93
+ - `POST /convert/file` - Convert uploaded CSV/JSON file
94
+ - `POST /analyze` - Analyze data and get mapping information
95
+ - `POST /validate` - Validate GDF data structure
96
+
97
+ ### Information
98
+
99
+ - `GET /entities` - List supported entity types
100
+ - `GET /erps` - List supported ERP systems
101
+ - `GET /health` - Health check endpoint
102
+
103
+ ### Example API Usage
104
+
105
+ ```bash
106
+ # Convert data via API
107
+ curl -X POST "http://localhost:8000/convert" \
108
+ -H "Content-Type: application/json" \
109
+ -d '{
110
+ "data": [{"tranId": "SO1001", "trandate": "2025-08-04", "entity": "CUST01", "total": 1249.0}],
111
+ "entity": "sales_orders",
112
+ "erp": "NetSuite"
113
+ }'
114
+
115
+ # Upload and convert file
116
+ curl -X POST "http://localhost:8000/convert/file" \
117
+ -F "file=@sample.csv" \
118
+ -F "entity=sales_orders" \
119
+ -F "erp=NetSuite"
120
+ ```
121
+
122
+ ## Architecture
123
+
124
+ ### Core Components
125
+
126
+ ```
127
+ mapper/
128
+ ├── __init__.py # Package initialization and exports
129
+ ├── models.py # Pydantic models for validation
130
+ ├── template_loader.py # Template loading and validation
131
+ ├── erp_resolver.py # ERP auto-detection using Jaccard similarity
132
+ ├── llm_handler.py # LLM fallback for unknown mappings
133
+ └── converter.py # Main conversion orchestration
134
+
135
+ api.py # FastAPI backend server
136
+ main.py # CLI tool
137
+ template.json # ERP to CDF mapping templates
138
+ requirements.txt # Python dependencies
139
+ ```
140
+
141
+ ### Data Flow
142
+
143
+ 1. **Input**: GDF data from ERP export (CSV/JSON/DataFrame)
144
+ 2. **ERP Detection**: Jaccard similarity matching against known templates
145
+ 3. **Mapping Resolution**: Template-based or LLM-inferred column mapping
146
+ 4. **Transformation**: Apply mapping, add missing columns, type conversion
147
+ 5. **Output**: CDF-compliant data with standardized schema
148
+
149
+ ## Supported Entities
150
+
151
+ | Entity | Description | CDF Fields |
152
+ |--------|-------------|------------|
153
+ | `sales_orders` | Sales transactions with line items | order_id, order_date, customer_id, status, currency, total_amount, notes, item_id, description, quantity, unit_price, line_total, tax_code |
154
+ | `customers` | Customer master data | customer_id, customer_name, contact_email, phone_number, alt_phone, is_company, status, currency, created_date, last_modified |
155
+ | `invoices` | Invoice documents | invoice_id, invoice_date, customer_id, status, currency, total_amount, due_date, notes, item_id, description, quantity, unit_price, line_total, tax_code |
156
+ | `purchase_orders` | Purchase orders | po_id, po_date, vendor_id, status, currency, total_amount, expected_receipt_date, notes, item_id, description, quantity, unit_price, line_total, tax_code |
157
+ | `inventory_items` | Product catalog | 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 |
158
+
159
+ ## ERP Systems
160
+
161
+ Currently supported ERP systems in `template.json`:
162
+
163
+ - **NetSuite** - Complete mappings for all entities
164
+ - **SAP ERP** - Extensible template structure
165
+ - **Oracle Fusion** - Ready for template expansion
166
+ - **Microsoft Dynamics** - Template framework available
167
+ - **Infor M3/LN** - Mapping structure defined
168
+
169
+ ## Configuration
170
+
171
+ ### Template Structure
172
+
173
+ The `template.json` file defines mappings from ERP-specific column names to CDF standard names:
174
+
175
+ ```json
176
+ {
177
+ "NetSuite": {
178
+ "sales_orders": {
179
+ "tranId": "order_id",
180
+ "trandate": "order_date",
181
+ "entity": "customer_id",
182
+ "total": "total_amount"
183
+ }
184
+ },
185
+ "CDF_META": {
186
+ "sales_orders": [
187
+ "order_id", "order_date", "customer_id", "status",
188
+ "currency", "total_amount", "notes", "item_id",
189
+ "description", "quantity", "unit_price", "line_total", "tax_code"
190
+ ]
191
+ }
192
+ }
193
+ ```
194
+
195
+ ### Environment Variables
196
+
197
+ ```bash
198
+ # Optional: OpenAI API key for LLM fallback
199
+ OPENAI_API_KEY=your-api-key-here
200
+
201
+ # Optional: Custom template file path
202
+ TEMPLATE_PATH=./custom-template.json
203
+ ```
204
+
205
+ ## Advanced Usage
206
+
207
+ ### Custom LLM Handler
208
+
209
+ ```python
210
+ from mapper import GDFToCDFConverter, LLMHandler
211
+
212
+ # Use custom LLM configuration
213
+ llm_handler = LLMHandler(
214
+ model_name="gpt-4o",
215
+ temperature=0.0,
216
+ max_retries=3
217
+ )
218
+
219
+ converter = GDFToCDFConverter(llm_handler=llm_handler)
220
+ ```
221
+
222
+ ### Batch Processing
223
+
224
+ ```python
225
+ from pathlib import Path
226
+ from mapper import create_converter, EntityType
227
+
228
+ converter = create_converter()
229
+
230
+ # Process multiple files
231
+ input_dir = Path("./data")
232
+ output_dir = Path("./converted")
233
+
234
+ for csv_file in input_dir.glob("*.csv"):
235
+ data = pd.read_csv(csv_file).to_dict('records')
236
+ result = converter.convert(data, EntityType.SALES_ORDERS)
237
+
238
+ if result.success:
239
+ output_file = output_dir / f"{csv_file.stem}_cdf.json"
240
+ with output_file.open('w') as f:
241
+ json.dump(result.data, f, indent=2, default=str)
242
+ ```
243
+
244
+ ### Custom Template
245
+
246
+ ```python
247
+ from pathlib import Path
248
+ from mapper import GDFToCDFConverter
249
+
250
+ # Use custom template file
251
+ converter = GDFToCDFConverter(
252
+ template_path=Path("./my-custom-template.json")
253
+ )
254
+ ```
255
+
256
+ ## Testing
257
+
258
+ ### Run Tests
259
+
260
+ ```bash
261
+ # Install test dependencies
262
+ pip install pytest pytest-asyncio httpx
263
+
264
+ # Run tests
265
+ pytest tests/
266
+
267
+ # Run with coverage
268
+ pytest --cov=mapper tests/
269
+ ```
270
+
271
+ ### Test API Endpoints
272
+
273
+ ```bash
274
+ # Start server
275
+ python api.py
276
+
277
+ # Test endpoints
278
+ curl http://localhost:8000/health
279
+ curl http://localhost:8000/entities
280
+ curl http://localhost:8000/erps
281
+ ```
282
+
283
+ ## Development
284
+
285
+ ### Code Formatting
286
+
287
+ ```bash
288
+ # Format code
289
+ black mapper/ api.py main.py
290
+
291
+ # Sort imports
292
+ isort mapper/ api.py main.py
293
+
294
+ # Type checking
295
+ mypy mapper/
296
+ ```
297
+
298
+ ### Adding New ERP Systems
299
+
300
+ 1. Update `template.json` with new ERP mappings:
301
+
302
+ ```json
303
+ {
304
+ "YourERP": {
305
+ "sales_orders": {
306
+ "order_number": "order_id",
307
+ "order_dt": "order_date",
308
+ "customer_code": "customer_id"
309
+ }
310
+ }
311
+ }
312
+ ```
313
+
314
+ 2. Test the new mappings:
315
+
316
+ ```python
317
+ result = converter.convert(data, EntityType.SALES_ORDERS, erp="YourERP")
318
+ ```
319
+
320
+ ### Extending Entity Types
321
+
322
+ 1. Add new entity to `EntityType` enum in `models.py`
323
+ 2. Create corresponding Pydantic model
324
+ 3. Update `template.json` with CDF_META schema
325
+ 4. Add data type mappings in `converter.py`
326
+
327
+ ## Troubleshooting
328
+
329
+ ### Common Issues
330
+
331
+ **LLM API Key Missing**
332
+ ```
333
+ ValueError: API key required for LLM operations
334
+ ```
335
+ Solution: Set `OPENAI_API_KEY` environment variable or use mock LLM
336
+
337
+ **Template File Not Found**
338
+ ```
339
+ FileNotFoundError: Template file not found: template.json
340
+ ```
341
+ Solution: Ensure `template.json` exists in working directory
342
+
343
+ **Low ERP Detection Confidence**
344
+ ```
345
+ No column mapping could be determined
346
+ ```
347
+ Solution: Use LLM fallback or specify ERP explicitly
348
+
349
+ ### Debug Mode
350
+
351
+ ```python
352
+ # Enable verbose logging
353
+ import logging
354
+ logging.basicConfig(level=logging.DEBUG)
355
+
356
+ # Use mock LLM for testing
357
+ converter = GDFToCDFConverter(use_mock_llm=True)
358
+ ```
359
+
360
+ ## Contributing
361
+
362
+ 1. Fork the repository
363
+ 2. Create a feature branch
364
+ 3. Make your changes
365
+ 4. Add tests for new functionality
366
+ 5. Run the test suite
367
+ 6. Submit a pull request
368
+
369
+ ## License
370
+
371
+ This project is licensed under the MIT License - see the LICENSE file for details.
372
+
373
+ ## Support
374
+
375
+ For questions, issues, or feature requests:
376
+
377
+ 1. Check the [documentation](README.md)
378
+ 2. Search existing [issues](../../issues)
379
+ 3. Create a new issue with detailed information
380
+ 4. For API questions, check the interactive docs at `/docs`
381
+
382
+ ---
383
+
384
+ **Built with ❤️ for seamless ERP data integration**
api.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI backend for GDF to CDF conversion service.
3
+ Provides REST API endpoints for converting ERP data to Common Data Frame format.
4
+ """
5
+
6
+ import io
7
+ import json
8
+ import pandas as pd
9
+ from pathlib import Path
10
+ from typing import Dict, List, Optional, Union
11
+ from fastapi import FastAPI, HTTPException, UploadFile, File, Form, Query
12
+ from fastapi.middleware.cors import CORSMiddleware
13
+ from fastapi.responses import JSONResponse
14
+ from pydantic import ValidationError
15
+
16
+ from mapper import (
17
+ GDFToCDFConverter,
18
+ EntityType,
19
+ ConversionRequest,
20
+ ConversionResponse,
21
+ create_converter
22
+ )
23
+
24
+ # Initialize FastAPI app
25
+ app = FastAPI(
26
+ title="GDF to CDF Conversion API",
27
+ description="Convert General Data Frames from ERP exports to Common Data Frame format",
28
+ version="1.0.0",
29
+ docs_url="/docs",
30
+ redoc_url="/redoc"
31
+ )
32
+
33
+ # Add CORS middleware
34
+ app.add_middleware(
35
+ CORSMiddleware,
36
+ allow_origins=["*"], # Configure appropriately for production
37
+ allow_credentials=True,
38
+ allow_methods=["*"],
39
+ allow_headers=["*"],
40
+ )
41
+
42
+ # Global converter instance
43
+ converter = None
44
+
45
+ def get_converter() -> GDFToCDFConverter:
46
+ """Get or create converter instance."""
47
+ global converter
48
+ if converter is None:
49
+ try:
50
+ converter = create_converter(use_mock_llm=False)
51
+ except Exception:
52
+ # Fallback to mock LLM if real LLM setup fails
53
+ converter = create_converter(use_mock_llm=True)
54
+ return converter
55
+
56
+
57
+ @app.on_event("startup")
58
+ async def startup_event():
59
+ """Initialize converter on startup."""
60
+ get_converter()
61
+
62
+
63
+ @app.get("/")
64
+ async def root():
65
+ """Root endpoint with API information."""
66
+ return {
67
+ "message": "GDF to CDF Conversion API",
68
+ "version": "1.0.0",
69
+ "docs": "/docs",
70
+ "endpoints": {
71
+ "convert": "/convert",
72
+ "convert_file": "/convert/file",
73
+ "analyze": "/analyze",
74
+ "health": "/health",
75
+ "entities": "/entities",
76
+ "erps": "/erps"
77
+ }
78
+ }
79
+
80
+
81
+ @app.get("/health")
82
+ async def health_check():
83
+ """Health check endpoint."""
84
+ try:
85
+ conv = get_converter()
86
+ return {
87
+ "status": "healthy",
88
+ "converter_initialized": conv is not None,
89
+ "template_loaded": conv.template_loader._template_cache is not None
90
+ }
91
+ except Exception as e:
92
+ return {
93
+ "status": "unhealthy",
94
+ "error": str(e)
95
+ }
96
+
97
+
98
+ @app.get("/entities")
99
+ async def get_supported_entities():
100
+ """Get list of supported entity types."""
101
+ return {
102
+ "entities": [entity.value for entity in EntityType],
103
+ "descriptions": {
104
+ "sales_orders": "Sales order transactions with line items",
105
+ "customers": "Customer master data and contact information",
106
+ "invoices": "Invoice documents with billing details",
107
+ "purchase_orders": "Purchase orders and procurement data",
108
+ "inventory_items": "Product catalog and inventory information"
109
+ }
110
+ }
111
+
112
+
113
+ @app.get("/erps")
114
+ async def get_supported_erps():
115
+ """Get list of supported ERP systems."""
116
+ try:
117
+ conv = get_converter()
118
+ erp_names = conv.template_loader.get_erp_names()
119
+ return {
120
+ "erp_systems": erp_names,
121
+ "count": len(erp_names)
122
+ }
123
+ except Exception as e:
124
+ raise HTTPException(status_code=500, detail=f"Failed to load ERP systems: {str(e)}")
125
+
126
+
127
+ @app.post("/convert", response_model=ConversionResponse)
128
+ async def convert_data(request: ConversionRequest):
129
+ """Convert GDF data to CDF format via JSON payload."""
130
+ try:
131
+ conv = get_converter()
132
+ result = conv.convert(
133
+ gdf_data=request.data,
134
+ entity=request.entity,
135
+ erp=request.erp,
136
+ use_llm=request.use_llm
137
+ )
138
+ return result
139
+ except Exception as e:
140
+ raise HTTPException(status_code=500, detail=f"Conversion failed: {str(e)}")
141
+
142
+
143
+ @app.post("/convert/file")
144
+ async def convert_file(
145
+ file: UploadFile = File(...),
146
+ entity: EntityType = Form(...),
147
+ erp: Optional[str] = Form(None),
148
+ use_llm: bool = Form(True)
149
+ ):
150
+ """Convert GDF data from uploaded CSV/JSON file."""
151
+ try:
152
+ # Read file content
153
+ content = await file.read()
154
+
155
+ # Parse file based on extension
156
+ if file.filename.lower().endswith('.csv'):
157
+ df = pd.read_csv(io.StringIO(content.decode('utf-8')))
158
+ data = df.to_dict('records')
159
+ elif file.filename.lower().endswith('.json'):
160
+ data = json.loads(content.decode('utf-8'))
161
+ else:
162
+ raise HTTPException(
163
+ status_code=400,
164
+ detail="Unsupported file format. Only CSV and JSON files are supported."
165
+ )
166
+
167
+ # Convert data
168
+ conv = get_converter()
169
+ result = conv.convert(
170
+ gdf_data=data,
171
+ entity=entity,
172
+ erp=erp,
173
+ use_llm=use_llm
174
+ )
175
+
176
+ return result
177
+
178
+ except json.JSONDecodeError:
179
+ raise HTTPException(status_code=400, detail="Invalid JSON file format")
180
+ except pd.errors.EmptyDataError:
181
+ raise HTTPException(status_code=400, detail="Empty CSV file")
182
+ except Exception as e:
183
+ raise HTTPException(status_code=500, detail=f"File processing failed: {str(e)}")
184
+
185
+
186
+ @app.post("/analyze")
187
+ async def analyze_data(
188
+ data: Union[List[Dict], Dict] = None,
189
+ entity: EntityType = Query(...),
190
+ erp: Optional[str] = Query(None)
191
+ ):
192
+ """Analyze GDF data and get mapping information without conversion."""
193
+ try:
194
+ if not data:
195
+ raise HTTPException(status_code=400, detail="No data provided")
196
+
197
+ # Extract columns from data
198
+ if isinstance(data, dict):
199
+ columns = list(data.keys())
200
+ elif isinstance(data, list) and data:
201
+ columns = list(data[0].keys()) if data[0] else []
202
+ else:
203
+ raise HTTPException(status_code=400, detail="Invalid data format")
204
+
205
+ conv = get_converter()
206
+ analysis = conv.get_mapping_info(columns, entity, erp)
207
+
208
+ return {
209
+ "analysis": analysis,
210
+ "recommendations": _generate_recommendations(analysis)
211
+ }
212
+
213
+ except Exception as e:
214
+ raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}")
215
+
216
+
217
+ @app.post("/analyze/file")
218
+ async def analyze_file(
219
+ file: UploadFile = File(...),
220
+ entity: EntityType = Form(...),
221
+ erp: Optional[str] = Form(None)
222
+ ):
223
+ """Analyze uploaded file and get mapping information."""
224
+ try:
225
+ # Read file content
226
+ content = await file.read()
227
+
228
+ # Parse file to get columns
229
+ if file.filename.lower().endswith('.csv'):
230
+ df = pd.read_csv(io.StringIO(content.decode('utf-8')))
231
+ columns = list(df.columns)
232
+ elif file.filename.lower().endswith('.json'):
233
+ data = json.loads(content.decode('utf-8'))
234
+ if isinstance(data, list) and data:
235
+ columns = list(data[0].keys())
236
+ elif isinstance(data, dict):
237
+ columns = list(data.keys())
238
+ else:
239
+ raise HTTPException(status_code=400, detail="Cannot extract columns from JSON structure")
240
+ else:
241
+ raise HTTPException(
242
+ status_code=400,
243
+ detail="Unsupported file format. Only CSV and JSON files are supported."
244
+ )
245
+
246
+ conv = get_converter()
247
+ analysis = conv.get_mapping_info(columns, entity, erp)
248
+
249
+ return {
250
+ "filename": file.filename,
251
+ "analysis": analysis,
252
+ "recommendations": _generate_recommendations(analysis)
253
+ }
254
+
255
+ except Exception as e:
256
+ raise HTTPException(status_code=500, detail=f"File analysis failed: {str(e)}")
257
+
258
+
259
+ @app.post("/validate")
260
+ async def validate_data(data: Union[List[Dict], Dict]):
261
+ """Validate GDF data structure and content."""
262
+ try:
263
+ conv = get_converter()
264
+ validation = conv.validate_gdf_data(data)
265
+ return validation
266
+ except Exception as e:
267
+ raise HTTPException(status_code=500, detail=f"Validation failed: {str(e)}")
268
+
269
+
270
+ def _generate_recommendations(analysis: Dict) -> Dict:
271
+ """Generate recommendations based on analysis results."""
272
+ recommendations = {
273
+ "suggested_erp": None,
274
+ "confidence": "low",
275
+ "actions": []
276
+ }
277
+
278
+ suggestions = analysis.get("erp_suggestions", [])
279
+
280
+ if suggestions:
281
+ best_match = suggestions[0]
282
+ recommendations["suggested_erp"] = best_match["erp"]
283
+
284
+ if best_match["above_threshold"]:
285
+ recommendations["confidence"] = "high"
286
+ recommendations["actions"].append(
287
+ f"Use ERP '{best_match['erp']}' with {best_match['similarity_score']:.2%} confidence"
288
+ )
289
+ else:
290
+ recommendations["confidence"] = "medium"
291
+ recommendations["actions"].append(
292
+ f"Consider ERP '{best_match['erp']}' or use LLM fallback"
293
+ )
294
+ else:
295
+ recommendations["actions"].append("Use LLM fallback for column mapping")
296
+
297
+ # Check for missing mappings
298
+ template_mapping = analysis.get("template_mapping")
299
+ if template_mapping:
300
+ gdf_cols = set(analysis.get("gdf_columns", []))
301
+ mapped_cols = set(template_mapping.keys())
302
+ unmapped = gdf_cols - mapped_cols
303
+
304
+ if unmapped:
305
+ recommendations["actions"].append(
306
+ f"Review unmapped columns: {', '.join(unmapped)}"
307
+ )
308
+
309
+ return recommendations
310
+
311
+
312
+ # Error handlers
313
+ @app.exception_handler(ValidationError)
314
+ async def validation_exception_handler(request, exc):
315
+ """Handle Pydantic validation errors."""
316
+ return JSONResponse(
317
+ status_code=422,
318
+ content={
319
+ "error": "Validation Error",
320
+ "details": exc.errors()
321
+ }
322
+ )
323
+
324
+
325
+ @app.exception_handler(ValueError)
326
+ async def value_error_handler(request, exc):
327
+ """Handle value errors."""
328
+ return JSONResponse(
329
+ status_code=400,
330
+ content={
331
+ "error": "Invalid Input",
332
+ "message": str(exc)
333
+ }
334
+ )
335
+
336
+
337
+ if __name__ == "__main__":
338
+ import uvicorn
339
+ uvicorn.run(
340
+ "api:app",
341
+ host="0.0.0.0",
342
+ port=8000,
343
+ reload=True,
344
+ log_level="info"
345
+ )
explain.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ It first takes the input and then
2
+
3
+ when the ERP type is known
gdf_to_cdf_algorithm.md ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GDF to CDF Conversion Algorithm
2
+
3
+ ## Goal
4
+ Convert an input General Data-Frame (GDF) exported from any ERP into the standardized Common Data Frame (CDF) layout.
5
+
6
+ ## Inputs
7
+ 1. GDF – a tabular dataset whose columns are ERP-specific.
8
+ 2. Entity – one of: sales_orders, customers, invoices, purchase_orders, inventory_items.
9
+ 3. template.json – ERP + entity-specific mappings from GDF to CDF.
10
+ 4. ERP name (optional) – if known, bypass detection.
11
+
12
+ ## Steps
13
+ 1. Load template.json
14
+ 2. If ERP is known, use its mapping. If not:
15
+ - Compute Jaccard similarity between GDF columns and each ERP’s template
16
+ - Pick ERP with best score above threshold
17
+ 3. If mapping is unavailable:
18
+ - Use an LLM (LLaMA 3 70B Instruct) to infer column mappings
19
+ 4. Rename columns, insert missing ones as null
20
+ 5. Return result in CDF format, with correct column order and SQL data types.
21
+
22
+ ## Output
23
+ A DataFrame in valid CDF format.
gdf_to_cdf_mapper.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # gdf_to_cdf_mapper.py
2
+ """
3
+ Algorithm & reference implementation to convert a General Data‑Frame (GDF)
4
+ coming from *any* ERP export into the unified Common Data Frame (CDF)
5
+ format defined in the companion document.
6
+
7
+ Key capabilities
8
+ ----------------
9
+ 1. **Template‑Driven Mapping** – Uses a `template.json` file that stores the
10
+ per‑ERP, per‑entity column mappings ⟨GDF ➜ CDF⟩.
11
+ 2. **Automatic ERP Detection** – If the ERP type is *not* supplied, the
12
+ library inspects incoming columns and scores each ERP template (Jaccard
13
+ similarity) to choose the most likely source.
14
+ 3. **LLM‑Assisted Fallback** – When no ERP template reaches a similarity
15
+ threshold, a Large‑Language‑Model (via LangChain) is invoked to infer
16
+ the mapping.
17
+ 4. **Graceful Degradation** – Missing GDF columns are created with
18
+ `pd.NA` so the resulting CDF preserves schema integrity.
19
+
20
+ Suggested LLM 🔮
21
+ ----------------
22
+ For the AI fallback, "**GPT‑4o**" (OpenAI) offers the best blend of
23
+ reliability and reasoning for column‑name inference. If an open‑source
24
+ model is required, **Llama‑3‑70B‑Instruct** is a strong alternative.
25
+
26
+ Usage
27
+ -----
28
+ ```python
29
+ from gdf_to_cdf_mapper import map_to_cdf
30
+ cdf_df = map_to_cdf(gdf_df, entity="sales_orders", erp="NetSuite")
31
+ ```
32
+ `erp` may be omitted to trigger auto‑detection.
33
+ """
34
+
35
+ from __future__ import annotations
36
+
37
+ import json
38
+ from pathlib import Path
39
+ from typing import Dict, List, Optional, Tuple
40
+
41
+ import pandas as pd
42
+ from langchain.chat_models import ChatOpenAI # Requires: langchain>=0.1.0
43
+ from langchain.schema import AIMessage, HumanMessage
44
+
45
+ _TEMPLATE_PATH = Path("template.json")
46
+ _SIM_THRESHOLD = 0.4 # min. Jaccard similarity to accept ERP template
47
+
48
+
49
+ def _load_template(path: Path = _TEMPLATE_PATH) -> Dict[str, Dict[str, Dict[str, str]]]:
50
+ """Load mapping template: ERP ➜ entity ➜ {GDF_col: CDF_col}."""
51
+ with path.open() as fp:
52
+ return json.load(fp)
53
+
54
+
55
+ def _jaccard(a: set, b: set) -> float:
56
+ return len(a & b) / max(1, len(a | b))
57
+
58
+
59
+ def _detect_erp(gdf_cols: List[str], template: dict) -> Optional[str]:
60
+ scores: List[Tuple[str, float]] = []
61
+ gdf_set = set(gdf_cols)
62
+ for erp, entities in template.items():
63
+ # Aggregate all columns across entities for scoring
64
+ template_cols = {col for mapping in entities.values() for col in mapping.keys()}
65
+ scores.append((erp, _jaccard(gdf_set, template_cols)))
66
+ scores.sort(key=lambda x: x[1], reverse=True)
67
+ if scores[0][1] >= _SIM_THRESHOLD:
68
+ return scores[0][0]
69
+ return None
70
+
71
+
72
+ def _llm_infer_mapping(gdf_cols: List[str], cdf_cols: List[str], entity: str, model_name: str = "gpt-4o") -> Dict[str, str]:
73
+ """Use an LLM to guess column mappings when templates fail."""
74
+ llm = ChatOpenAI(model_name=model_name, temperature=0)
75
+ prompt = (
76
+ "You are a data integration expert. Given these source columns: "
77
+ f"{gdf_cols}\nand the target CDF columns for entity '{entity}': {cdf_cols}.\n"
78
+ "Return a JSON mapping where keys are *exact* source column names and values are the best‑matching CDF column names."
79
+ )
80
+ response = llm([HumanMessage(content=prompt)])
81
+ try:
82
+ return json.loads(response.content)
83
+ except Exception:
84
+ raise ValueError("LLM failed to return valid JSON mapping.")
85
+
86
+
87
+ def map_to_cdf(
88
+ gdf: pd.DataFrame,
89
+ *,
90
+ entity: str,
91
+ erp: Optional[str] = None,
92
+ template_path: Path = _TEMPLATE_PATH,
93
+ use_llm: bool = True,
94
+ ) -> pd.DataFrame:
95
+ """Convert a GDF DataFrame to CDF.
96
+
97
+ Parameters
98
+ ----------
99
+ gdf : pd.DataFrame
100
+ Incoming general data frame.
101
+ entity : str
102
+ One of: "sales_orders", "customers", "invoices", "purchase_orders", "inventory_items".
103
+ erp : str, optional
104
+ Name of ERP in the template. If ``None``, auto‑detect.
105
+ use_llm : bool, default True
106
+ Whether to fall back to LLM mapping if ERP template not resolved.
107
+ """
108
+ template = _load_template(template_path)
109
+
110
+ # Step 1 – determine ERP
111
+ erp_name = erp or _detect_erp(list(gdf.columns), template)
112
+ mapping: Dict[str, str]
113
+ if erp_name and entity in template.get(erp_name, {}):
114
+ mapping = template[erp_name][entity]
115
+ elif use_llm:
116
+ cdf_cols = list(template["CDF_META"][entity]) # assumes meta list exists in template
117
+ mapping = _llm_infer_mapping(list(gdf.columns), cdf_cols, entity)
118
+ else:
119
+ raise ValueError("Unable to resolve ERP mapping and use_llm=False")
120
+
121
+ # Step 2 – perform renaming / projection
122
+ cdf_df = gdf.rename(columns=mapping)
123
+
124
+ # Step 3 – add missing CDF columns with NA
125
+ expected_cols = list(template["CDF_META"][entity])
126
+ for col in expected_cols:
127
+ if col not in cdf_df.columns:
128
+ cdf_df[col] = pd.NA
129
+
130
+ # Step 4 – reorder columns to standard CDF order
131
+ cdf_df = cdf_df[expected_cols]
132
+ return cdf_df
133
+
134
+
135
+ if __name__ == "__main__":
136
+ # --- Example demo ---
137
+ sample = pd.DataFrame(
138
+ {
139
+ "tranId": ["SO1001"],
140
+ "trandate": ["2025-08-04"],
141
+ "entity": ["CUST01"],
142
+ "total": [1249.0],
143
+ }
144
+ )
145
+ cdf = map_to_cdf(sample, entity="sales_orders", erp="NetSuite")
146
+ print(cdf.head())
main.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLI tool for GDF to CDF conversion.
3
+ Provides command-line interface for batch converting CSV/JSON files.
4
+ """
5
+
6
+ import argparse
7
+ import json
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import List, Optional
11
+
12
+ import pandas as pd
13
+
14
+ from mapper import (
15
+ GDFToCDFConverter,
16
+ EntityType,
17
+ create_converter
18
+ )
19
+
20
+
21
+ def setup_argparser() -> argparse.ArgumentParser:
22
+ """Set up command line argument parser."""
23
+ parser = argparse.ArgumentParser(
24
+ description="Convert GDF files from ERP exports to CDF format",
25
+ formatter_class=argparse.RawDescriptionHelpFormatter,
26
+ epilog="""
27
+ Examples:
28
+ # Convert single file with auto-detection
29
+ python main.py convert sales_orders input.csv -o output.csv
30
+
31
+ # Convert with specific ERP
32
+ python main.py convert customers data.json --erp NetSuite -o result.json
33
+
34
+ # Batch convert multiple files
35
+ python main.py batch sales_orders *.csv --output-dir ./converted/
36
+
37
+ # Analyze file without conversion
38
+ python main.py analyze sales_orders sample.csv
39
+
40
+ # List supported entities and ERPs
41
+ python main.py list-entities
42
+ python main.py list-erps
43
+ """
44
+ )
45
+
46
+ subparsers = parser.add_subparsers(dest='command', help='Available commands')
47
+
48
+ # Convert command
49
+ convert_parser = subparsers.add_parser('convert', help='Convert single file')
50
+ convert_parser.add_argument('entity', choices=[e.value for e in EntityType],
51
+ help='Entity type to convert')
52
+ convert_parser.add_argument('input_file', type=Path, help='Input GDF file (CSV or JSON)')
53
+ convert_parser.add_argument('-o', '--output', type=Path, help='Output file path')
54
+ convert_parser.add_argument('--erp', help='ERP system name (optional for auto-detection)')
55
+ convert_parser.add_argument('--no-llm', action='store_true',
56
+ help='Disable LLM fallback for unknown mappings')
57
+ convert_parser.add_argument('--template', type=Path, help='Custom template.json file')
58
+ convert_parser.add_argument('--format', choices=['csv', 'json'],
59
+ help='Output format (auto-detected from extension if not specified)')
60
+
61
+ # Batch convert command
62
+ batch_parser = subparsers.add_parser('batch', help='Batch convert multiple files')
63
+ batch_parser.add_argument('entity', choices=[e.value for e in EntityType],
64
+ help='Entity type to convert')
65
+ batch_parser.add_argument('input_pattern', help='Input file pattern (e.g., *.csv)')
66
+ batch_parser.add_argument('--output-dir', type=Path, default=Path('./converted'),
67
+ help='Output directory (default: ./converted)')
68
+ batch_parser.add_argument('--erp', help='ERP system name (optional for auto-detection)')
69
+ batch_parser.add_argument('--no-llm', action='store_true',
70
+ help='Disable LLM fallback for unknown mappings')
71
+ batch_parser.add_argument('--template', type=Path, help='Custom template.json file')
72
+ batch_parser.add_argument('--format', choices=['csv', 'json'], default='csv',
73
+ help='Output format (default: csv)')
74
+
75
+ # Analyze command
76
+ analyze_parser = subparsers.add_parser('analyze', help='Analyze file without conversion')
77
+ analyze_parser.add_argument('entity', choices=[e.value for e in EntityType],
78
+ help='Entity type to analyze')
79
+ analyze_parser.add_argument('input_file', type=Path, help='Input GDF file to analyze')
80
+ analyze_parser.add_argument('--erp', help='ERP system name for analysis')
81
+ analyze_parser.add_argument('--template', type=Path, help='Custom template.json file')
82
+ analyze_parser.add_argument('--verbose', '-v', action='store_true',
83
+ help='Show detailed analysis information')
84
+
85
+ # List commands
86
+ subparsers.add_parser('list-entities', help='List supported entity types')
87
+ subparsers.add_parser('list-erps', help='List supported ERP systems')
88
+
89
+ # Validate command
90
+ validate_parser = subparsers.add_parser('validate', help='Validate GDF file structure')
91
+ validate_parser.add_argument('input_file', type=Path, help='Input file to validate')
92
+
93
+ return parser
94
+
95
+
96
+ def load_file(file_path: Path) -> List[dict]:
97
+ """Load data from CSV or JSON file."""
98
+ if not file_path.exists():
99
+ raise FileNotFoundError(f"File not found: {file_path}")
100
+
101
+ if file_path.suffix.lower() == '.csv':
102
+ df = pd.read_csv(file_path)
103
+ return df.to_dict('records')
104
+ elif file_path.suffix.lower() == '.json':
105
+ with file_path.open('r', encoding='utf-8') as f:
106
+ data = json.load(f)
107
+ if isinstance(data, dict):
108
+ return [data]
109
+ return data
110
+ else:
111
+ raise ValueError(f"Unsupported file format: {file_path.suffix}")
112
+
113
+
114
+ def save_file(data: List[dict], file_path: Path, format_type: Optional[str] = None):
115
+ """Save data to CSV or JSON file."""
116
+ # Determine format from extension if not specified
117
+ if format_type is None:
118
+ format_type = file_path.suffix.lower().lstrip('.')
119
+
120
+ # Ensure output directory exists
121
+ file_path.parent.mkdir(parents=True, exist_ok=True)
122
+
123
+ if format_type == 'csv':
124
+ df = pd.DataFrame(data)
125
+ df.to_csv(file_path, index=False)
126
+ elif format_type == 'json':
127
+ with file_path.open('w', encoding='utf-8') as f:
128
+ json.dump(data, f, indent=2, default=str)
129
+ else:
130
+ raise ValueError(f"Unsupported output format: {format_type}")
131
+
132
+
133
+ def convert_command(args):
134
+ """Handle convert command."""
135
+ try:
136
+ # Load input data
137
+ print(f"Loading data from {args.input_file}...")
138
+ data = load_file(args.input_file)
139
+ print(f"Loaded {len(data)} records")
140
+
141
+ # Create converter
142
+ converter = create_converter(
143
+ template_path=args.template,
144
+ use_mock_llm=args.no_llm
145
+ )
146
+
147
+ # Convert data
148
+ print(f"Converting {args.entity} data...")
149
+ result = converter.convert(
150
+ gdf_data=data,
151
+ entity=EntityType(args.entity),
152
+ erp=args.erp,
153
+ use_llm=not args.no_llm
154
+ )
155
+
156
+ if not result.success:
157
+ print(f"❌ Conversion failed: {result.message}")
158
+ return 1
159
+
160
+ # Determine output file
161
+ if args.output:
162
+ output_file = args.output
163
+ else:
164
+ stem = args.input_file.stem
165
+ suffix = '.csv' if args.format == 'csv' or not args.format else f'.{args.format}'
166
+ output_file = args.input_file.parent / f"{stem}_cdf{suffix}"
167
+
168
+ # Save results
169
+ save_file(result.data, output_file, args.format)
170
+
171
+ print(f"✅ Successfully converted {len(result.data)} records")
172
+ print(f"📁 Output saved to: {output_file}")
173
+ print(f"🔍 ERP detected: {result.detected_erp or 'Unknown'}")
174
+ print(f"📋 Mapping source: {result.mapping_source}")
175
+
176
+ return 0
177
+
178
+ except Exception as e:
179
+ print(f"❌ Error: {e}")
180
+ return 1
181
+
182
+
183
+ def batch_command(args):
184
+ """Handle batch convert command."""
185
+ try:
186
+ # Find input files
187
+ input_files = list(Path('.').glob(args.input_pattern))
188
+ if not input_files:
189
+ print(f"❌ No files found matching pattern: {args.input_pattern}")
190
+ return 1
191
+
192
+ print(f"Found {len(input_files)} files to convert")
193
+
194
+ # Create output directory
195
+ args.output_dir.mkdir(parents=True, exist_ok=True)
196
+
197
+ # Create converter
198
+ converter = create_converter(
199
+ template_path=args.template,
200
+ use_mock_llm=args.no_llm
201
+ )
202
+
203
+ # Process each file
204
+ success_count = 0
205
+ for input_file in input_files:
206
+ try:
207
+ print(f"\n📄 Processing {input_file}...")
208
+
209
+ # Load data
210
+ data = load_file(input_file)
211
+
212
+ # Convert
213
+ result = converter.convert(
214
+ gdf_data=data,
215
+ entity=EntityType(args.entity),
216
+ erp=args.erp,
217
+ use_llm=not args.no_llm
218
+ )
219
+
220
+ if not result.success:
221
+ print(f" ❌ Failed: {result.message}")
222
+ continue
223
+
224
+ # Save output
225
+ output_file = args.output_dir / f"{input_file.stem}_cdf.{args.format}"
226
+ save_file(result.data, output_file, args.format)
227
+
228
+ print(f" ✅ Converted {len(result.data)} records → {output_file}")
229
+ success_count += 1
230
+
231
+ except Exception as e:
232
+ print(f" ❌ Error processing {input_file}: {e}")
233
+
234
+ print(f"\n🎉 Batch conversion complete: {success_count}/{len(input_files)} files processed")
235
+ return 0 if success_count > 0 else 1
236
+
237
+ except Exception as e:
238
+ print(f"❌ Batch conversion error: {e}")
239
+ return 1
240
+
241
+
242
+ def analyze_command(args):
243
+ """Handle analyze command."""
244
+ try:
245
+ # Load data to get columns
246
+ print(f"Analyzing {args.input_file}...")
247
+ data = load_file(args.input_file)
248
+
249
+ if not data:
250
+ print("❌ No data found in file")
251
+ return 1
252
+
253
+ columns = list(data[0].keys()) if data else []
254
+
255
+ # Create converter and analyze
256
+ converter = create_converter(template_path=args.template)
257
+ analysis = converter.get_mapping_info(
258
+ gdf_columns=columns,
259
+ entity=EntityType(args.entity),
260
+ erp=args.erp
261
+ )
262
+
263
+ # Display results
264
+ print(f"\n📊 Analysis Results for {args.entity}")
265
+ print("=" * 50)
266
+
267
+ print(f"📁 File: {args.input_file}")
268
+ print(f"📋 Records: {len(data)}")
269
+ print(f"📝 Columns: {len(columns)}")
270
+
271
+ if args.verbose:
272
+ print(f"🔍 GDF Columns: {', '.join(columns)}")
273
+
274
+ # ERP suggestions
275
+ suggestions = analysis.get('erp_suggestions', [])
276
+ if suggestions:
277
+ print(f"\n🎯 ERP Detection Results:")
278
+ for i, suggestion in enumerate(suggestions[:3], 1):
279
+ status = "✅" if suggestion['above_threshold'] else "⚠️"
280
+ print(f" {i}. {status} {suggestion['erp']}: {suggestion['similarity_score']:.1%} similarity")
281
+
282
+ # Template mapping
283
+ template_mapping = analysis.get('template_mapping')
284
+ if template_mapping:
285
+ print(f"\n🗺️ Template Mapping ({len(template_mapping)} columns):")
286
+ if args.verbose:
287
+ for gdf_col, cdf_col in template_mapping.items():
288
+ print(f" {gdf_col} → {cdf_col}")
289
+
290
+ # CDF schema
291
+ cdf_schema = analysis.get('cdf_schema', [])
292
+ print(f"\n📋 CDF Schema ({len(cdf_schema)} columns):")
293
+ if args.verbose:
294
+ print(f" {', '.join(cdf_schema)}")
295
+
296
+ return 0
297
+
298
+ except Exception as e:
299
+ print(f"❌ Analysis error: {e}")
300
+ return 1
301
+
302
+
303
+ def list_entities_command(args):
304
+ """Handle list-entities command."""
305
+ print("📋 Supported Entity Types:")
306
+ print("=" * 30)
307
+
308
+ descriptions = {
309
+ "sales_orders": "Sales order transactions with line items",
310
+ "customers": "Customer master data and contact information",
311
+ "invoices": "Invoice documents with billing details",
312
+ "purchase_orders": "Purchase orders and procurement data",
313
+ "inventory_items": "Product catalog and inventory information"
314
+ }
315
+
316
+ for entity in EntityType:
317
+ desc = descriptions.get(entity.value, "")
318
+ print(f" • {entity.value:<20} - {desc}")
319
+
320
+ return 0
321
+
322
+
323
+ def list_erps_command(args):
324
+ """Handle list-erps command."""
325
+ try:
326
+ converter = create_converter()
327
+ erp_names = converter.template_loader.get_erp_names()
328
+
329
+ print("🏢 Supported ERP Systems:")
330
+ print("=" * 30)
331
+
332
+ for erp in erp_names:
333
+ print(f" • {erp}")
334
+
335
+ print(f"\nTotal: {len(erp_names)} ERP systems supported")
336
+ return 0
337
+
338
+ except Exception as e:
339
+ print(f"❌ Error loading ERP systems: {e}")
340
+ return 1
341
+
342
+
343
+ def validate_command(args):
344
+ """Handle validate command."""
345
+ try:
346
+ print(f"Validating {args.input_file}...")
347
+
348
+ # Load and validate data
349
+ data = load_file(args.input_file)
350
+ converter = create_converter()
351
+ validation = converter.validate_gdf_data(data)
352
+
353
+ if validation['valid']:
354
+ print("✅ File is valid")
355
+ print(f"📊 Records: {validation['row_count']}")
356
+ print(f"📝 Columns: {validation['column_count']}")
357
+ print(f"🔍 Column names: {', '.join(validation['columns'])}")
358
+
359
+ # Show null counts if any
360
+ null_counts = validation.get('null_counts', {})
361
+ if any(count > 0 for count in null_counts.values()):
362
+ print("\n⚠️ Null value counts:")
363
+ for col, count in null_counts.items():
364
+ if count > 0:
365
+ print(f" {col}: {count}")
366
+ else:
367
+ print(f"❌ File validation failed: {validation.get('error', 'Unknown error')}")
368
+ return 1
369
+
370
+ return 0
371
+
372
+ except Exception as e:
373
+ print(f"❌ Validation error: {e}")
374
+ return 1
375
+
376
+
377
+ def main():
378
+ """Main CLI entry point."""
379
+ parser = setup_argparser()
380
+ args = parser.parse_args()
381
+
382
+ if not args.command:
383
+ parser.print_help()
384
+ return 1
385
+
386
+ # Route to appropriate command handler
387
+ command_handlers = {
388
+ 'convert': convert_command,
389
+ 'batch': batch_command,
390
+ 'analyze': analyze_command,
391
+ 'list-entities': list_entities_command,
392
+ 'list-erps': list_erps_command,
393
+ 'validate': validate_command
394
+ }
395
+
396
+ handler = command_handlers.get(args.command)
397
+ if handler:
398
+ return handler(args)
399
+ else:
400
+ print(f"❌ Unknown command: {args.command}")
401
+ return 1
402
+
403
+
404
+ if __name__ == "__main__":
405
+ sys.exit(main())
mapper/__init__.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ GDF to CDF Mapper Package
3
+
4
+ A modular Python package for converting General Data Frames (GDFs) from ERP exports
5
+ into a normalized Common Data Frame (CDF) format.
6
+
7
+ Key Features:
8
+ - Template-driven mapping with ERP auto-detection
9
+ - LLM fallback for unknown ERP schemas
10
+ - Pydantic models for data validation
11
+ - FastAPI integration ready
12
+ - CLI tool support
13
+
14
+ Usage:
15
+ from mapper import GDFToCDFConverter, EntityType
16
+
17
+ converter = GDFToCDFConverter()
18
+ result = converter.convert(gdf_data, EntityType.SALES_ORDERS)
19
+ """
20
+
21
+ from .models import (
22
+ EntityType,
23
+ ConversionRequest,
24
+ ConversionResponse,
25
+ SalesOrderCDF,
26
+ CustomerCDF,
27
+ InvoiceCDF,
28
+ PurchaseOrderCDF,
29
+ InventoryItemCDF,
30
+ CDF_MODELS
31
+ )
32
+
33
+ from .template_loader import TemplateLoader
34
+ from .erp_resolver import ERPResolver
35
+ from .llm_handler import LLMHandler, MockLLMHandler
36
+ from .converter import GDFToCDFConverter
37
+
38
+ __version__ = "1.0.0"
39
+ __author__ = "CleanFlow AI"
40
+ __description__ = "GDF to CDF conversion toolkit for ERP data integration"
41
+
42
+ # Main exports
43
+ __all__ = [
44
+ # Core converter
45
+ "GDFToCDFConverter",
46
+
47
+ # Models and enums
48
+ "EntityType",
49
+ "ConversionRequest",
50
+ "ConversionResponse",
51
+ "SalesOrderCDF",
52
+ "CustomerCDF",
53
+ "InvoiceCDF",
54
+ "PurchaseOrderCDF",
55
+ "InventoryItemCDF",
56
+ "CDF_MODELS",
57
+
58
+ # Component classes
59
+ "TemplateLoader",
60
+ "ERPResolver",
61
+ "LLMHandler",
62
+ "MockLLMHandler",
63
+
64
+ # Package metadata
65
+ "__version__",
66
+ "__author__",
67
+ "__description__"
68
+ ]
69
+
70
+
71
+ def create_converter(template_path=None, use_mock_llm=False, **kwargs):
72
+ """Convenience function to create a converter instance.
73
+
74
+ Args:
75
+ template_path: Path to template.json file
76
+ use_mock_llm: Use mock LLM handler for testing
77
+ **kwargs: Additional arguments for GDFToCDFConverter
78
+
79
+ Returns:
80
+ GDFToCDFConverter instance
81
+ """
82
+ return GDFToCDFConverter(
83
+ template_path=template_path,
84
+ use_mock_llm=use_mock_llm,
85
+ **kwargs
86
+ )
87
+
88
+
89
+ def convert_gdf_to_cdf(data, entity, erp=None, use_llm=True, **converter_kwargs):
90
+ """Quick conversion function for simple use cases.
91
+
92
+ Args:
93
+ data: GDF data to convert
94
+ entity: EntityType or string entity name
95
+ erp: ERP system name (optional)
96
+ use_llm: Whether to use LLM fallback
97
+ **converter_kwargs: Additional arguments for converter initialization
98
+
99
+ Returns:
100
+ ConversionResponse object
101
+ """
102
+ if isinstance(entity, str):
103
+ entity = EntityType(entity)
104
+
105
+ converter = create_converter(**converter_kwargs)
106
+ return converter.convert(data, entity, erp, use_llm)
mapper/converter.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Main GDF to CDF conversion logic.
3
+ Orchestrates template loading, ERP detection, LLM fallback, and data transformation.
4
+ """
5
+
6
+ import pandas as pd
7
+ from pathlib import Path
8
+ from typing import Dict, List, Optional, Tuple, Union, Any
9
+
10
+ from .models import EntityType, ConversionResponse
11
+ from .template_loader import TemplateLoader
12
+ from .erp_resolver import ERPResolver
13
+ from .llm_handler import LLMHandler, MockLLMHandler
14
+
15
+
16
+ class GDFToCDFConverter:
17
+ """Main converter class for GDF to CDF transformation."""
18
+
19
+ def __init__(self,
20
+ template_path: Optional[Path] = None,
21
+ similarity_threshold: float = 0.4,
22
+ llm_handler: Optional[LLMHandler] = None,
23
+ use_mock_llm: bool = False):
24
+ """Initialize converter.
25
+
26
+ Args:
27
+ template_path: Path to template.json file
28
+ similarity_threshold: Minimum Jaccard similarity for ERP detection
29
+ llm_handler: Custom LLM handler instance
30
+ use_mock_llm: Use mock LLM handler for testing
31
+ """
32
+ self.template_loader = TemplateLoader(template_path)
33
+ self.erp_resolver = ERPResolver(self.template_loader, similarity_threshold)
34
+
35
+ # Initialize LLM handler
36
+ if llm_handler:
37
+ self.llm_handler = llm_handler
38
+ elif use_mock_llm:
39
+ self.llm_handler = MockLLMHandler()
40
+ else:
41
+ try:
42
+ self.llm_handler = LLMHandler()
43
+ except (ValueError, ImportError):
44
+ # Fallback to mock if LLM setup fails
45
+ self.llm_handler = MockLLMHandler()
46
+
47
+ def convert(self,
48
+ gdf_data: Union[pd.DataFrame, List[Dict[str, Any]], Dict[str, Any]],
49
+ entity: EntityType,
50
+ erp: Optional[str] = None,
51
+ use_llm: bool = True) -> ConversionResponse:
52
+ """Convert GDF data to CDF format.
53
+
54
+ Args:
55
+ gdf_data: Input GDF data as DataFrame, list of records, or single record
56
+ entity: Entity type to convert
57
+ erp: ERP system name (optional for auto-detection)
58
+ use_llm: Whether to use LLM fallback for unknown mappings
59
+
60
+ Returns:
61
+ ConversionResponse with converted data and metadata
62
+ """
63
+ try:
64
+ # Convert input to DataFrame
65
+ gdf_df = self._prepare_dataframe(gdf_data)
66
+
67
+ if gdf_df.empty:
68
+ return ConversionResponse(
69
+ success=False,
70
+ data=[],
71
+ message="Input data is empty"
72
+ )
73
+
74
+ # Get column mapping
75
+ mapping, detected_erp, mapping_source = self._get_column_mapping(
76
+ list(gdf_df.columns), entity.value, erp, use_llm
77
+ )
78
+
79
+ if not mapping:
80
+ return ConversionResponse(
81
+ success=False,
82
+ data=[],
83
+ detected_erp=detected_erp,
84
+ mapping_source=mapping_source,
85
+ message="No column mapping could be determined"
86
+ )
87
+
88
+ # Apply mapping and transformation
89
+ cdf_df = self._apply_mapping(gdf_df, mapping, entity.value)
90
+
91
+ # Convert to list of dictionaries
92
+ cdf_data = cdf_df.to_dict('records')
93
+
94
+ return ConversionResponse(
95
+ success=True,
96
+ data=cdf_data,
97
+ detected_erp=detected_erp,
98
+ mapping_source=mapping_source,
99
+ message=f"Successfully converted {len(cdf_data)} records"
100
+ )
101
+
102
+ except Exception as e:
103
+ return ConversionResponse(
104
+ success=False,
105
+ data=[],
106
+ message=f"Conversion failed: {str(e)}"
107
+ )
108
+
109
+ def _prepare_dataframe(self, data: Union[pd.DataFrame, List[Dict[str, Any]], Dict[str, Any]]) -> pd.DataFrame:
110
+ """Convert input data to pandas DataFrame.
111
+
112
+ Args:
113
+ data: Input data in various formats
114
+
115
+ Returns:
116
+ Pandas DataFrame
117
+ """
118
+ if isinstance(data, pd.DataFrame):
119
+ return data.copy()
120
+ elif isinstance(data, list):
121
+ return pd.DataFrame(data)
122
+ elif isinstance(data, dict):
123
+ return pd.DataFrame([data])
124
+ else:
125
+ raise ValueError(f"Unsupported data type: {type(data)}")
126
+
127
+ def _get_column_mapping(self,
128
+ gdf_columns: List[str],
129
+ entity: str,
130
+ erp: Optional[str],
131
+ use_llm: bool) -> Tuple[Dict[str, str], Optional[str], str]:
132
+ """Get column mapping using template or LLM fallback.
133
+
134
+ Args:
135
+ gdf_columns: List of GDF column names
136
+ entity: Entity type
137
+ erp: ERP system name (optional)
138
+ use_llm: Whether to use LLM fallback
139
+
140
+ Returns:
141
+ Tuple of (mapping_dict, detected_erp, mapping_source)
142
+ """
143
+ detected_erp = erp
144
+ mapping_source = "template"
145
+
146
+ # Step 1: Try template-based mapping
147
+ if erp:
148
+ # Use provided ERP
149
+ mapping = self.template_loader.get_entity_mapping(erp, entity)
150
+ if mapping:
151
+ return mapping, erp, "template"
152
+ else:
153
+ # Auto-detect ERP
154
+ detected_erp = self.erp_resolver.detect_erp(gdf_columns, entity)
155
+ if detected_erp:
156
+ mapping = self.template_loader.get_entity_mapping(detected_erp, entity)
157
+ if mapping:
158
+ return mapping, detected_erp, "template"
159
+
160
+ # Step 2: Try LLM fallback
161
+ if use_llm:
162
+ try:
163
+ cdf_columns = self.template_loader.get_cdf_schema(entity)
164
+ llm_mapping = self.llm_handler.infer_mapping(gdf_columns, cdf_columns, entity)
165
+ if llm_mapping:
166
+ return llm_mapping, detected_erp, "llm"
167
+ except Exception:
168
+ pass # Fall through to fallback
169
+
170
+ # Step 3: Fallback - return empty mapping
171
+ return {}, detected_erp, "fallback"
172
+
173
+ def _apply_mapping(self, gdf_df: pd.DataFrame, mapping: Dict[str, str], entity: str) -> pd.DataFrame:
174
+ """Apply column mapping and ensure CDF schema compliance.
175
+
176
+ Args:
177
+ gdf_df: Input GDF DataFrame
178
+ mapping: Column mapping dictionary
179
+ entity: Entity type
180
+
181
+ Returns:
182
+ CDF-compliant DataFrame
183
+ """
184
+ # Step 1: Rename columns according to mapping
185
+ cdf_df = gdf_df.rename(columns=mapping)
186
+
187
+ # Step 2: Get expected CDF schema
188
+ expected_columns = self.template_loader.get_cdf_schema(entity)
189
+
190
+ # Step 3: Add missing columns with null values
191
+ for col in expected_columns:
192
+ if col not in cdf_df.columns:
193
+ cdf_df[col] = pd.NA
194
+
195
+ # Step 4: Reorder columns to match CDF schema
196
+ cdf_df = cdf_df[expected_columns]
197
+
198
+ # Step 5: Apply data type conversions
199
+ cdf_df = self._apply_data_types(cdf_df, entity)
200
+
201
+ return cdf_df
202
+
203
+ def _apply_data_types(self, df: pd.DataFrame, entity: str) -> pd.DataFrame:
204
+ """Apply appropriate data types based on CDF schema.
205
+
206
+ Args:
207
+ df: DataFrame to type-convert
208
+ entity: Entity type
209
+
210
+ Returns:
211
+ DataFrame with proper data types
212
+ """
213
+ # Define data type mappings for each entity
214
+ type_mappings = {
215
+ "sales_orders": {
216
+ "order_date": "datetime64[ns]",
217
+ "total_amount": "float64",
218
+ "quantity": "Int64",
219
+ "unit_price": "float64",
220
+ "line_total": "float64"
221
+ },
222
+ "customers": {
223
+ "is_company": "boolean",
224
+ "created_date": "datetime64[ns]",
225
+ "last_modified": "datetime64[ns]"
226
+ },
227
+ "invoices": {
228
+ "invoice_date": "datetime64[ns]",
229
+ "total_amount": "float64",
230
+ "due_date": "datetime64[ns]",
231
+ "quantity": "Int64",
232
+ "unit_price": "float64",
233
+ "line_total": "float64"
234
+ },
235
+ "purchase_orders": {
236
+ "po_date": "datetime64[ns]",
237
+ "total_amount": "float64",
238
+ "expected_receipt_date": "datetime64[ns]",
239
+ "quantity": "Int64",
240
+ "unit_price": "float64",
241
+ "line_total": "float64"
242
+ },
243
+ "inventory_items": {
244
+ "base_price": "float64",
245
+ "cost_price": "float64",
246
+ "is_active": "boolean",
247
+ "quantity_on_hand": "Int64",
248
+ "reorder_point": "Int64"
249
+ }
250
+ }
251
+
252
+ entity_types = type_mappings.get(entity, {})
253
+
254
+ for column, dtype in entity_types.items():
255
+ if column in df.columns:
256
+ try:
257
+ if dtype.startswith("datetime"):
258
+ df[column] = pd.to_datetime(df[column], errors='coerce')
259
+ elif dtype == "boolean":
260
+ df[column] = df[column].astype("boolean")
261
+ elif dtype == "Int64":
262
+ df[column] = pd.to_numeric(df[column], errors='coerce').astype("Int64")
263
+ elif dtype == "float64":
264
+ df[column] = pd.to_numeric(df[column], errors='coerce').astype("float64")
265
+ except Exception:
266
+ # Keep original data if conversion fails
267
+ pass
268
+
269
+ return df
270
+
271
+ def get_mapping_info(self,
272
+ gdf_columns: List[str],
273
+ entity: EntityType,
274
+ erp: Optional[str] = None) -> Dict[str, Any]:
275
+ """Get detailed mapping information without performing conversion.
276
+
277
+ Args:
278
+ gdf_columns: List of GDF column names
279
+ entity: Entity type
280
+ erp: ERP system name (optional)
281
+
282
+ Returns:
283
+ Dictionary with mapping analysis information
284
+ """
285
+ entity_str = entity.value
286
+
287
+ # Get ERP suggestions
288
+ suggestions = self.erp_resolver.suggest_best_matches(gdf_columns, entity_str)
289
+
290
+ # Get template mapping if ERP is known
291
+ template_mapping = None
292
+ if erp:
293
+ template_mapping = self.template_loader.get_entity_mapping(erp, entity_str)
294
+ elif suggestions and suggestions[0]['above_threshold']:
295
+ template_mapping = self.template_loader.get_entity_mapping(
296
+ suggestions[0]['erp'], entity_str
297
+ )
298
+
299
+ # Get CDF schema
300
+ cdf_schema = self.template_loader.get_cdf_schema(entity_str)
301
+
302
+ return {
303
+ "gdf_columns": gdf_columns,
304
+ "cdf_schema": cdf_schema,
305
+ "erp_suggestions": suggestions,
306
+ "template_mapping": template_mapping,
307
+ "available_erps": self.template_loader.get_erp_names()
308
+ }
309
+
310
+ def validate_gdf_data(self, data: Union[pd.DataFrame, List[Dict], Dict]) -> Dict[str, Any]:
311
+ """Validate GDF data structure and content.
312
+
313
+ Args:
314
+ data: Input GDF data
315
+
316
+ Returns:
317
+ Validation results dictionary
318
+ """
319
+ try:
320
+ df = self._prepare_dataframe(data)
321
+
322
+ return {
323
+ "valid": True,
324
+ "row_count": len(df),
325
+ "column_count": len(df.columns),
326
+ "columns": list(df.columns),
327
+ "has_data": not df.empty,
328
+ "null_counts": df.isnull().sum().to_dict(),
329
+ "data_types": df.dtypes.astype(str).to_dict()
330
+ }
331
+ except Exception as e:
332
+ return {
333
+ "valid": False,
334
+ "error": str(e)
335
+ }
mapper/erp_resolver.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ERP resolver for automatic ERP system detection.
3
+ Uses Jaccard similarity to match GDF columns against known ERP templates.
4
+ """
5
+
6
+ from typing import Dict, List, Optional, Tuple
7
+
8
+ from .template_loader import TemplateLoader
9
+
10
+
11
+ class ERPResolver:
12
+ """Resolves ERP system from GDF column names using similarity matching."""
13
+
14
+ def __init__(self, template_loader: TemplateLoader, similarity_threshold: float = 0.4):
15
+ """Initialize ERP resolver.
16
+
17
+ Args:
18
+ template_loader: Template loader instance
19
+ similarity_threshold: Minimum Jaccard similarity to accept ERP match
20
+ """
21
+ self.template_loader = template_loader
22
+ self.similarity_threshold = similarity_threshold
23
+
24
+ def detect_erp(self, gdf_columns: List[str], entity: str) -> Optional[str]:
25
+ """Detect ERP system from GDF column names.
26
+
27
+ Args:
28
+ gdf_columns: List of column names from GDF
29
+ entity: Entity type being processed
30
+
31
+ Returns:
32
+ ERP system name if detected above threshold, None otherwise
33
+ """
34
+ scores = self._calculate_similarity_scores(gdf_columns, entity)
35
+
36
+ if not scores:
37
+ return None
38
+
39
+ # Get best match
40
+ best_erp, best_score = max(scores, key=lambda x: x[1])
41
+
42
+ if best_score >= self.similarity_threshold:
43
+ return best_erp
44
+
45
+ return None
46
+
47
+ def get_similarity_scores(self, gdf_columns: List[str], entity: str) -> List[Tuple[str, float]]:
48
+ """Get similarity scores for all ERPs, sorted by score descending.
49
+
50
+ Args:
51
+ gdf_columns: List of column names from GDF
52
+ entity: Entity type being processed
53
+
54
+ Returns:
55
+ List of (erp_name, similarity_score) tuples sorted by score descending
56
+ """
57
+ scores = self._calculate_similarity_scores(gdf_columns, entity)
58
+ return sorted(scores, key=lambda x: x[1], reverse=True)
59
+
60
+ def _calculate_similarity_scores(self, gdf_columns: List[str], entity: str) -> List[Tuple[str, float]]:
61
+ """Calculate Jaccard similarity scores for all ERPs.
62
+
63
+ Args:
64
+ gdf_columns: List of column names from GDF
65
+ entity: Entity type being processed
66
+
67
+ Returns:
68
+ List of (erp_name, similarity_score) tuples
69
+ """
70
+ scores = []
71
+ gdf_set = set(col.lower().strip() for col in gdf_columns) # Normalize for comparison
72
+
73
+ erp_columns = self.template_loader.get_all_erp_columns(entity)
74
+
75
+ for erp_name, erp_cols in erp_columns.items():
76
+ if not erp_cols: # Skip if no columns for this ERP/entity
77
+ continue
78
+
79
+ erp_set = set(col.lower().strip() for col in erp_cols) # Normalize for comparison
80
+ similarity = self._jaccard_similarity(gdf_set, erp_set)
81
+ scores.append((erp_name, similarity))
82
+
83
+ return scores
84
+
85
+ def _jaccard_similarity(self, set_a: set, set_b: set) -> float:
86
+ """Calculate Jaccard similarity between two sets.
87
+
88
+ Args:
89
+ set_a: First set
90
+ set_b: Second set
91
+
92
+ Returns:
93
+ Jaccard similarity coefficient (0.0 to 1.0)
94
+ """
95
+ if not set_a and not set_b:
96
+ return 1.0
97
+
98
+ intersection = len(set_a & set_b)
99
+ union = len(set_a | set_b)
100
+
101
+ return intersection / union if union > 0 else 0.0
102
+
103
+ def get_matching_columns(self, gdf_columns: List[str], erp: str, entity: str) -> Dict[str, List[str]]:
104
+ """Get detailed column matching information.
105
+
106
+ Args:
107
+ gdf_columns: List of column names from GDF
108
+ erp: ERP system name
109
+ entity: Entity type
110
+
111
+ Returns:
112
+ Dictionary with 'matched', 'unmatched_gdf', 'unmatched_erp' lists
113
+ """
114
+ mapping = self.template_loader.get_entity_mapping(erp, entity)
115
+ if not mapping:
116
+ return {
117
+ 'matched': [],
118
+ 'unmatched_gdf': gdf_columns,
119
+ 'unmatched_erp': []
120
+ }
121
+
122
+ gdf_set = set(col.lower().strip() for col in gdf_columns)
123
+ erp_set = set(col.lower().strip() for col in mapping.keys())
124
+
125
+ # Find matches (case-insensitive)
126
+ matched = []
127
+ unmatched_gdf = []
128
+
129
+ for gdf_col in gdf_columns:
130
+ gdf_col_norm = gdf_col.lower().strip()
131
+ if gdf_col_norm in erp_set:
132
+ # Find the original ERP column name
133
+ for erp_col in mapping.keys():
134
+ if erp_col.lower().strip() == gdf_col_norm:
135
+ matched.append((gdf_col, erp_col))
136
+ break
137
+ else:
138
+ unmatched_gdf.append(gdf_col)
139
+
140
+ # Find unmatched ERP columns
141
+ matched_erp_cols = {erp_col for _, erp_col in matched}
142
+ unmatched_erp = [col for col in mapping.keys() if col not in matched_erp_cols]
143
+
144
+ return {
145
+ 'matched': matched,
146
+ 'unmatched_gdf': unmatched_gdf,
147
+ 'unmatched_erp': unmatched_erp
148
+ }
149
+
150
+ def suggest_best_matches(self, gdf_columns: List[str], entity: str, top_n: int = 3) -> List[Dict]:
151
+ """Suggest best ERP matches with detailed information.
152
+
153
+ Args:
154
+ gdf_columns: List of column names from GDF
155
+ entity: Entity type
156
+ top_n: Number of top matches to return
157
+
158
+ Returns:
159
+ List of dictionaries with ERP match details
160
+ """
161
+ scores = self.get_similarity_scores(gdf_columns, entity)
162
+ suggestions = []
163
+
164
+ for erp_name, score in scores[:top_n]:
165
+ matching_info = self.get_matching_columns(gdf_columns, erp_name, entity)
166
+
167
+ suggestions.append({
168
+ 'erp': erp_name,
169
+ 'similarity_score': score,
170
+ 'above_threshold': score >= self.similarity_threshold,
171
+ 'matched_columns': len(matching_info['matched']),
172
+ 'total_gdf_columns': len(gdf_columns),
173
+ 'total_erp_columns': len(self.template_loader.get_entity_mapping(erp_name, entity) or {}),
174
+ 'matching_details': matching_info
175
+ })
176
+
177
+ return suggestions
mapper/llm_handler.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ LLM fallback handler for column mapping inference.
3
+ Uses LLaMA-3-70B-Instruct or other LLMs to infer column mappings when templates fail.
4
+ """
5
+
6
+ import json
7
+ import os
8
+ from typing import Dict, List, Optional
9
+
10
+ try:
11
+ from langchain_openai import ChatOpenAI
12
+ from langchain_core.messages import HumanMessage, SystemMessage
13
+ LANGCHAIN_AVAILABLE = True
14
+ except ImportError:
15
+ LANGCHAIN_AVAILABLE = False
16
+
17
+ try:
18
+ import openai
19
+ OPENAI_AVAILABLE = True
20
+ except ImportError:
21
+ OPENAI_AVAILABLE = False
22
+
23
+
24
+ class LLMHandler:
25
+ """Handles LLM-based column mapping inference."""
26
+
27
+ def __init__(self,
28
+ model_name: str = "gpt-4o",
29
+ api_key: Optional[str] = None,
30
+ temperature: float = 0.0,
31
+ max_retries: int = 3):
32
+ """Initialize LLM handler.
33
+
34
+ Args:
35
+ model_name: LLM model to use (e.g., "gpt-4o", "llama-3-70b-instruct")
36
+ api_key: API key for the LLM service
37
+ temperature: Temperature for LLM generation (0.0 for deterministic)
38
+ max_retries: Maximum number of retry attempts
39
+ """
40
+ self.model_name = model_name
41
+ self.api_key = api_key or os.getenv("OPENAI_API_KEY")
42
+ self.temperature = temperature
43
+ self.max_retries = max_retries
44
+
45
+ # Initialize LLM client
46
+ self._init_llm_client()
47
+
48
+ def _init_llm_client(self):
49
+ """Initialize the appropriate LLM client."""
50
+ if not self.api_key:
51
+ raise ValueError("API key required for LLM operations. Set OPENAI_API_KEY environment variable.")
52
+
53
+ if LANGCHAIN_AVAILABLE:
54
+ self.llm = ChatOpenAI(
55
+ model=self.model_name,
56
+ temperature=self.temperature,
57
+ api_key=self.api_key
58
+ )
59
+ self.use_langchain = True
60
+ elif OPENAI_AVAILABLE:
61
+ openai.api_key = self.api_key
62
+ self.use_langchain = False
63
+ else:
64
+ raise ImportError("Either langchain-openai or openai package is required for LLM functionality")
65
+
66
+ def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str], entity: str) -> Dict[str, str]:
67
+ """Infer column mapping using LLM.
68
+
69
+ Args:
70
+ gdf_columns: Source GDF column names
71
+ cdf_columns: Target CDF column names
72
+ entity: Entity type being processed
73
+
74
+ Returns:
75
+ Dictionary mapping GDF columns to CDF columns
76
+
77
+ Raises:
78
+ ValueError: If LLM fails to return valid mapping
79
+ Exception: If LLM service is unavailable
80
+ """
81
+ prompt = self._build_mapping_prompt(gdf_columns, cdf_columns, entity)
82
+
83
+ for attempt in range(self.max_retries):
84
+ try:
85
+ if self.use_langchain:
86
+ response = self._query_with_langchain(prompt)
87
+ else:
88
+ response = self._query_with_openai(prompt)
89
+
90
+ # Parse and validate response
91
+ mapping = self._parse_mapping_response(response, gdf_columns, cdf_columns)
92
+ return mapping
93
+
94
+ except Exception as e:
95
+ if attempt == self.max_retries - 1:
96
+ raise ValueError(f"LLM failed to return valid mapping after {self.max_retries} attempts: {e}")
97
+ continue
98
+
99
+ raise ValueError("LLM mapping inference failed")
100
+
101
+ def _build_mapping_prompt(self, gdf_columns: List[str], cdf_columns: List[str], entity: str) -> str:
102
+ """Build prompt for LLM column mapping inference.
103
+
104
+ Args:
105
+ gdf_columns: Source GDF column names
106
+ cdf_columns: Target CDF column names
107
+ entity: Entity type
108
+
109
+ Returns:
110
+ Formatted prompt string
111
+ """
112
+ system_context = f"""You are a data integration expert specializing in ERP system mappings.
113
+ Your task is to map source columns from an unknown ERP system to a standardized Common Data Frame (CDF) schema for {entity}.
114
+
115
+ Rules:
116
+ 1. Return ONLY a valid JSON object mapping source columns to CDF columns
117
+ 2. Each source column should map to exactly one CDF column
118
+ 3. If a source column doesn't clearly match any CDF column, omit it from the mapping
119
+ 4. Use your knowledge of ERP systems and common field naming conventions
120
+ 5. Consider semantic meaning, not just string similarity
121
+ 6. Be conservative - only map when you're confident about the relationship
122
+
123
+ Entity type: {entity}
124
+ Source columns: {gdf_columns}
125
+ Target CDF columns: {cdf_columns}
126
+
127
+ Return a JSON mapping where keys are source column names and values are CDF column names.
128
+ Example format: {{"source_col1": "cdf_col1", "source_col2": "cdf_col2"}}"""
129
+
130
+ return system_context
131
+
132
+ def _query_with_langchain(self, prompt: str) -> str:
133
+ """Query LLM using LangChain.
134
+
135
+ Args:
136
+ prompt: Prompt to send to LLM
137
+
138
+ Returns:
139
+ LLM response text
140
+ """
141
+ messages = [
142
+ SystemMessage(content="You are a data integration expert. Return only valid JSON."),
143
+ HumanMessage(content=prompt)
144
+ ]
145
+
146
+ response = self.llm.invoke(messages)
147
+ return response.content
148
+
149
+ def _query_with_openai(self, prompt: str) -> str:
150
+ """Query LLM using OpenAI client directly.
151
+
152
+ Args:
153
+ prompt: Prompt to send to LLM
154
+
155
+ Returns:
156
+ LLM response text
157
+ """
158
+ response = openai.ChatCompletion.create(
159
+ model=self.model_name,
160
+ messages=[
161
+ {"role": "system", "content": "You are a data integration expert. Return only valid JSON."},
162
+ {"role": "user", "content": prompt}
163
+ ],
164
+ temperature=self.temperature
165
+ )
166
+
167
+ return response.choices[0].message.content
168
+
169
+ def _parse_mapping_response(self, response: str, gdf_columns: List[str], cdf_columns: List[str]) -> Dict[str, str]:
170
+ """Parse and validate LLM mapping response.
171
+
172
+ Args:
173
+ response: Raw LLM response
174
+ gdf_columns: Original GDF columns for validation
175
+ cdf_columns: Original CDF columns for validation
176
+
177
+ Returns:
178
+ Validated mapping dictionary
179
+
180
+ Raises:
181
+ ValueError: If response is invalid
182
+ """
183
+ try:
184
+ # Try to extract JSON from response
185
+ response = response.strip()
186
+
187
+ # Handle cases where LLM wraps JSON in markdown code blocks
188
+ if response.startswith("```json"):
189
+ response = response[7:]
190
+ if response.startswith("```"):
191
+ response = response[3:]
192
+ if response.endswith("```"):
193
+ response = response[:-3]
194
+
195
+ response = response.strip()
196
+
197
+ mapping = json.loads(response)
198
+
199
+ if not isinstance(mapping, dict):
200
+ raise ValueError("Response is not a dictionary")
201
+
202
+ # Validate mapping
203
+ validated_mapping = {}
204
+ gdf_set = set(gdf_columns)
205
+ cdf_set = set(cdf_columns)
206
+
207
+ for source_col, target_col in mapping.items():
208
+ if not isinstance(source_col, str) or not isinstance(target_col, str):
209
+ continue
210
+
211
+ # Check if source column exists in GDF
212
+ if source_col not in gdf_set:
213
+ continue
214
+
215
+ # Check if target column exists in CDF schema
216
+ if target_col not in cdf_set:
217
+ continue
218
+
219
+ validated_mapping[source_col] = target_col
220
+
221
+ return validated_mapping
222
+
223
+ except json.JSONDecodeError as e:
224
+ raise ValueError(f"Invalid JSON in LLM response: {e}")
225
+ except Exception as e:
226
+ raise ValueError(f"Failed to parse LLM response: {e}")
227
+
228
+ def get_mapping_confidence(self, mapping: Dict[str, str], gdf_columns: List[str]) -> float:
229
+ """Calculate confidence score for a mapping.
230
+
231
+ Args:
232
+ mapping: Column mapping dictionary
233
+ gdf_columns: Original GDF columns
234
+
235
+ Returns:
236
+ Confidence score between 0.0 and 1.0
237
+ """
238
+ if not gdf_columns:
239
+ return 0.0
240
+
241
+ mapped_columns = len(mapping)
242
+ total_columns = len(gdf_columns)
243
+
244
+ # Simple confidence based on coverage
245
+ coverage_score = mapped_columns / total_columns
246
+
247
+ # Could be enhanced with semantic similarity scoring
248
+ return min(coverage_score, 1.0)
249
+
250
+ def explain_mapping(self, mapping: Dict[str, str], entity: str) -> str:
251
+ """Generate explanation for the mapping decisions.
252
+
253
+ Args:
254
+ mapping: Column mapping dictionary
255
+ entity: Entity type
256
+
257
+ Returns:
258
+ Human-readable explanation of mapping decisions
259
+ """
260
+ if not mapping:
261
+ return f"No column mappings could be inferred for {entity} entity."
262
+
263
+ explanation = f"LLM inferred {len(mapping)} column mappings for {entity}:\n"
264
+
265
+ for source_col, target_col in mapping.items():
266
+ explanation += f" • {source_col} → {target_col}\n"
267
+
268
+ return explanation
269
+
270
+
271
+ class MockLLMHandler(LLMHandler):
272
+ """Mock LLM handler for testing without API calls."""
273
+
274
+ def __init__(self):
275
+ """Initialize mock handler without API requirements."""
276
+ self.model_name = "mock-llm"
277
+ self.temperature = 0.0
278
+ self.max_retries = 1
279
+
280
+ def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str], entity: str) -> Dict[str, str]:
281
+ """Mock mapping inference using simple heuristics.
282
+
283
+ Args:
284
+ gdf_columns: Source GDF column names
285
+ cdf_columns: Target CDF column names
286
+ entity: Entity type
287
+
288
+ Returns:
289
+ Mock mapping dictionary
290
+ """
291
+ mapping = {}
292
+
293
+ # Simple heuristic matching based on common patterns
294
+ for gdf_col in gdf_columns:
295
+ gdf_lower = gdf_col.lower()
296
+
297
+ for cdf_col in cdf_columns:
298
+ cdf_lower = cdf_col.lower()
299
+
300
+ # Simple substring matching
301
+ if (gdf_lower in cdf_lower or cdf_lower in gdf_lower or
302
+ any(word in cdf_lower for word in gdf_lower.split('_')) or
303
+ any(word in gdf_lower for word in cdf_lower.split('_'))):
304
+ mapping[gdf_col] = cdf_col
305
+ break
306
+
307
+ return mapping
mapper/models.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pydantic models for GDF to CDF conversion.
3
+ Defines input/output validation schemas and data types.
4
+ """
5
+
6
+ from datetime import date, datetime
7
+ from decimal import Decimal
8
+ from typing import Any, Dict, List, Optional, Union
9
+ from enum import Enum
10
+
11
+ from pydantic import BaseModel, Field, validator
12
+
13
+
14
+ class EntityType(str, Enum):
15
+ """Supported entity types for conversion."""
16
+ SALES_ORDERS = "sales_orders"
17
+ CUSTOMERS = "customers"
18
+ INVOICES = "invoices"
19
+ PURCHASE_ORDERS = "purchase_orders"
20
+ INVENTORY_ITEMS = "inventory_items"
21
+
22
+
23
+ class ConversionRequest(BaseModel):
24
+ """Request model for GDF to CDF conversion."""
25
+ data: Union[List[Dict[str, Any]], Dict[str, Any]] = Field(
26
+ ..., description="Input GDF data as list of records or single record"
27
+ )
28
+ entity: EntityType = Field(..., description="Entity type to convert")
29
+ erp: Optional[str] = Field(None, description="ERP system name (optional for auto-detection)")
30
+ use_llm: bool = Field(True, description="Whether to use LLM fallback for unknown mappings")
31
+
32
+
33
+ class ConversionResponse(BaseModel):
34
+ """Response model for GDF to CDF conversion."""
35
+ success: bool = Field(..., description="Whether conversion was successful")
36
+ data: List[Dict[str, Any]] = Field(..., description="Converted CDF data")
37
+ detected_erp: Optional[str] = Field(None, description="Auto-detected ERP system")
38
+ mapping_source: str = Field(..., description="Source of mapping: 'template', 'llm', or 'fallback'")
39
+ message: Optional[str] = Field(None, description="Additional information or error message")
40
+
41
+
42
+ class SalesOrderCDF(BaseModel):
43
+ """CDF schema for sales orders."""
44
+ order_id: str = Field(..., max_length=64)
45
+ order_date: date
46
+ customer_id: str = Field(..., max_length=64)
47
+ status: str = Field(..., max_length=32)
48
+ currency: str = Field(..., max_length=8)
49
+ total_amount: Decimal = Field(..., decimal_places=2)
50
+ notes: Optional[str] = None
51
+ item_id: str = Field(..., max_length=64)
52
+ description: Optional[str] = None
53
+ quantity: int
54
+ unit_price: Decimal = Field(..., decimal_places=2)
55
+ line_total: Decimal = Field(..., decimal_places=2)
56
+ tax_code: Optional[str] = Field(None, max_length=32)
57
+
58
+
59
+ class CustomerCDF(BaseModel):
60
+ """CDF schema for customers."""
61
+ customer_id: str = Field(..., max_length=64)
62
+ customer_name: str = Field(..., max_length=255)
63
+ contact_email: Optional[str] = Field(None, max_length=255)
64
+ phone_number: Optional[str] = Field(None, max_length=32)
65
+ alt_phone: Optional[str] = Field(None, max_length=32)
66
+ is_company: Optional[bool] = None
67
+ status: str = Field(..., max_length=32)
68
+ currency: Optional[str] = Field(None, max_length=8)
69
+ created_date: Optional[datetime] = None
70
+ last_modified: Optional[datetime] = None
71
+
72
+
73
+ class InvoiceCDF(BaseModel):
74
+ """CDF schema for invoices."""
75
+ invoice_id: str = Field(..., max_length=64)
76
+ invoice_date: date
77
+ customer_id: str = Field(..., max_length=64)
78
+ status: str = Field(..., max_length=32)
79
+ currency: str = Field(..., max_length=8)
80
+ total_amount: Decimal = Field(..., decimal_places=2)
81
+ due_date: Optional[date] = None
82
+ notes: Optional[str] = None
83
+ item_id: str = Field(..., max_length=64)
84
+ description: Optional[str] = None
85
+ quantity: int
86
+ unit_price: Decimal = Field(..., decimal_places=2)
87
+ line_total: Decimal = Field(..., decimal_places=2)
88
+ tax_code: Optional[str] = Field(None, max_length=32)
89
+
90
+
91
+ class PurchaseOrderCDF(BaseModel):
92
+ """CDF schema for purchase orders."""
93
+ po_id: str = Field(..., max_length=64)
94
+ po_date: date
95
+ vendor_id: str = Field(..., max_length=64)
96
+ status: str = Field(..., max_length=32)
97
+ currency: str = Field(..., max_length=8)
98
+ total_amount: Decimal = Field(..., decimal_places=2)
99
+ expected_receipt_date: Optional[date] = None
100
+ notes: Optional[str] = None
101
+ item_id: str = Field(..., max_length=64)
102
+ description: Optional[str] = None
103
+ quantity: int
104
+ unit_price: Decimal = Field(..., decimal_places=2)
105
+ line_total: Decimal = Field(..., decimal_places=2)
106
+ tax_code: Optional[str] = Field(None, max_length=32)
107
+
108
+
109
+ class InventoryItemCDF(BaseModel):
110
+ """CDF schema for inventory items."""
111
+ item_id: str = Field(..., max_length=64)
112
+ item_name: str = Field(..., max_length=255)
113
+ description: Optional[str] = None
114
+ purchase_description: Optional[str] = None
115
+ sales_description: Optional[str] = None
116
+ base_price: Optional[Decimal] = Field(None, decimal_places=2)
117
+ cost_price: Optional[Decimal] = Field(None, decimal_places=2)
118
+ unit_type: Optional[str] = Field(None, max_length=32)
119
+ is_active: Optional[bool] = None
120
+ quantity_on_hand: Optional[int] = None
121
+ reorder_point: Optional[int] = None
122
+ preferred_vendor_id: Optional[str] = Field(None, max_length=64)
123
+
124
+
125
+ # Mapping of entity types to their CDF models
126
+ CDF_MODELS = {
127
+ EntityType.SALES_ORDERS: SalesOrderCDF,
128
+ EntityType.CUSTOMERS: CustomerCDF,
129
+ EntityType.INVOICES: InvoiceCDF,
130
+ EntityType.PURCHASE_ORDERS: PurchaseOrderCDF,
131
+ EntityType.INVENTORY_ITEMS: InventoryItemCDF,
132
+ }
mapper/template_loader.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Template loader for ERP to CDF mappings.
3
+ Handles loading and validation of mapping templates.
4
+ """
5
+
6
+ import json
7
+ from pathlib import Path
8
+ from typing import Dict, List, Optional
9
+
10
+ from .models import EntityType
11
+
12
+
13
+ class TemplateLoader:
14
+ """Loads and manages ERP to CDF mapping templates."""
15
+
16
+ def __init__(self, template_path: Optional[Path] = None):
17
+ """Initialize template loader.
18
+
19
+ Args:
20
+ template_path: Path to template.json file. Defaults to template.json in current directory.
21
+ """
22
+ self.template_path = template_path or Path("template.json")
23
+ self._template_cache: Optional[Dict] = None
24
+
25
+ def load_template(self) -> Dict[str, Dict[str, Dict[str, str]]]:
26
+ """Load mapping template from JSON file.
27
+
28
+ Returns:
29
+ Dictionary with structure: ERP -> entity -> {GDF_col: CDF_col}
30
+
31
+ Raises:
32
+ FileNotFoundError: If template file doesn't exist
33
+ ValueError: If template format is invalid
34
+ """
35
+ if self._template_cache is not None:
36
+ return self._template_cache
37
+
38
+ if not self.template_path.exists():
39
+ raise FileNotFoundError(f"Template file not found: {self.template_path}")
40
+
41
+ try:
42
+ with self.template_path.open('r', encoding='utf-8') as fp:
43
+ template = json.load(fp)
44
+ except json.JSONDecodeError as e:
45
+ raise ValueError(f"Invalid JSON in template file: {e}")
46
+
47
+ # Validate template structure
48
+ self._validate_template(template)
49
+ self._template_cache = template
50
+ return template
51
+
52
+ def _validate_template(self, template: Dict) -> None:
53
+ """Validate template structure and required fields.
54
+
55
+ Args:
56
+ template: Loaded template dictionary
57
+
58
+ Raises:
59
+ ValueError: If template structure is invalid
60
+ """
61
+ if not isinstance(template, dict):
62
+ raise ValueError("Template must be a dictionary")
63
+
64
+ # Check for CDF_META section
65
+ if "CDF_META" not in template:
66
+ raise ValueError("Template missing required 'CDF_META' section")
67
+
68
+ cdf_meta = template["CDF_META"]
69
+ if not isinstance(cdf_meta, dict):
70
+ raise ValueError("CDF_META must be a dictionary")
71
+
72
+ # Validate that all supported entities have CDF schemas
73
+ for entity in EntityType:
74
+ if entity.value not in cdf_meta:
75
+ raise ValueError(f"CDF_META missing schema for entity: {entity.value}")
76
+
77
+ if not isinstance(cdf_meta[entity.value], list):
78
+ raise ValueError(f"CDF schema for {entity.value} must be a list of column names")
79
+
80
+ def get_erp_names(self) -> List[str]:
81
+ """Get list of available ERP systems in template.
82
+
83
+ Returns:
84
+ List of ERP system names
85
+ """
86
+ template = self.load_template()
87
+ return [erp for erp in template.keys() if erp != "CDF_META"]
88
+
89
+ def get_entity_mapping(self, erp: str, entity: str) -> Optional[Dict[str, str]]:
90
+ """Get column mapping for specific ERP and entity.
91
+
92
+ Args:
93
+ erp: ERP system name
94
+ entity: Entity type
95
+
96
+ Returns:
97
+ Dictionary mapping GDF columns to CDF columns, or None if not found
98
+ """
99
+ template = self.load_template()
100
+ return template.get(erp, {}).get(entity)
101
+
102
+ def get_cdf_schema(self, entity: str) -> List[str]:
103
+ """Get CDF column schema for entity.
104
+
105
+ Args:
106
+ entity: Entity type
107
+
108
+ Returns:
109
+ List of CDF column names in correct order
110
+
111
+ Raises:
112
+ ValueError: If entity not found in CDF_META
113
+ """
114
+ template = self.load_template()
115
+ cdf_meta = template.get("CDF_META", {})
116
+
117
+ if entity not in cdf_meta:
118
+ raise ValueError(f"Entity '{entity}' not found in CDF_META")
119
+
120
+ return cdf_meta[entity]
121
+
122
+ def get_all_erp_columns(self, entity: str) -> Dict[str, List[str]]:
123
+ """Get all GDF columns for an entity across all ERPs.
124
+
125
+ Args:
126
+ entity: Entity type
127
+
128
+ Returns:
129
+ Dictionary mapping ERP names to lists of their GDF columns
130
+ """
131
+ template = self.load_template()
132
+ erp_columns = {}
133
+
134
+ for erp_name in self.get_erp_names():
135
+ mapping = self.get_entity_mapping(erp_name, entity)
136
+ if mapping:
137
+ erp_columns[erp_name] = list(mapping.keys())
138
+
139
+ return erp_columns
140
+
141
+ def reload_template(self) -> None:
142
+ """Force reload of template from file."""
143
+ self._template_cache = None
144
+ self.load_template()
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Core dependencies
2
+ pandas>=2.0.0
3
+ pydantic>=2.0.0
4
+ fastapi>=0.100.0
5
+ uvicorn[standard]>=0.20.0
6
+
7
+ # LLM integration (optional)
8
+ langchain-openai>=0.1.0
9
+ openai>=1.0.0
10
+
11
+ # Additional utilities
12
+ python-multipart # For FastAPI file uploads
13
+ python-dotenv # For environment variable management
14
+
15
+ # Development dependencies (optional)
16
+ pytest>=7.0.0
17
+ pytest-asyncio
18
+ httpx # For testing FastAPI endpoints
19
+ black # Code formatting
20
+ isort # Import sorting
21
+ mypy # Type checking
template (1).json ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "NetSuite": {
3
+ "sales_orders": {
4
+ "tranId": "order_id",
5
+ "trandate": "order_date",
6
+ "entity": "customer_id",
7
+ "status": "status",
8
+ "currency": "currency",
9
+ "total": "total_amount",
10
+ "memo": "notes",
11
+ "itemList.item": "item_id",
12
+ "itemList.description": "description",
13
+ "itemList.quantity": "quantity",
14
+ "itemList.rate": "unit_price",
15
+ "itemList.amount": "line_total",
16
+ "itemList.taxCode": "tax_code"
17
+ },
18
+ "customers": {
19
+ "entityId": "customer_id",
20
+ "companyName": "customer_name",
21
+ "email": "contact_email",
22
+ "phone": "phone_number",
23
+ "altPhone": "alt_phone",
24
+ "isPerson": "is_company",
25
+ "status": "status",
26
+ "currency": "currency",
27
+ "dateCreated": "created_date",
28
+ "lastModifiedDate": "last_modified"
29
+ }
30
+ },
31
+ "CDF_META": {
32
+ "sales_orders": [
33
+ "order_id",
34
+ "order_date",
35
+ "customer_id",
36
+ "status",
37
+ "currency",
38
+ "total_amount",
39
+ "notes",
40
+ "item_id",
41
+ "description",
42
+ "quantity",
43
+ "unit_price",
44
+ "line_total",
45
+ "tax_code"
46
+ ],
47
+ "customers": [
48
+ "customer_id",
49
+ "customer_name",
50
+ "contact_email",
51
+ "phone_number",
52
+ "alt_phone",
53
+ "is_company",
54
+ "status",
55
+ "currency",
56
+ "created_date",
57
+ "last_modified"
58
+ ]
59
+ }
60
+ }
template.json ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "NetSuite": {
3
+ "sales_orders": {
4
+ "tranId": "order_id",
5
+ "trandate": "order_date",
6
+ "entity": "customer_id",
7
+ "status": "status",
8
+ "currency": "currency",
9
+ "total": "total_amount",
10
+ "memo": "notes",
11
+ "itemList.item": "item_id",
12
+ "itemList.description": "description",
13
+ "itemList.quantity": "quantity",
14
+ "itemList.rate": "unit_price",
15
+ "itemList.amount": "line_total",
16
+ "itemList.taxCode": "tax_code"
17
+ },
18
+ "customers": {
19
+ "entityId": "customer_id",
20
+ "companyName": "customer_name",
21
+ "email": "contact_email",
22
+ "phone": "phone_number",
23
+ "altPhone": "alt_phone",
24
+ "isPerson": "is_company",
25
+ "status": "status",
26
+ "currency": "currency",
27
+ "dateCreated": "creasdfasdfated_date",
28
+ "lastModifiedDate": "last_modified"
29
+ }
30
+ },
31
+ "CDF_META": {
32
+ "sales_orders": [
33
+ "order_id",
34
+ "order_date",
35
+ "customer_id",
36
+ "status",
37
+ "currency",
38
+ "total_amount",
39
+ "notes",
40
+ "item_id",
41
+ "description",
42
+ "quantity",
43
+ "unit_price",
44
+ "line_total",
45
+ "tax_code"
46
+ ],
47
+ "customers": [
48
+ "customer_id",
49
+ "customer_name",
50
+ "contact_email",
51
+ "phone_number",
52
+ "alt_phone",
53
+ "is_company",
54
+ "status",
55
+ "currency",
56
+ "created_date",
57
+ "last_modified"
58
+ " ]
59
+ }
60
+ }
61
+
62
+ two cases for the transformation logic
63
+
64
+ CASE ERP and ENTITY type is known
65
+
66
+ "auto-select-erp":false
67
+ "auto-select-entity":false
68
+
69
+ Directly go and serach and map for template.json
70
+
71
+ CASE ERP OR ENTITY type or Both are UNKNOWN
72
+ "auto-select-unknown-name":false
73
+ First check template if matches use it to transform
74
+ Else use AI to transform
75
+
76
+ API Schema
77
+
78
+ {
79
+ "auto-select-erp" bool:
80
+ "auto-select-enitity" bool:
81
+ "enity" str:
82
+ "erp" str:
83
+ "file" file: csv, excel, json, sql
84
+ }
85
+
86
+ Use Pandas and DuckDB to generate input_dataframe from the file
87
+
88
+ output_dataframe = ai_transformation_function(other params from the json api as it is..., instead of file use input_dataframe, file_format):