Spaces:
Sleeping
Sleeping
Update zoho_client.py
Browse files- zoho_client.py +59 -34
zoho_client.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
| 1 |
import requests
|
|
|
|
| 2 |
import config
|
| 3 |
from utils import normalize_date
|
| 4 |
|
| 5 |
def get_headers():
|
|
|
|
| 6 |
try:
|
| 7 |
params = {
|
| 8 |
"refresh_token": config.REFRESH_TOKEN,
|
|
@@ -18,82 +20,105 @@ def get_headers():
|
|
| 18 |
except Exception as e:
|
| 19 |
return None, str(e)
|
| 20 |
|
| 21 |
-
def
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
clean_name = str(name).strip()
|
| 24 |
if len(clean_name) < 2: clean_name = "MCP Customer"
|
| 25 |
|
| 26 |
search_url = f"{config.API_BASE}/contacts"
|
| 27 |
|
| 28 |
-
# ---
|
| 29 |
-
def
|
| 30 |
try:
|
| 31 |
params = {
|
| 32 |
"organization_id": config.ORGANIZATION_ID,
|
| 33 |
"contact_name_contains": target_name
|
| 34 |
-
#
|
| 35 |
}
|
| 36 |
resp = requests.get(search_url, headers=headers, params=params)
|
| 37 |
contacts = resp.json().get("contacts", [])
|
| 38 |
-
|
| 39 |
-
# Look for a decent match
|
| 40 |
for c in contacts:
|
|
|
|
| 41 |
if target_name.lower() in c["contact_name"].lower():
|
| 42 |
print(f"β
Found Existing Contact: {c['contact_name']} ({c['contact_id']})")
|
| 43 |
-
return c["contact_id"]
|
| 44 |
-
except:
|
| 45 |
-
|
| 46 |
-
return None
|
| 47 |
|
| 48 |
-
#
|
| 49 |
-
|
| 50 |
-
if
|
| 51 |
|
| 52 |
-
#
|
| 53 |
-
print(f"π Creating Customer: {clean_name}")
|
| 54 |
-
create_payload = {
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
create_resp = requests.post(search_url, headers=headers, params={"organization_id": config.ORGANIZATION_ID}, json=create_payload)
|
| 56 |
|
| 57 |
-
# 3. Handle Results
|
| 58 |
if create_resp.status_code == 201:
|
| 59 |
return create_resp.json().get("contact", {}).get("contact_id"), "Created New"
|
| 60 |
|
|
|
|
| 61 |
elif create_resp.json().get("code") == 3062:
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
if
|
| 66 |
-
return None, f"Error: Name '{clean_name}' exists, but I cannot retrieve its ID. Please check Zoho Manually."
|
| 67 |
|
|
|
|
|
|
|
| 68 |
else:
|
| 69 |
-
return None, f"Contact Error: {create_resp.text}"
|
| 70 |
|
| 71 |
def push_invoice(payload):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
headers, error = get_headers()
|
| 73 |
if error: return error
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
cid, c_status =
|
| 77 |
-
if not cid: return f"β
|
| 78 |
|
| 79 |
-
#
|
| 80 |
final_date = normalize_date(payload.get("date"))
|
| 81 |
-
|
| 82 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
zoho_json = {
|
| 84 |
"customer_id": cid,
|
| 85 |
"date": final_date,
|
| 86 |
-
"line_items":
|
| 87 |
"status": "draft"
|
| 88 |
}
|
| 89 |
|
| 90 |
-
|
|
|
|
|
|
|
| 91 |
url = f"{config.API_BASE}/invoices?organization_id={config.ORGANIZATION_ID}"
|
| 92 |
resp = requests.post(url, headers=headers, json=zoho_json)
|
| 93 |
|
|
|
|
| 94 |
if resp.status_code == 201:
|
| 95 |
inv = resp.json().get("invoice", {})
|
| 96 |
link = f"https://books.zoho.in/app/{config.ORGANIZATION_ID}#/invoices/{inv.get('invoice_id')}"
|
| 97 |
-
return f"β
SUCCESS! Invoice #{inv.get('invoice_number')} Created.\
|
| 98 |
|
| 99 |
-
|
|
|
|
|
|
| 1 |
import requests
|
| 2 |
+
import json
|
| 3 |
import config
|
| 4 |
from utils import normalize_date
|
| 5 |
|
| 6 |
def get_headers():
|
| 7 |
+
"""Generates the OAuth Header"""
|
| 8 |
try:
|
| 9 |
params = {
|
| 10 |
"refresh_token": config.REFRESH_TOKEN,
|
|
|
|
| 20 |
except Exception as e:
|
| 21 |
return None, str(e)
|
| 22 |
|
| 23 |
+
def get_contact_id_robust(name, headers):
|
| 24 |
+
"""
|
| 25 |
+
STRATEGY:
|
| 26 |
+
1. Search for the name (Fuzzy Match).
|
| 27 |
+
2. If found -> Return ID.
|
| 28 |
+
3. If not found -> Create New.
|
| 29 |
+
4. If creation fails (Duplicate) -> Force Search Again.
|
| 30 |
+
"""
|
| 31 |
clean_name = str(name).strip()
|
| 32 |
if len(clean_name) < 2: clean_name = "MCP Customer"
|
| 33 |
|
| 34 |
search_url = f"{config.API_BASE}/contacts"
|
| 35 |
|
| 36 |
+
# --- HELPER: SEARCH FUNCTION ---
|
| 37 |
+
def execute_search(target_name):
|
| 38 |
try:
|
| 39 |
params = {
|
| 40 |
"organization_id": config.ORGANIZATION_ID,
|
| 41 |
"contact_name_contains": target_name
|
| 42 |
+
# Removed 'contact_type' so we find both Customers & Vendors
|
| 43 |
}
|
| 44 |
resp = requests.get(search_url, headers=headers, params=params)
|
| 45 |
contacts = resp.json().get("contacts", [])
|
|
|
|
|
|
|
| 46 |
for c in contacts:
|
| 47 |
+
# Basic validation to ensure we didn't match "John" with "Johnson"
|
| 48 |
if target_name.lower() in c["contact_name"].lower():
|
| 49 |
print(f"β
Found Existing Contact: {c['contact_name']} ({c['contact_id']})")
|
| 50 |
+
return c["contact_id"]
|
| 51 |
+
except Exception as e:
|
| 52 |
+
print(f"β οΈ Search warning: {e}")
|
| 53 |
+
return None
|
| 54 |
|
| 55 |
+
# STEP 1: Try Search
|
| 56 |
+
existing_id = execute_search(clean_name)
|
| 57 |
+
if existing_id: return existing_id, "Existing"
|
| 58 |
|
| 59 |
+
# STEP 2: Try Create
|
| 60 |
+
print(f"π Creating New Customer: {clean_name}")
|
| 61 |
+
create_payload = {
|
| 62 |
+
"contact_name": clean_name,
|
| 63 |
+
"contact_type": "customer",
|
| 64 |
+
"payment_terms": 0 # Due on Receipt
|
| 65 |
+
}
|
| 66 |
create_resp = requests.post(search_url, headers=headers, params={"organization_id": config.ORGANIZATION_ID}, json=create_payload)
|
| 67 |
|
|
|
|
| 68 |
if create_resp.status_code == 201:
|
| 69 |
return create_resp.json().get("contact", {}).get("contact_id"), "Created New"
|
| 70 |
|
| 71 |
+
# STEP 3: Handle "Already Exists" (Code 3062)
|
| 72 |
elif create_resp.json().get("code") == 3062:
|
| 73 |
+
print(f"β οΈ Name Collision for '{clean_name}'. Retrying Search...")
|
| 74 |
+
# Search again (Just in case)
|
| 75 |
+
retry_id = execute_search(clean_name)
|
| 76 |
+
if retry_id: return retry_id, "Found (Recovered)"
|
|
|
|
| 77 |
|
| 78 |
+
return None, f"CRITICAL: Name '{clean_name}' exists, but API cannot retrieve ID. Manual check required."
|
| 79 |
+
|
| 80 |
else:
|
| 81 |
+
return None, f"Contact Creation Error: {create_resp.text}"
|
| 82 |
|
| 83 |
def push_invoice(payload):
|
| 84 |
+
"""
|
| 85 |
+
Orchestrates the Invoice Creation.
|
| 86 |
+
"""
|
| 87 |
+
# 1. Auth
|
| 88 |
headers, error = get_headers()
|
| 89 |
if error: return error
|
| 90 |
|
| 91 |
+
# 2. Get Contact ID (Guaranteed to return ID or fail with detailed error)
|
| 92 |
+
cid, c_status = get_contact_id_robust(payload.get("vendor_name"), headers)
|
| 93 |
+
if not cid: return f"β Stopped at Contact Step: {c_status}"
|
| 94 |
|
| 95 |
+
# 3. Clean Date
|
| 96 |
final_date = normalize_date(payload.get("date"))
|
| 97 |
+
|
| 98 |
+
# 4. Construct Invoice Payload
|
| 99 |
+
# Ensure line_items is never empty
|
| 100 |
+
items = payload.get("line_items", [])
|
| 101 |
+
if not items:
|
| 102 |
+
items = [{"name": "Services Rendered (AI Generated)", "rate": 0, "quantity": 1}]
|
| 103 |
+
|
| 104 |
zoho_json = {
|
| 105 |
"customer_id": cid,
|
| 106 |
"date": final_date,
|
| 107 |
+
"line_items": items,
|
| 108 |
"status": "draft"
|
| 109 |
}
|
| 110 |
|
| 111 |
+
print(f"π Pushing Invoice for CID: {cid}...")
|
| 112 |
+
|
| 113 |
+
# 5. Execute API Call
|
| 114 |
url = f"{config.API_BASE}/invoices?organization_id={config.ORGANIZATION_ID}"
|
| 115 |
resp = requests.post(url, headers=headers, json=zoho_json)
|
| 116 |
|
| 117 |
+
# 6. Handle Response
|
| 118 |
if resp.status_code == 201:
|
| 119 |
inv = resp.json().get("invoice", {})
|
| 120 |
link = f"https://books.zoho.in/app/{config.ORGANIZATION_ID}#/invoices/{inv.get('invoice_id')}"
|
| 121 |
+
return f"β
SUCCESS! Invoice #{inv.get('invoice_number')} Created.\nCustomer: {c_status}\nLink: {link}"
|
| 122 |
|
| 123 |
+
# 7. Return Detailed Error if Invoice fails
|
| 124 |
+
return f"β Zoho Invoice Error: {resp.text}"
|