Spaces:
Sleeping
Sleeping
Update zoho_client.py
Browse files- zoho_client.py +167 -169
zoho_client.py
CHANGED
|
@@ -2,34 +2,55 @@ import requests
|
|
| 2 |
import json
|
| 3 |
import config
|
| 4 |
from utils import normalize_date
|
| 5 |
-
from concurrent.futures import ThreadPoolExecutor
|
| 6 |
|
| 7 |
# =====================================================
|
| 8 |
-
# 1.
|
| 9 |
# =====================================================
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
"
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
"
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
}
|
| 28 |
|
| 29 |
-
ID_REGISTRY = {}
|
| 30 |
-
|
| 31 |
# =====================================================
|
| 32 |
-
# 2.
|
| 33 |
# =====================================================
|
| 34 |
def get_headers():
|
| 35 |
try:
|
|
@@ -46,173 +67,150 @@ def get_headers():
|
|
| 46 |
except: pass
|
| 47 |
return None
|
| 48 |
|
| 49 |
-
def resolve_id(ref_id):
|
| 50 |
-
return ID_REGISTRY.get(ref_id, ref_id)
|
| 51 |
-
|
| 52 |
-
def sanitize_payload(payload):
|
| 53 |
-
"""Trims strings to fit Zoho limits"""
|
| 54 |
-
clean = payload.copy()
|
| 55 |
-
if "line_items" in clean:
|
| 56 |
-
new_items = []
|
| 57 |
-
for item in clean["line_items"]:
|
| 58 |
-
name = item.get("name", "")
|
| 59 |
-
if len(name) > 100:
|
| 60 |
-
item["description"] = f"{name} \n {item.get('description', '')}"
|
| 61 |
-
item["name"] = name[:95] + "..."
|
| 62 |
-
new_items.append(item)
|
| 63 |
-
clean["line_items"] = new_items
|
| 64 |
-
return clean
|
| 65 |
-
|
| 66 |
# =====================================================
|
| 67 |
-
# 3.
|
| 68 |
# =====================================================
|
| 69 |
-
def
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
res = requests.get(search_url, headers=headers)
|
| 109 |
-
contacts = res.json().get("contacts", [])
|
| 110 |
-
if contacts: return contacts[0]["contact_id"]
|
| 111 |
-
except: pass
|
| 112 |
-
|
| 113 |
-
# Create
|
| 114 |
-
new_id, status = execute_api_call("contacts", {"contact_name": name, "contact_type": "customer"})
|
| 115 |
-
return new_id
|
| 116 |
|
| 117 |
-
|
| 118 |
-
"""Finds or Creates an Expense Account (Required for Expenses)"""
|
| 119 |
-
headers = get_headers()
|
| 120 |
-
url = f"{config.API_BASE}/chartofaccounts?organization_id={config.ORGANIZATION_ID}"
|
| 121 |
-
try:
|
| 122 |
-
res = requests.get(url, headers=headers)
|
| 123 |
-
for acc in res.json().get("chartofaccounts", []):
|
| 124 |
-
if "expense" in acc["account_type"].lower(): return acc["account_id"]
|
| 125 |
-
except: pass
|
| 126 |
-
|
| 127 |
-
# Create
|
| 128 |
-
new_id, _ = execute_api_call("chartofaccounts", {"account_name": "MCP Auto Expenses", "account_type": "expense"})
|
| 129 |
-
return new_id
|
| 130 |
|
| 131 |
# =====================================================
|
| 132 |
-
#
|
| 133 |
# =====================================================
|
| 134 |
-
def
|
| 135 |
"""
|
| 136 |
-
|
| 137 |
"""
|
| 138 |
-
|
| 139 |
-
|
| 140 |
|
| 141 |
-
|
|
|
|
| 142 |
|
| 143 |
-
#
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
if not cid: return "β Dependency Error: Could not create Customer."
|
| 150 |
-
|
| 151 |
-
# Format Data
|
| 152 |
-
payload = {
|
| 153 |
-
"customer_id": cid,
|
| 154 |
-
"date": normalize_date(data.get("date")),
|
| 155 |
-
"line_items": data.get("line_items", [{"name": "Services", "rate": 0, "quantity": 1}]),
|
| 156 |
-
"status": "draft"
|
| 157 |
-
}
|
| 158 |
-
# Specific fields
|
| 159 |
-
if doc_type == "invoice": payload["invoice_number"] = data.get("reference_number")
|
| 160 |
-
if doc_type == "estimate": payload["estimate_number"] = data.get("reference_number")
|
| 161 |
-
|
| 162 |
-
obj_id, msg = execute_api_call(endpoint, payload)
|
| 163 |
-
if obj_id: return f"β
{doc_type.title()} Created! ID: {obj_id}"
|
| 164 |
-
return f"β {doc_type.title()} Failed: {msg}"
|
| 165 |
|
| 166 |
-
# ---
|
| 167 |
-
|
| 168 |
-
#
|
| 169 |
-
|
| 170 |
-
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
"account_id": acc_id,
|
| 176 |
-
"paid_through_account_id": acc_id, # Simplification
|
| 177 |
-
"vendor_id": cid,
|
| 178 |
-
"reference_number": data.get("reference_number")
|
| 179 |
-
}
|
| 180 |
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
-
# ---
|
| 186 |
-
elif
|
| 187 |
-
payload =
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
obj_id, msg = execute_api_call("contacts", payload)
|
| 192 |
-
if obj_id: return f"β
Contact Created: {obj_id}"
|
| 193 |
-
return f"β Contact Failed: {msg}"
|
| 194 |
|
| 195 |
-
|
| 196 |
-
else:
|
| 197 |
-
return f"β οΈ Unknown Document Type: '{doc_type}'. Logic not implemented."
|
| 198 |
|
| 199 |
# =====================================================
|
| 200 |
-
#
|
| 201 |
# =====================================================
|
| 202 |
-
def
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 207 |
|
| 208 |
-
|
|
|
|
| 209 |
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
import json
|
| 3 |
import config
|
| 4 |
from utils import normalize_date
|
|
|
|
| 5 |
|
| 6 |
# =====================================================
|
| 7 |
+
# 1. THE DECISION TABLE (Orchestration Logic)
|
| 8 |
# =====================================================
|
| 9 |
+
# Defines how to handle each document type.
|
| 10 |
+
# - endpoint: The API route
|
| 11 |
+
# - dependency: What needs to exist first? (customer/vendor/account)
|
| 12 |
+
# - payload_map: How to format the JSON for Zoho
|
| 13 |
+
DECISION_TABLE = {
|
| 14 |
+
"invoice": {
|
| 15 |
+
"endpoint": "invoices",
|
| 16 |
+
"dependency": "customer",
|
| 17 |
+
"id_key": "invoice_number",
|
| 18 |
+
"payload_type": "sales"
|
| 19 |
+
},
|
| 20 |
+
"estimate": {
|
| 21 |
+
"endpoint": "estimates",
|
| 22 |
+
"dependency": "customer",
|
| 23 |
+
"id_key": "estimate_number",
|
| 24 |
+
"payload_type": "sales"
|
| 25 |
+
},
|
| 26 |
+
"credit_note": {
|
| 27 |
+
"endpoint": "creditnotes",
|
| 28 |
+
"dependency": "customer",
|
| 29 |
+
"id_key": "creditnote_number",
|
| 30 |
+
"payload_type": "sales"
|
| 31 |
+
},
|
| 32 |
+
"bill": {
|
| 33 |
+
"endpoint": "bills",
|
| 34 |
+
"dependency": "vendor",
|
| 35 |
+
"id_key": "bill_number",
|
| 36 |
+
"payload_type": "purchase"
|
| 37 |
+
},
|
| 38 |
+
"purchase_order": {
|
| 39 |
+
"endpoint": "purchaseorders",
|
| 40 |
+
"dependency": "vendor",
|
| 41 |
+
"id_key": "purchaseorder_number",
|
| 42 |
+
"payload_type": "purchase"
|
| 43 |
+
},
|
| 44 |
+
"expense": {
|
| 45 |
+
"endpoint": "expenses",
|
| 46 |
+
"dependency": "account",
|
| 47 |
+
"id_key": "reference_number",
|
| 48 |
+
"payload_type": "expense"
|
| 49 |
+
}
|
| 50 |
}
|
| 51 |
|
|
|
|
|
|
|
| 52 |
# =====================================================
|
| 53 |
+
# 2. CORE UTILS
|
| 54 |
# =====================================================
|
| 55 |
def get_headers():
|
| 56 |
try:
|
|
|
|
| 67 |
except: pass
|
| 68 |
return None
|
| 69 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
# =====================================================
|
| 71 |
+
# 3. DEPENDENCY RESOLVERS
|
| 72 |
# =====================================================
|
| 73 |
+
def resolve_dependency(dep_type, name, headers):
|
| 74 |
+
"""
|
| 75 |
+
Ensures the required Parent Entity exists.
|
| 76 |
+
"""
|
| 77 |
+
if not name: name = "MCP Generic Contact"
|
| 78 |
|
| 79 |
+
# --- CUSTOMER / VENDOR ---
|
| 80 |
+
if dep_type in ["customer", "vendor"]:
|
| 81 |
+
# Search
|
| 82 |
+
search_url = f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}&contact_name_contains={name}"
|
| 83 |
+
try:
|
| 84 |
+
res = requests.get(search_url, headers=headers)
|
| 85 |
+
contacts = res.json().get("contacts", [])
|
| 86 |
+
if contacts:
|
| 87 |
+
print(f" β
Found {dep_type}: {contacts[0]['contact_name']}")
|
| 88 |
+
return contacts[0]["contact_id"]
|
| 89 |
+
except: pass
|
| 90 |
+
|
| 91 |
+
# Create
|
| 92 |
+
print(f" π Creating {dep_type}: {name}")
|
| 93 |
+
payload = {"contact_name": name, "contact_type": dep_type}
|
| 94 |
+
res = requests.post(f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}", headers=headers, json=payload)
|
| 95 |
+
if res.status_code == 201:
|
| 96 |
+
return res.json().get("contact", {}).get("contact_id")
|
| 97 |
|
| 98 |
+
# --- EXPENSE ACCOUNT ---
|
| 99 |
+
elif dep_type == "account":
|
| 100 |
+
# Find Expense Account
|
| 101 |
+
url = f"{config.API_BASE}/chartofaccounts?organization_id={config.ORGANIZATION_ID}"
|
| 102 |
+
try:
|
| 103 |
+
res = requests.get(url, headers=headers)
|
| 104 |
+
for acc in res.json().get("chartofaccounts", []):
|
| 105 |
+
if "expense" in acc["account_type"].lower():
|
| 106 |
+
return acc["account_id"]
|
| 107 |
+
except: pass
|
| 108 |
+
|
| 109 |
+
# Create
|
| 110 |
+
payload = {"account_name": "MCP Auto Expenses", "account_type": "expense"}
|
| 111 |
+
res = requests.post(url, headers=headers, json=payload)
|
| 112 |
+
if res.status_code == 201: return res.json().get("chartofaccount", {}).get("account_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
|
| 116 |
# =====================================================
|
| 117 |
+
# 4. PAYLOAD FACTORY
|
| 118 |
# =====================================================
|
| 119 |
+
def build_payload(doc_type, data, dependency_id):
|
| 120 |
"""
|
| 121 |
+
Constructs the Zoho JSON based on the Decision Table strategy.
|
| 122 |
"""
|
| 123 |
+
strategy = DECISION_TABLE.get(doc_type)
|
| 124 |
+
if not strategy: return None
|
| 125 |
|
| 126 |
+
ptype = strategy["payload_type"]
|
| 127 |
+
date_val = normalize_date(data.get("date"))
|
| 128 |
|
| 129 |
+
# Base Payload
|
| 130 |
+
payload = {"date": date_val}
|
| 131 |
+
|
| 132 |
+
# Add Reference Number (Invoice #, PO #)
|
| 133 |
+
ref_key = strategy["id_key"]
|
| 134 |
+
payload[ref_key] = data.get("reference_number") or f"AUTO-{int(time.time())}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
# --- SALES & PURCHASES ---
|
| 137 |
+
if ptype in ["sales", "purchase"]:
|
| 138 |
+
# Link Contact
|
| 139 |
+
key = "customer_id" if strategy["dependency"] == "customer" else "vendor_id"
|
| 140 |
+
payload[key] = dependency_id
|
| 141 |
|
| 142 |
+
# Line Items
|
| 143 |
+
raw_items = data.get("line_items", [])
|
| 144 |
+
if not raw_items: raw_items = [{"name": "Services", "rate": 0, "quantity": 1}]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
+
clean_items = []
|
| 147 |
+
for item in raw_items:
|
| 148 |
+
name = item.get("name", "Item")
|
| 149 |
+
# Truncate long names
|
| 150 |
+
desc = item.get("description", "")
|
| 151 |
+
if len(name) > 100:
|
| 152 |
+
desc = f"{name}\n{desc}"
|
| 153 |
+
name = name[:95] + "..."
|
| 154 |
+
|
| 155 |
+
clean_items.append({
|
| 156 |
+
"name": name,
|
| 157 |
+
"description": desc,
|
| 158 |
+
"rate": item.get("rate", 0),
|
| 159 |
+
"quantity": item.get("quantity", 1)
|
| 160 |
+
})
|
| 161 |
+
payload["line_items"] = clean_items
|
| 162 |
+
payload["status"] = "draft"
|
| 163 |
|
| 164 |
+
# --- EXPENSES ---
|
| 165 |
+
elif ptype == "expense":
|
| 166 |
+
payload["account_id"] = dependency_id
|
| 167 |
+
payload["amount"] = data.get("total", 0)
|
| 168 |
+
# Vendor is optional but good to have
|
| 169 |
+
# payload["vendor_id"] = ... (requires separate lookup)
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
+
return payload
|
|
|
|
|
|
|
| 172 |
|
| 173 |
# =====================================================
|
| 174 |
+
# 5. MASTER EXECUTOR
|
| 175 |
# =====================================================
|
| 176 |
+
def route_and_execute(ai_output):
|
| 177 |
+
doc_type = ai_output.get("doc_type", "unknown")
|
| 178 |
+
data = ai_output.get("data", {})
|
| 179 |
+
|
| 180 |
+
# 1. Lookup Strategy
|
| 181 |
+
strategy = DECISION_TABLE.get(doc_type)
|
| 182 |
+
if not strategy:
|
| 183 |
+
return f"β οΈ Unknown Document Type: '{doc_type}'. Check Decision Table."
|
| 184 |
+
|
| 185 |
+
print(f"π Routing: {doc_type} -> /{strategy['endpoint']}")
|
| 186 |
+
|
| 187 |
+
# 2. Auth
|
| 188 |
+
headers = get_headers()
|
| 189 |
+
if not headers: return "Auth Failed"
|
| 190 |
+
|
| 191 |
+
# 3. Resolve Dependency (Customer/Vendor/Account)
|
| 192 |
+
dep_name = data.get("contact_name") or data.get("vendor_name")
|
| 193 |
+
dep_id = resolve_dependency(strategy["dependency"], dep_name, headers)
|
| 194 |
+
|
| 195 |
+
if not dep_id:
|
| 196 |
+
return f"β Dependency Failed: Could not create/find {strategy['dependency']}."
|
| 197 |
|
| 198 |
+
# 4. Build Payload
|
| 199 |
+
zoho_payload = build_payload(doc_type, data, dep_id)
|
| 200 |
|
| 201 |
+
# 5. Execute API Call
|
| 202 |
+
url = f"{config.API_BASE}/{strategy['endpoint']}?organization_id={config.ORGANIZATION_ID}"
|
| 203 |
+
try:
|
| 204 |
+
resp = requests.post(url, headers=headers, json=zoho_payload)
|
| 205 |
+
if resp.status_code == 201:
|
| 206 |
+
res_data = resp.json()
|
| 207 |
+
# Generic ID finder
|
| 208 |
+
keys = list(res_data.keys())
|
| 209 |
+
main_key = keys[1] if keys[0] == "code" and len(keys) > 1 else keys[0]
|
| 210 |
+
obj_id = res_data[main_key].get(f"{main_key}_id")
|
| 211 |
|
| 212 |
+
return f"β
{doc_type.upper()} Created! ID: {obj_id}\nEndpoint: {strategy['endpoint']}"
|
| 213 |
+
|
| 214 |
+
return f"β Zoho Error: {resp.text}"
|
| 215 |
+
except Exception as e:
|
| 216 |
+
return f"β System Error: {e}"
|