Spaces:
Sleeping
Sleeping
Update zoho_client.py
Browse files- zoho_client.py +240 -239
zoho_client.py
CHANGED
|
@@ -4,6 +4,7 @@ import config
|
|
| 4 |
from utils import normalize_date
|
| 5 |
import time
|
| 6 |
import re
|
|
|
|
| 7 |
|
| 8 |
# =====================================================
|
| 9 |
# 1. CONFIGURATION
|
|
@@ -12,17 +13,25 @@ API_MATRIX = {
|
|
| 12 |
('invoice', 'create'): ('POST', 'invoices'),
|
| 13 |
('estimate', 'create'): ('POST', 'estimates'),
|
| 14 |
('credit_note', 'create'): ('POST', 'creditnotes'),
|
|
|
|
|
|
|
| 15 |
('bill', 'create'): ('POST', 'bills'),
|
| 16 |
('purchase_order', 'create'): ('POST', 'purchaseorders'),
|
| 17 |
('expense', 'create'): ('POST', 'expenses'),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
('payment', 'create'): ('POST', 'customerpayments'),
|
|
|
|
| 19 |
}
|
| 20 |
|
| 21 |
DEPENDENCY_MAP = {
|
| 22 |
-
'customer_id': '
|
| 23 |
-
'vendor_id': '
|
| 24 |
-
'project_id': 'project',
|
| 25 |
-
'account_id': '
|
| 26 |
}
|
| 27 |
|
| 28 |
DOC_TYPE_MAPPING = {
|
|
@@ -39,263 +48,255 @@ DOC_TYPE_MAPPING = {
|
|
| 39 |
ID_CACHE = {}
|
| 40 |
|
| 41 |
# =====================================================
|
| 42 |
-
# 2.
|
| 43 |
# =====================================================
|
| 44 |
-
def
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
def _execute_request(method, endpoint, payload, headers):
|
| 64 |
-
url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
|
| 65 |
-
try:
|
| 66 |
-
if method == 'POST': return requests.post(url, headers=headers, json=payload)
|
| 67 |
-
elif method == 'GET': return requests.get(url, headers=headers, params=payload)
|
| 68 |
-
except Exception as e: print(f"Net Error: {e}")
|
| 69 |
-
return None
|
| 70 |
|
| 71 |
# =====================================================
|
| 72 |
-
# 3.
|
| 73 |
# =====================================================
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
# 1. Strict Search
|
| 78 |
-
res = _execute_request('GET', search_url, {'contact_name_contains': name}, headers)
|
| 79 |
-
if res and res.status_code == 200:
|
| 80 |
-
contacts = res.json().get("contacts", [])
|
| 81 |
-
for c in contacts:
|
| 82 |
-
# Return first match
|
| 83 |
-
return c.get("contact_id"), c.get("contact_name")
|
| 84 |
-
return None, None
|
| 85 |
-
|
| 86 |
-
def create_contact(name, type_val, headers):
|
| 87 |
-
"""Try to create. Handle duplicates."""
|
| 88 |
-
payload = {"contact_name": name, "contact_type": type_val}
|
| 89 |
-
res = _execute_request('POST', "contacts", payload, headers)
|
| 90 |
-
|
| 91 |
-
if res and res.status_code == 201:
|
| 92 |
-
return res.json().get("contact", {}).get("contact_id"), "Created New"
|
| 93 |
-
|
| 94 |
-
# If Duplicate, we MUST be able to find it via search now
|
| 95 |
-
if res and res.json().get("code") == 3062:
|
| 96 |
-
found_id, found_name = search_contact(name, headers)
|
| 97 |
-
if found_id: return found_id, "Found (Recovered)"
|
| 98 |
-
|
| 99 |
-
return None, f"Failed: {res.text if res else 'No Resp'}"
|
| 100 |
|
| 101 |
-
def
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
# ---
|
| 112 |
-
|
| 113 |
-
|
|
|
|
| 114 |
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
return
|
| 120 |
-
|
| 121 |
-
# Attempt 2: Create New
|
| 122 |
-
yield f" ๐ Not found. Creating '{name}'..."
|
| 123 |
-
cid, status = create_contact(name, dep_type, headers)
|
| 124 |
-
if cid:
|
| 125 |
-
yield f" โ
Success: {status}"
|
| 126 |
-
return cid
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
|
|
|
|
|
|
| 142 |
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
-
# Create Default
|
| 155 |
-
payload = {"account_name": "MCP Auto Expenses", "account_type": "expense"}
|
| 156 |
-
res = _execute_request('POST', 'chartofaccounts', payload, headers)
|
| 157 |
if res and res.status_code == 201:
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
|
|
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
# 4. DATA MAPPING
|
| 164 |
-
# =====================================================
|
| 165 |
-
def map_line_items(raw_items, total_fallback):
|
| 166 |
-
"""Ensures line items exist and match API requirements."""
|
| 167 |
-
clean_items = []
|
| 168 |
-
|
| 169 |
-
# If AI failed to get items, create one from Total
|
| 170 |
-
if not raw_items:
|
| 171 |
-
return [{
|
| 172 |
-
"name": "Services Rendered",
|
| 173 |
-
"description": "Auto-generated from Total Amount",
|
| 174 |
-
"rate": _clean_amount(total_fallback),
|
| 175 |
-
"quantity": 1
|
| 176 |
-
}]
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 187 |
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 194 |
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
doc_type = ai_output.get("doc_type", "invoice").lower()
|
| 202 |
-
data = ai_output.get("data", {})
|
| 203 |
-
|
| 204 |
-
mapping = DOC_TYPE_MAPPING.get(doc_type, DOC_TYPE_MAPPING["invoice"])
|
| 205 |
-
entity, action, dep_field = mapping
|
| 206 |
-
|
| 207 |
-
yield f"๐ Routing: {entity.upper()} -> /{API_MATRIX[(entity, action)][1]}\n"
|
| 208 |
-
|
| 209 |
-
headers = get_headers()
|
| 210 |
-
if not headers:
|
| 211 |
-
yield "โ Auth Failed"
|
| 212 |
-
return
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
for log in resolve_dependency_step(dep_field, dep_name, headers):
|
| 220 |
-
if isinstance(log, str): yield log
|
| 221 |
-
else: dep_id = log # Capture returned ID if it's not a string log
|
| 222 |
-
|
| 223 |
-
if not dep_id:
|
| 224 |
-
# Last ditch effort: Try to use the ID from the generator loop if logic got mixed
|
| 225 |
-
# (Re-running simplified logic just to get ID if the loop above was only logging)
|
| 226 |
-
# In Python generators, return values are tricky. Let's use a wrapper approach.
|
| 227 |
-
# Simpler fix: The resolver creates/finds and returns.
|
| 228 |
-
# We will execute it purely for value now:
|
| 229 |
-
pass # The logic above yields logs. We need to refactor slightly to extract value.
|
| 230 |
-
# Refactoring resolve_dependency_step to NOT be a generator for logic simplicity here.
|
| 231 |
-
# See updated resolve_dependency_step above (it returns, doesn't yield).
|
| 232 |
-
# Wait, I made it yield logs above. Let's split it.
|
| 233 |
-
|
| 234 |
-
# --- FIX: Logic Separation for Generator ---
|
| 235 |
-
# To keep logs flowing AND get the ID, we do this:
|
| 236 |
-
|
| 237 |
-
# Re-run resolver logic properly here without yield to get ID
|
| 238 |
-
# (This duplicates the specific call but ensures we get the variable)
|
| 239 |
-
# Actually, let's just run it synchronously and print logs.
|
| 240 |
-
|
| 241 |
-
# -- EXECUTION BLOCK --
|
| 242 |
-
final_dep_id = None
|
| 243 |
-
|
| 244 |
-
# 1. Search
|
| 245 |
-
yield f"โ Resolving {DEPENDENCY_MAP[dep_field]} ('{dep_name}')..."
|
| 246 |
-
|
| 247 |
-
final_dep_id, status_msg = search_contact(dep_name, headers)
|
| 248 |
-
if final_dep_id:
|
| 249 |
-
yield f" โ
Found: {status_msg}"
|
| 250 |
-
else:
|
| 251 |
-
yield f" ๐ Creating: '{dep_name}'..."
|
| 252 |
-
final_dep_id, status_msg = create_contact(dep_name, DEPENDENCY_MAP[dep_field], headers)
|
| 253 |
|
| 254 |
-
|
| 255 |
-
yield " โ ๏ธ Failed. Switching to FALLBACK..."
|
| 256 |
-
fallback = f"MCP Fallback {DEPENDENCY_MAP[dep_field].capitalize()}"
|
| 257 |
-
final_dep_id, _ = search_contact(fallback, headers)
|
| 258 |
-
if not final_dep_id:
|
| 259 |
-
final_dep_id, _ = create_contact(fallback, DEPENDENCY_MAP[dep_field], headers)
|
| 260 |
-
|
| 261 |
-
if not final_dep_id:
|
| 262 |
-
yield "๐ FATAL: Could not resolve any Contact/Vendor."
|
| 263 |
-
return
|
| 264 |
|
| 265 |
-
#
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
|
|
|
|
|
|
| 284 |
|
| 285 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
yield "โ ๏ธ Auto-Number Conflict. Retrying..."
|
| 294 |
-
for k in ["invoice_number", "bill_number", "estimate_number"]:
|
| 295 |
-
if k in payload: del payload[k]
|
| 296 |
-
resp = _execute_request(method, endpoint, payload, headers)
|
| 297 |
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from utils import normalize_date
|
| 5 |
import time
|
| 6 |
import re
|
| 7 |
+
from functools import wraps
|
| 8 |
|
| 9 |
# =====================================================
|
| 10 |
# 1. CONFIGURATION
|
|
|
|
| 13 |
('invoice', 'create'): ('POST', 'invoices'),
|
| 14 |
('estimate', 'create'): ('POST', 'estimates'),
|
| 15 |
('credit_note', 'create'): ('POST', 'creditnotes'),
|
| 16 |
+
('retainer_invoice', 'create'): ('POST', 'retainerinvoices'),
|
| 17 |
+
('recurring_invoice', 'create'): ('POST', 'recurringinvoices'),
|
| 18 |
('bill', 'create'): ('POST', 'bills'),
|
| 19 |
('purchase_order', 'create'): ('POST', 'purchaseorders'),
|
| 20 |
('expense', 'create'): ('POST', 'expenses'),
|
| 21 |
+
('recurring_expense', 'create'): ('POST', 'recurringexpenses'),
|
| 22 |
+
('contact', 'create'): ('POST', 'contacts'),
|
| 23 |
+
('item', 'create'): ('POST', 'items'),
|
| 24 |
+
('project', 'create'): ('POST', 'projects'),
|
| 25 |
+
('task', 'create'): ('POST', 'projects/{project_id}/tasks'),
|
| 26 |
('payment', 'create'): ('POST', 'customerpayments'),
|
| 27 |
+
('chart_of_account', 'create'): ('POST', 'chartofaccounts'),
|
| 28 |
}
|
| 29 |
|
| 30 |
DEPENDENCY_MAP = {
|
| 31 |
+
'customer_id': ('contact', 'contact_name', 'MCP Customer'),
|
| 32 |
+
'vendor_id': ('contact', 'contact_name', 'MCP Vendor'),
|
| 33 |
+
'project_id': ('project', 'project_name', 'MCP General Project'),
|
| 34 |
+
'account_id': ('chart_of_account', 'account_name', 'MCP Auto Expenses'),
|
| 35 |
}
|
| 36 |
|
| 37 |
DOC_TYPE_MAPPING = {
|
|
|
|
| 48 |
ID_CACHE = {}
|
| 49 |
|
| 50 |
# =====================================================
|
| 51 |
+
# 2. RESILIENCE DECORATORS (The Armor)
|
| 52 |
# =====================================================
|
| 53 |
+
def retry_strategy(retries=3, backoff=1):
|
| 54 |
+
"""Feature 1: Exponential Backoff for Network Glitches"""
|
| 55 |
+
def decorator(func):
|
| 56 |
+
@wraps(func)
|
| 57 |
+
def wrapper(*args, **kwargs):
|
| 58 |
+
x = 0
|
| 59 |
+
while True:
|
| 60 |
+
try:
|
| 61 |
+
return func(*args, **kwargs)
|
| 62 |
+
except Exception as e:
|
| 63 |
+
if x == retries:
|
| 64 |
+
print(f"โ Network Error (Giving Up): {e}")
|
| 65 |
+
raise e
|
| 66 |
+
sleep_time = backoff * (2 ** x)
|
| 67 |
+
print(f"โ ๏ธ Connection Glitch. Retrying in {sleep_time}s...")
|
| 68 |
+
time.sleep(sleep_time)
|
| 69 |
+
x += 1
|
| 70 |
+
return wrapper
|
| 71 |
+
return decorator
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
# =====================================================
|
| 74 |
+
# 3. ORCHESTRATOR CLASS
|
| 75 |
# =====================================================
|
| 76 |
+
class ZohoOrchestrator:
|
| 77 |
+
def __init__(self):
|
| 78 |
+
self.headers = self._get_headers()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
def _get_headers(self):
|
| 81 |
+
try:
|
| 82 |
+
params = {
|
| 83 |
+
"refresh_token": config.REFRESH_TOKEN,
|
| 84 |
+
"client_id": config.CLIENT_ID,
|
| 85 |
+
"client_secret": config.CLIENT_SECRET,
|
| 86 |
+
"grant_type": "refresh_token",
|
| 87 |
+
"redirect_uri": "http://www.google.com"
|
| 88 |
+
}
|
| 89 |
+
resp = requests.post(config.AUTH_URL, data=params, timeout=10)
|
| 90 |
+
if resp.status_code == 200:
|
| 91 |
+
return {"Authorization": f"Zoho-oauthtoken {resp.json().get('access_token')}"}
|
| 92 |
+
except Exception as e:
|
| 93 |
+
print(f"Auth Error: {e}")
|
| 94 |
+
return None
|
| 95 |
|
| 96 |
+
# --- Feature 3: Pre-Flight Validator ---
|
| 97 |
+
def _validate_data(self, val, dtype="string"):
|
| 98 |
+
"""Cleans data types before sending."""
|
| 99 |
+
if val is None: return "" if dtype == "string" else 0
|
| 100 |
|
| 101 |
+
if dtype == "float":
|
| 102 |
+
try:
|
| 103 |
+
clean = str(val).replace(",", "").replace("$", "").replace("โน", "").strip()
|
| 104 |
+
return float(clean)
|
| 105 |
+
except: return 0.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
if dtype == "string":
|
| 108 |
+
clean = str(val).strip()
|
| 109 |
+
# Zoho Max Limits
|
| 110 |
+
if len(clean) > 200: return clean[:197] + "..."
|
| 111 |
+
return clean
|
| 112 |
+
|
| 113 |
+
return val
|
| 114 |
+
|
| 115 |
+
# --- Feature 2: Token Immortalizer ---
|
| 116 |
+
@retry_strategy(retries=3)
|
| 117 |
+
def _execute_request(self, method, endpoint, payload=None):
|
| 118 |
+
url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
|
| 119 |
|
| 120 |
+
if not self.headers:
|
| 121 |
+
self.headers = self._get_headers()
|
| 122 |
+
if not self.headers: return None # Auth failed completely
|
| 123 |
+
|
| 124 |
+
# Execute
|
| 125 |
+
if method == 'POST':
|
| 126 |
+
resp = requests.post(url, headers=self.headers, json=payload, timeout=15)
|
| 127 |
+
else:
|
| 128 |
+
resp = requests.get(url, headers=self.headers, params=payload, timeout=15)
|
| 129 |
+
|
| 130 |
+
# CHECK FOR EXPIRY (401)
|
| 131 |
+
if resp.status_code == 401:
|
| 132 |
+
print("๐ Token Expired. Refreshing...")
|
| 133 |
+
self.headers = self._get_headers()
|
| 134 |
+
# Retry once with new token
|
| 135 |
+
if method == 'POST':
|
| 136 |
+
resp = requests.post(url, headers=self.headers, json=payload, timeout=15)
|
| 137 |
+
else:
|
| 138 |
+
resp = requests.get(url, headers=self.headers, params=payload, timeout=15)
|
| 139 |
+
|
| 140 |
+
return resp
|
| 141 |
+
|
| 142 |
+
# -------------------------------------------------
|
| 143 |
+
# DEPENDENCY RESOLVER (Never-Fail)
|
| 144 |
+
# -------------------------------------------------
|
| 145 |
+
def resolve_dependency_step(self, dep_key, name):
|
| 146 |
+
dep_type = DEPENDENCY_MAP.get(dep_key, ('customer',))[0]
|
| 147 |
|
| 148 |
+
# Sanitize Name
|
| 149 |
+
name = self._validate_data(name, "string")
|
| 150 |
+
if not name or name.lower() in ["unknown", "none"]:
|
| 151 |
+
name = "MCP Auto Expenses" if dep_type == "chart_of_account" else f"MCP Generic {dep_type.capitalize()}"
|
| 152 |
|
| 153 |
+
# Check Cache
|
| 154 |
+
cache_key = f"{dep_type}_{name}"
|
| 155 |
+
if cache_key in ID_CACHE: return ID_CACHE[cache_key], "Cached"
|
| 156 |
+
|
| 157 |
+
# 1. SEARCH
|
| 158 |
+
search_ep = "chartofaccounts" if dep_type == "chart_of_account" else f"{dep_type}s"
|
| 159 |
+
if dep_type == "chart_of_account":
|
| 160 |
+
res = self._execute_request('GET', search_ep)
|
| 161 |
+
if res and res.status_code == 200:
|
| 162 |
+
for acc in res.json().get("chartofaccounts", []):
|
| 163 |
+
# Loose Match or Fallback to any Expense
|
| 164 |
+
if name.lower() in acc["account_name"].lower() or "expense" in acc["account_type"].lower():
|
| 165 |
+
ID_CACHE[cache_key] = acc['account_id']
|
| 166 |
+
return acc['account_id'], f"Using '{acc['account_name']}'"
|
| 167 |
+
else:
|
| 168 |
+
res = self._execute_request('GET', search_ep, {'contact_name_contains': name})
|
| 169 |
+
if res and res.status_code == 200:
|
| 170 |
+
contacts = res.json().get("contacts", [])
|
| 171 |
+
if contacts:
|
| 172 |
+
cid = contacts[0]["contact_id"]
|
| 173 |
+
ID_CACHE[cache_key] = cid
|
| 174 |
+
return cid, "Found Existing"
|
| 175 |
+
|
| 176 |
+
# 2. CREATE (With Fallback)
|
| 177 |
+
create_payload = {}
|
| 178 |
+
if dep_type == "contact":
|
| 179 |
+
c_type = 'vendor' if dep_key == 'vendor_id' else 'customer'
|
| 180 |
+
create_payload = {"contact_name": name, "contact_type": c_type}
|
| 181 |
+
elif dep_type == "chart_of_account":
|
| 182 |
+
create_payload = {"account_name": "MCP Auto Expenses", "account_type": "expense"}
|
| 183 |
+
|
| 184 |
+
res = self._execute_request('POST', search_ep, create_payload)
|
| 185 |
|
|
|
|
|
|
|
|
|
|
| 186 |
if res and res.status_code == 201:
|
| 187 |
+
# Extract ID
|
| 188 |
+
data = res.json()
|
| 189 |
+
inner = list(data.values())[1] if len(data) > 1 else list(data.values())[0]
|
| 190 |
+
if isinstance(inner, dict):
|
| 191 |
+
for k, v in inner.items():
|
| 192 |
+
if k.endswith('_id'):
|
| 193 |
+
ID_CACHE[cache_key] = v
|
| 194 |
+
return v, "Created New"
|
| 195 |
|
| 196 |
+
# 3. COLLISION RECOVERY (Existing but search failed)
|
| 197 |
+
if res and res.json().get("code") == 3062:
|
| 198 |
+
# Try creating with Timestamp suffix
|
| 199 |
+
return self.resolve_dependency_step(dep_key, f"{name} {int(time.time())}")
|
| 200 |
|
| 201 |
+
return None, "Failed"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
+
# -------------------------------------------------
|
| 204 |
+
# PAYLOAD BUILDER
|
| 205 |
+
# -------------------------------------------------
|
| 206 |
+
def build_payload(self, entity, data, dep_id, dep_field):
|
| 207 |
+
# Base
|
| 208 |
+
payload = {
|
| 209 |
+
"date": normalize_date(data.get("date")),
|
| 210 |
+
dep_field: dep_id
|
| 211 |
+
}
|
| 212 |
|
| 213 |
+
# Line Items (Validator Applied)
|
| 214 |
+
clean_items = []
|
| 215 |
+
raw_items = data.get("line_items", [])
|
| 216 |
+
if not raw_items:
|
| 217 |
+
total = self._validate_data(data.get("total"), "float")
|
| 218 |
+
raw_items = [{"name": "Services Rendered", "rate": total, "quantity": 1}]
|
| 219 |
+
|
| 220 |
+
for item in raw_items:
|
| 221 |
+
name = item.get("name") or item.get("description") or "Item"
|
| 222 |
+
desc = item.get("description", "")
|
| 223 |
|
| 224 |
+
# Handle Long Strings
|
| 225 |
+
name_str = self._validate_data(name, "string")
|
| 226 |
+
if len(name_str) > 95:
|
| 227 |
+
desc = f"{name_str}\n{desc}"
|
| 228 |
+
name_str = name_str[:95] + "..."
|
| 229 |
+
|
| 230 |
+
clean_items.append({
|
| 231 |
+
"name": name_str,
|
| 232 |
+
"description": self._validate_data(desc, "string"),
|
| 233 |
+
"rate": self._validate_data(item.get("rate"), "float"),
|
| 234 |
+
"quantity": self._validate_data(item.get("quantity", 1), "float")
|
| 235 |
+
})
|
| 236 |
|
| 237 |
+
payload["line_items"] = clean_items
|
| 238 |
+
payload["status"] = "draft"
|
| 239 |
+
|
| 240 |
+
if entity == 'expense':
|
| 241 |
+
payload["amount"] = self._validate_data(data.get("total"), "float")
|
| 242 |
+
payload["paid_through_account_id"] = dep_id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 243 |
|
| 244 |
+
# IDs
|
| 245 |
+
ref = data.get("reference_number") or f"AUTO-{int(time.time())}"
|
| 246 |
+
if entity == 'invoice': payload['invoice_number'] = ref
|
| 247 |
+
elif entity == 'bill': payload['bill_number'] = ref
|
| 248 |
+
elif entity == 'estimate': payload['estimate_number'] = ref
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 249 |
|
| 250 |
+
return payload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 251 |
|
| 252 |
+
# -------------------------------------------------
|
| 253 |
+
# MAIN PROCESS
|
| 254 |
+
# -------------------------------------------------
|
| 255 |
+
def process_document(self, ai_output):
|
| 256 |
+
doc_type = ai_output.get("doc_type", "invoice").lower()
|
| 257 |
+
data = ai_output.get("data", {})
|
| 258 |
+
|
| 259 |
+
mapping = DOC_TYPE_MAPPING.get(doc_type, DOC_TYPE_MAPPING["invoice"])
|
| 260 |
+
entity, action, dep_field = mapping
|
| 261 |
+
|
| 262 |
+
yield f"๐ Strategy: {entity.upper()}"
|
| 263 |
+
|
| 264 |
+
# 1. Dependencies
|
| 265 |
+
dep_name = data.get("vendor_name") or data.get("contact_name")
|
| 266 |
+
yield f"โ Resolving {dep_field}..."
|
| 267 |
+
dep_id, status = self.resolve_dependency_step(dep_field, dep_name)
|
| 268 |
+
yield f" -> {status} ({dep_id})"
|
| 269 |
+
|
| 270 |
+
if not dep_id:
|
| 271 |
+
yield "๐ Critical Dependency Failed."
|
| 272 |
+
return
|
| 273 |
|
| 274 |
+
# 2. Build
|
| 275 |
+
payload = self.build_payload(entity, data, dep_id, dep_field)
|
| 276 |
+
|
| 277 |
+
# 3. Send
|
| 278 |
+
yield "๐ Sending to Zoho..."
|
| 279 |
+
method, endpoint = API_MATRIX[(entity, action)]
|
| 280 |
+
resp = self._execute_request(method, endpoint, payload)
|
| 281 |
+
|
| 282 |
+
# 4. Retry Auto-Number
|
| 283 |
+
if resp and resp.status_code != 201 and resp.json().get("code") == 4097:
|
| 284 |
+
yield "โ ๏ธ Auto-Numbering detected. Retrying..."
|
| 285 |
+
for k in ["invoice_number", "bill_number", "estimate_number"]:
|
| 286 |
+
if k in payload: del payload[k]
|
| 287 |
+
resp = self._execute_request(method, endpoint, payload)
|
| 288 |
|
| 289 |
+
# 5. Result
|
| 290 |
+
if resp and resp.status_code == 201:
|
| 291 |
+
yield f"\nโ
SUCCESS! {entity.capitalize()} Created."
|
| 292 |
+
else:
|
| 293 |
+
err = resp.text if resp else "Unknown"
|
| 294 |
+
yield f"\nโ Zoho Error: {err}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 295 |
|
| 296 |
+
# =====================================================
|
| 297 |
+
# APP BRIDGE
|
| 298 |
+
# =====================================================
|
| 299 |
+
def route_and_execute(ai_output):
|
| 300 |
+
orch = ZohoOrchestrator()
|
| 301 |
+
for log in orch.process_document(ai_output):
|
| 302 |
+
yield log
|