Spaces:
Sleeping
Sleeping
Update zoho_client.py
Browse files- zoho_client.py +75 -65
zoho_client.py
CHANGED
|
@@ -3,10 +3,10 @@ import json
|
|
| 3 |
import config
|
| 4 |
from utils import normalize_date
|
| 5 |
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
-
import time
|
| 7 |
|
| 8 |
# =====================================================
|
| 9 |
-
# 1.
|
| 10 |
# =====================================================
|
| 11 |
DECISION_TABLE = {
|
| 12 |
"invoice": {
|
|
@@ -47,6 +47,8 @@ DECISION_TABLE = {
|
|
| 47 |
}
|
| 48 |
}
|
| 49 |
|
|
|
|
|
|
|
| 50 |
# =====================================================
|
| 51 |
# 2. CORE UTILS
|
| 52 |
# =====================================================
|
|
@@ -65,19 +67,12 @@ def get_headers():
|
|
| 65 |
except: pass
|
| 66 |
return None
|
| 67 |
|
| 68 |
-
def resolve_id(ref_id):
|
| 69 |
-
return ID_REGISTRY.get(ref_id, ref_id)
|
| 70 |
-
|
| 71 |
def sanitize_payload(payload):
|
| 72 |
-
"""Trims strings to fit Zoho limits"""
|
| 73 |
clean = payload.copy()
|
| 74 |
if "line_items" in clean:
|
| 75 |
new_items = []
|
| 76 |
for item in clean["line_items"]:
|
| 77 |
-
name = item.get("name", "")
|
| 78 |
-
# Ensure name is a string
|
| 79 |
-
if not isinstance(name, str): name = str(name)
|
| 80 |
-
|
| 81 |
if len(name) > 100:
|
| 82 |
item["description"] = f"{name} \n {item.get('description', '')}"
|
| 83 |
item["name"] = name[:95] + "..."
|
|
@@ -86,52 +81,83 @@ def sanitize_payload(payload):
|
|
| 86 |
return clean
|
| 87 |
|
| 88 |
# =====================================================
|
| 89 |
-
# 3. DEPENDENCY
|
| 90 |
# =====================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
def resolve_dependency(dep_type, name, headers):
|
| 92 |
"""
|
| 93 |
-
|
|
|
|
|
|
|
| 94 |
"""
|
| 95 |
if not name or str(name).lower() == "unknown":
|
| 96 |
name = "MCP Generic Contact"
|
| 97 |
|
| 98 |
# --- CUSTOMER / VENDOR ---
|
| 99 |
if dep_type in ["customer", "vendor"]:
|
| 100 |
-
|
| 101 |
-
search_url = f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}&contact_name_contains={name}"
|
| 102 |
-
try:
|
| 103 |
-
res = requests.get(search_url, headers=headers)
|
| 104 |
-
contacts = res.json().get("contacts", [])
|
| 105 |
-
if contacts:
|
| 106 |
-
print(f" β
Found {dep_type}: {contacts[0]['contact_name']}")
|
| 107 |
-
return contacts[0]["contact_id"]
|
| 108 |
-
except: pass
|
| 109 |
|
| 110 |
-
#
|
| 111 |
-
|
| 112 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
c_type = "customer" if dep_type == "customer" else "vendor"
|
| 114 |
payload = {"contact_name": name, "contact_type": c_type}
|
| 115 |
|
| 116 |
res = requests.post(f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}", headers=headers, json=payload)
|
|
|
|
| 117 |
if res.status_code == 201:
|
| 118 |
-
|
|
|
|
|
|
|
|
|
|
| 119 |
elif res.json().get("code") == 3062:
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
# --- EXPENSE ACCOUNT ---
|
| 125 |
elif dep_type == "account":
|
| 126 |
-
#
|
| 127 |
url = f"{config.API_BASE}/chartofaccounts?organization_id={config.ORGANIZATION_ID}"
|
| 128 |
try:
|
| 129 |
res = requests.get(url, headers=headers)
|
| 130 |
for acc in res.json().get("chartofaccounts", []):
|
| 131 |
-
if "expense" in acc["account_type"].lower():
|
| 132 |
-
return acc["account_id"]
|
| 133 |
except: pass
|
| 134 |
-
|
| 135 |
# Create
|
| 136 |
payload = {"account_name": "MCP Auto Expenses", "account_type": "expense"}
|
| 137 |
res = requests.post(url, headers=headers, json=payload)
|
|
@@ -143,38 +169,33 @@ def resolve_dependency(dep_type, name, headers):
|
|
| 143 |
# 4. PAYLOAD FACTORY
|
| 144 |
# =====================================================
|
| 145 |
def build_payload(doc_type, data, dependency_id):
|
| 146 |
-
"""
|
| 147 |
-
Constructs the Zoho JSON based on the Decision Table strategy.
|
| 148 |
-
"""
|
| 149 |
strategy = DECISION_TABLE.get(doc_type)
|
| 150 |
if not strategy: return None
|
| 151 |
|
| 152 |
ptype = strategy["payload_type"]
|
| 153 |
date_val = normalize_date(data.get("date"))
|
| 154 |
|
| 155 |
-
# Base Payload
|
| 156 |
payload = {"date": date_val}
|
| 157 |
|
| 158 |
-
#
|
| 159 |
ref_key = strategy["id_key"]
|
| 160 |
-
#
|
| 161 |
-
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
#
|
| 164 |
if ptype in ["sales", "purchase"]:
|
| 165 |
-
# Link Contact
|
| 166 |
key = "customer_id" if strategy["dependency"] == "customer" else "vendor_id"
|
| 167 |
payload[key] = dependency_id
|
| 168 |
|
| 169 |
-
# Line Items
|
| 170 |
raw_items = data.get("line_items", [])
|
| 171 |
if not raw_items: raw_items = [{"name": "Services", "rate": 0, "quantity": 1}]
|
| 172 |
|
| 173 |
clean_items = []
|
| 174 |
for item in raw_items:
|
| 175 |
-
name = item.get("name", "Item")
|
| 176 |
-
|
| 177 |
-
desc = item.get("description", "")
|
| 178 |
if len(name) > 100:
|
| 179 |
desc = f"{name}\n{desc}"
|
| 180 |
name = name[:95] + "..."
|
|
@@ -188,57 +209,46 @@ def build_payload(doc_type, data, dependency_id):
|
|
| 188 |
payload["line_items"] = clean_items
|
| 189 |
payload["status"] = "draft"
|
| 190 |
|
| 191 |
-
#
|
| 192 |
elif ptype == "expense":
|
| 193 |
payload["account_id"] = dependency_id
|
| 194 |
payload["amount"] = data.get("total", 0)
|
| 195 |
-
# Vendor is optional but good to have
|
| 196 |
-
# payload["vendor_id"] = ... (requires separate lookup)
|
| 197 |
|
| 198 |
return payload
|
| 199 |
|
| 200 |
# =====================================================
|
| 201 |
-
# 5.
|
| 202 |
# =====================================================
|
| 203 |
def route_and_execute(ai_output):
|
| 204 |
-
"""
|
| 205 |
-
Takes the AI JSON {doc_type, data} and routes to the correct function.
|
| 206 |
-
"""
|
| 207 |
doc_type = ai_output.get("doc_type", "unknown").lower()
|
| 208 |
data = sanitize_payload(ai_output.get("data", {}))
|
| 209 |
|
| 210 |
-
# 1. Lookup Strategy
|
| 211 |
strategy = DECISION_TABLE.get(doc_type)
|
| 212 |
-
if not strategy:
|
| 213 |
-
return f"β οΈ Unknown Document Type: '{doc_type}'. Check Decision Table."
|
| 214 |
|
| 215 |
print(f"π Routing: {doc_type} -> /{strategy['endpoint']}")
|
| 216 |
|
| 217 |
-
# 2. Auth
|
| 218 |
headers = get_headers()
|
| 219 |
if not headers: return "Auth Failed"
|
| 220 |
|
| 221 |
-
#
|
| 222 |
dep_name = data.get("contact_name") or data.get("vendor_name")
|
| 223 |
dep_id = resolve_dependency(strategy["dependency"], dep_name, headers)
|
| 224 |
|
| 225 |
-
if not dep_id:
|
| 226 |
-
return f"β Dependency Failed: Could not create/find {strategy['dependency']}."
|
| 227 |
|
| 228 |
-
#
|
| 229 |
zoho_payload = build_payload(doc_type, data, dep_id)
|
| 230 |
-
|
| 231 |
-
# 5. Execute API Call
|
| 232 |
url = f"{config.API_BASE}/{strategy['endpoint']}?organization_id={config.ORGANIZATION_ID}"
|
|
|
|
| 233 |
try:
|
| 234 |
resp = requests.post(url, headers=headers, json=zoho_payload)
|
| 235 |
if resp.status_code == 201:
|
| 236 |
res_data = resp.json()
|
| 237 |
-
# Generic ID finder
|
| 238 |
keys = list(res_data.keys())
|
|
|
|
| 239 |
main_key = keys[1] if keys[0] == "code" and len(keys) > 1 else keys[0]
|
| 240 |
obj_id = res_data[main_key].get(f"{main_key}_id")
|
| 241 |
-
|
| 242 |
return f"β
{doc_type.upper()} Created! ID: {obj_id}\nEndpoint: {strategy['endpoint']}"
|
| 243 |
|
| 244 |
return f"β Zoho Error: {resp.text}"
|
|
|
|
| 3 |
import config
|
| 4 |
from utils import normalize_date
|
| 5 |
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
+
import time
|
| 7 |
|
| 8 |
# =====================================================
|
| 9 |
+
# 1. DECISION TABLE (Routing Logic)
|
| 10 |
# =====================================================
|
| 11 |
DECISION_TABLE = {
|
| 12 |
"invoice": {
|
|
|
|
| 47 |
}
|
| 48 |
}
|
| 49 |
|
| 50 |
+
ID_REGISTRY = {}
|
| 51 |
+
|
| 52 |
# =====================================================
|
| 53 |
# 2. CORE UTILS
|
| 54 |
# =====================================================
|
|
|
|
| 67 |
except: pass
|
| 68 |
return None
|
| 69 |
|
|
|
|
|
|
|
|
|
|
| 70 |
def sanitize_payload(payload):
|
|
|
|
| 71 |
clean = payload.copy()
|
| 72 |
if "line_items" in clean:
|
| 73 |
new_items = []
|
| 74 |
for item in clean["line_items"]:
|
| 75 |
+
name = str(item.get("name", ""))
|
|
|
|
|
|
|
|
|
|
| 76 |
if len(name) > 100:
|
| 77 |
item["description"] = f"{name} \n {item.get('description', '')}"
|
| 78 |
item["name"] = name[:95] + "..."
|
|
|
|
| 81 |
return clean
|
| 82 |
|
| 83 |
# =====================================================
|
| 84 |
+
# 3. SMART DEPENDENCY RESOLVER (The Fix)
|
| 85 |
# =====================================================
|
| 86 |
+
|
| 87 |
+
def find_contact_by_name(name, headers):
|
| 88 |
+
"""
|
| 89 |
+
Searches for a contact using 'contact_name_contains'.
|
| 90 |
+
Returns ID if found, else None.
|
| 91 |
+
"""
|
| 92 |
+
search_url = f"{config.API_BASE}/contacts"
|
| 93 |
+
params = {
|
| 94 |
+
"organization_id": config.ORGANIZATION_ID,
|
| 95 |
+
"contact_name_contains": name
|
| 96 |
+
}
|
| 97 |
+
try:
|
| 98 |
+
res = requests.get(search_url, headers=headers, params=params)
|
| 99 |
+
contacts = res.json().get("contacts", [])
|
| 100 |
+
for c in contacts:
|
| 101 |
+
# Loose match check
|
| 102 |
+
if name.lower() in c["contact_name"].lower() or c["contact_name"].lower() in name.lower():
|
| 103 |
+
return c["contact_id"]
|
| 104 |
+
except: pass
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
def resolve_dependency(dep_type, name, headers):
|
| 108 |
"""
|
| 109 |
+
1. Search
|
| 110 |
+
2. Create
|
| 111 |
+
3. Recover from Duplicate Error
|
| 112 |
"""
|
| 113 |
if not name or str(name).lower() == "unknown":
|
| 114 |
name = "MCP Generic Contact"
|
| 115 |
|
| 116 |
# --- CUSTOMER / VENDOR ---
|
| 117 |
if dep_type in ["customer", "vendor"]:
|
| 118 |
+
print(f" π Searching for {dep_type}: {name}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
+
# 1. First Search
|
| 121 |
+
existing_id = find_contact_by_name(name, headers)
|
| 122 |
+
if existing_id:
|
| 123 |
+
print(f" β
Found Existing: {existing_id}")
|
| 124 |
+
return existing_id
|
| 125 |
+
|
| 126 |
+
# 2. Attempt Creation
|
| 127 |
+
print(f" π Attempting Create: {name}")
|
| 128 |
c_type = "customer" if dep_type == "customer" else "vendor"
|
| 129 |
payload = {"contact_name": name, "contact_type": c_type}
|
| 130 |
|
| 131 |
res = requests.post(f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}", headers=headers, json=payload)
|
| 132 |
+
|
| 133 |
if res.status_code == 201:
|
| 134 |
+
new_id = res.json().get("contact", {}).get("contact_id")
|
| 135 |
+
print(f" β
Created New: {new_id}")
|
| 136 |
+
return new_id
|
| 137 |
+
|
| 138 |
elif res.json().get("code") == 3062:
|
| 139 |
+
print(" β οΈ Duplicate Error. Recovering...")
|
| 140 |
+
# 3. RECOVERY STRATEGY: Search by first word
|
| 141 |
+
# If "Dr. Pranith Goli" fails, search "Pranith"
|
| 142 |
+
first_word = name.split(" ")[0]
|
| 143 |
+
if len(first_word) > 2:
|
| 144 |
+
retry_id = find_contact_by_name(first_word, headers)
|
| 145 |
+
if retry_id:
|
| 146 |
+
print(f" β
Recovered ID: {retry_id}")
|
| 147 |
+
return retry_id
|
| 148 |
+
|
| 149 |
+
print(" β Recovery Failed. Name exists but unsearchable.")
|
| 150 |
+
return None
|
| 151 |
+
|
| 152 |
# --- EXPENSE ACCOUNT ---
|
| 153 |
elif dep_type == "account":
|
| 154 |
+
# Search
|
| 155 |
url = f"{config.API_BASE}/chartofaccounts?organization_id={config.ORGANIZATION_ID}"
|
| 156 |
try:
|
| 157 |
res = requests.get(url, headers=headers)
|
| 158 |
for acc in res.json().get("chartofaccounts", []):
|
| 159 |
+
if "expense" in acc["account_type"].lower(): return acc["account_id"]
|
|
|
|
| 160 |
except: pass
|
|
|
|
| 161 |
# Create
|
| 162 |
payload = {"account_name": "MCP Auto Expenses", "account_type": "expense"}
|
| 163 |
res = requests.post(url, headers=headers, json=payload)
|
|
|
|
| 169 |
# 4. PAYLOAD FACTORY
|
| 170 |
# =====================================================
|
| 171 |
def build_payload(doc_type, data, dependency_id):
|
|
|
|
|
|
|
|
|
|
| 172 |
strategy = DECISION_TABLE.get(doc_type)
|
| 173 |
if not strategy: return None
|
| 174 |
|
| 175 |
ptype = strategy["payload_type"]
|
| 176 |
date_val = normalize_date(data.get("date"))
|
| 177 |
|
|
|
|
| 178 |
payload = {"date": date_val}
|
| 179 |
|
| 180 |
+
# Reference Number
|
| 181 |
ref_key = strategy["id_key"]
|
| 182 |
+
# Clean Ref Number
|
| 183 |
+
ref_val = data.get("reference_number")
|
| 184 |
+
if not ref_val: ref_val = f"AUTO-{int(time.time())}"
|
| 185 |
+
payload[ref_key] = ref_val
|
| 186 |
|
| 187 |
+
# SALES / PURCHASE
|
| 188 |
if ptype in ["sales", "purchase"]:
|
|
|
|
| 189 |
key = "customer_id" if strategy["dependency"] == "customer" else "vendor_id"
|
| 190 |
payload[key] = dependency_id
|
| 191 |
|
|
|
|
| 192 |
raw_items = data.get("line_items", [])
|
| 193 |
if not raw_items: raw_items = [{"name": "Services", "rate": 0, "quantity": 1}]
|
| 194 |
|
| 195 |
clean_items = []
|
| 196 |
for item in raw_items:
|
| 197 |
+
name = str(item.get("name", "Item"))
|
| 198 |
+
desc = str(item.get("description", ""))
|
|
|
|
| 199 |
if len(name) > 100:
|
| 200 |
desc = f"{name}\n{desc}"
|
| 201 |
name = name[:95] + "..."
|
|
|
|
| 209 |
payload["line_items"] = clean_items
|
| 210 |
payload["status"] = "draft"
|
| 211 |
|
| 212 |
+
# EXPENSE
|
| 213 |
elif ptype == "expense":
|
| 214 |
payload["account_id"] = dependency_id
|
| 215 |
payload["amount"] = data.get("total", 0)
|
|
|
|
|
|
|
| 216 |
|
| 217 |
return payload
|
| 218 |
|
| 219 |
# =====================================================
|
| 220 |
+
# 5. ORCHESTRATOR
|
| 221 |
# =====================================================
|
| 222 |
def route_and_execute(ai_output):
|
|
|
|
|
|
|
|
|
|
| 223 |
doc_type = ai_output.get("doc_type", "unknown").lower()
|
| 224 |
data = sanitize_payload(ai_output.get("data", {}))
|
| 225 |
|
|
|
|
| 226 |
strategy = DECISION_TABLE.get(doc_type)
|
| 227 |
+
if not strategy: return f"β οΈ Unknown Document Type: '{doc_type}'"
|
|
|
|
| 228 |
|
| 229 |
print(f"π Routing: {doc_type} -> /{strategy['endpoint']}")
|
| 230 |
|
|
|
|
| 231 |
headers = get_headers()
|
| 232 |
if not headers: return "Auth Failed"
|
| 233 |
|
| 234 |
+
# Resolve Dependency (With Retry Logic)
|
| 235 |
dep_name = data.get("contact_name") or data.get("vendor_name")
|
| 236 |
dep_id = resolve_dependency(strategy["dependency"], dep_name, headers)
|
| 237 |
|
| 238 |
+
if not dep_id: return f"β Dependency Failed: Could not create/find {strategy['dependency']} ({dep_name})."
|
|
|
|
| 239 |
|
| 240 |
+
# Build & Send
|
| 241 |
zoho_payload = build_payload(doc_type, data, dep_id)
|
|
|
|
|
|
|
| 242 |
url = f"{config.API_BASE}/{strategy['endpoint']}?organization_id={config.ORGANIZATION_ID}"
|
| 243 |
+
|
| 244 |
try:
|
| 245 |
resp = requests.post(url, headers=headers, json=zoho_payload)
|
| 246 |
if resp.status_code == 201:
|
| 247 |
res_data = resp.json()
|
|
|
|
| 248 |
keys = list(res_data.keys())
|
| 249 |
+
# Find the ID in response
|
| 250 |
main_key = keys[1] if keys[0] == "code" and len(keys) > 1 else keys[0]
|
| 251 |
obj_id = res_data[main_key].get(f"{main_key}_id")
|
|
|
|
| 252 |
return f"β
{doc_type.upper()} Created! ID: {obj_id}\nEndpoint: {strategy['endpoint']}"
|
| 253 |
|
| 254 |
return f"β Zoho Error: {resp.text}"
|