diff --git a/app/system/backend/sync_router.py b/app/system/backend/sync_router.py index ee16c1d..df00a2b 100644 --- a/app/system/backend/sync_router.py +++ b/app/system/backend/sync_router.py @@ -205,6 +205,7 @@ async def sync_vtiger_contacts() -> Dict[str, Any]: updated_count = 0 skipped_count = 0 linked_count = 0 + customers_created_count = 0 debug_count = 0 for i, contact in enumerate(all_contacts, 1): @@ -288,13 +289,102 @@ async def sync_vtiger_contacts() -> Dict[str, Any]: ) if not customer_result or len(customer_result) == 0: - # No matching customer found - if debug_count <= 20: - logger.warning(f" ↳ No customer found with vtiger_id={account_id}") - continue - - customer_id = customer_result[0]['id'] - customer_name = customer_result[0]['name'] + # FALLBACK: Create customer from vTiger account if not found + try: + account_query = f"SELECT id, accountname, email1, siccode, cf_accounts_cvr, website, bill_city, bill_code, bill_country FROM Accounts WHERE id = '{account_id}';" + account_data = await vtiger.query(account_query) + + if account_data and len(account_data) > 0: + account = account_data[0] + account_name = account.get('accountname', '').strip() + cvr = account.get('cf_accounts_cvr') or account.get('siccode') + + if cvr: + cvr = re.sub(r'\D', '', str(cvr))[:8] + if len(cvr) != 8: + cvr = None + + # Check if customer already exists by CVR (to avoid duplicates) + if cvr: + existing_by_cvr = execute_query( + "SELECT id, name FROM customers WHERE cvr_number = %s", + (cvr,) + ) + if existing_by_cvr: + # Found by CVR - update vtiger_id and use this customer + execute_query( + "UPDATE customers SET vtiger_id = %s, last_synced_at = NOW() WHERE id = %s", + (account_id, existing_by_cvr[0]['id']) + ) + customer_id = existing_by_cvr[0]['id'] + customer_name = existing_by_cvr[0]['name'] + logger.info(f"✅ Matched by CVR and updated vtiger_id: {customer_name} → {account_id}") + else: + # Create new customer from vTiger + country = (account.get('bill_country') or 'DK').strip().upper()[:2] + new_customer = execute_query(""" + INSERT INTO customers + (name, cvr_number, email, website, city, postal_code, country, vtiger_id, last_synced_at) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW()) + RETURNING id, name + """, ( + account_name, + cvr, + account.get('email1'), + account.get('website'), + account.get('bill_city'), + account.get('bill_code'), + country, + account_id + )) + + if new_customer: + customer_id = new_customer[0]['id'] + customer_name = new_customer[0]['name'] + customers_created_count += 1 + logger.info(f"✨ Created customer from vTiger: {customer_name} (vtiger_id={account_id})") + else: + if debug_count <= 20: + logger.warning(f" ↳ Failed to create customer from account_id={account_id}") + continue + else: + # No CVR - create customer anyway (might be foreign company) + country = (account.get('bill_country') or 'DK').strip().upper()[:2] + new_customer = execute_query(""" + INSERT INTO customers + (name, email, website, city, postal_code, country, vtiger_id, last_synced_at) + VALUES (%s, %s, %s, %s, %s, %s, %s, NOW()) + RETURNING id, name + """, ( + account_name, + account.get('email1'), + account.get('website'), + account.get('bill_city'), + account.get('bill_code'), + country, + account_id + )) + + if new_customer: + customer_id = new_customer[0]['id'] + customer_name = new_customer[0]['name'] + customers_created_count += 1 + logger.info(f"✨ Created customer from vTiger (no CVR): {customer_name} (vtiger_id={account_id})") + else: + if debug_count <= 20: + logger.warning(f" ↳ Failed to create customer from account_id={account_id}") + continue + else: + if debug_count <= 20: + logger.warning(f" ↳ Account not found in vTiger: {account_id}") + continue + + except Exception as e: + logger.error(f"❌ Failed to fetch/create customer from vTiger account {account_id}: {e}") + continue + else: + customer_id = customer_result[0]['id'] + customer_name = customer_result[0]['name'] # Check if link already exists existing_link = execute_query( @@ -318,13 +408,14 @@ async def sync_vtiger_contacts() -> Dict[str, Any]: if linked_count <= 10: # Log first 10 successful links logger.info(f"🔗 LINKED: {first_name} {last_name} → {customer_name}") - logger.info(f"✅ SYNC COMPLETE: created={created_count}, updated={updated_count}, linked={linked_count}, skipped={skipped_count}, total={len(all_contacts)}") + logger.info(f"✅ SYNC COMPLETE: created={created_count}, updated={updated_count}, linked={linked_count}, customers_created={customers_created_count}, skipped={skipped_count}, total={len(all_contacts)}") return { "status": "success", "created": created_count, "updated": updated_count, "linked": linked_count, + "customers_created": customers_created_count, "skipped": skipped_count, "total_processed": len(all_contacts) }