vachaspathi commited on
Commit
e3dcd01
ยท
verified ยท
1 Parent(s): 5865513

Update zoho_client.py

Browse files
Files changed (1) hide show
  1. 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': 'customer',
23
- 'vendor_id': 'vendor',
24
- 'project_id': 'project',
25
- 'account_id': 'account'
26
  }
27
 
28
  DOC_TYPE_MAPPING = {
@@ -39,263 +48,255 @@ DOC_TYPE_MAPPING = {
39
  ID_CACHE = {}
40
 
41
  # =====================================================
42
- # 2. UTILITIES
43
  # =====================================================
44
- def get_headers():
45
- try:
46
- params = {
47
- "refresh_token": config.REFRESH_TOKEN,
48
- "client_id": config.CLIENT_ID,
49
- "client_secret": config.CLIENT_SECRET,
50
- "grant_type": "refresh_token",
51
- "redirect_uri": "http://www.google.com"
52
- }
53
- resp = requests.post(config.AUTH_URL, data=params)
54
- if resp.status_code == 200:
55
- return {"Authorization": f"Zoho-oauthtoken {resp.json().get('access_token')}"}
56
- except: pass
57
- return None
58
-
59
- def _clean_amount(val):
60
- try: return float(str(val).replace(",", "").replace("$", "").strip())
61
- except: return 0.0
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. THE "NEVER-FAIL" RESOLVER
73
  # =====================================================
74
- def search_contact(name, headers):
75
- """Try to find contact by strict or loose name match."""
76
- search_url = "contacts"
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 resolve_dependency_step(dep_key, name, headers):
102
- """
103
- Cascading Logic: Search -> Create -> Fallback
104
- """
105
- dep_type = DEPENDENCY_MAP.get(dep_key, 'customer')
106
-
107
- # 1. Sanitization
108
- if not name or str(name).lower() in ["unknown", "none", "null"]:
109
- name = "Unknown Party"
 
 
 
 
 
 
110
 
111
- # --- A. CONTACTS (Customer/Vendor) ---
112
- if dep_type in ['customer', 'vendor']:
113
- yield f" ๐Ÿ”Ž Looking for {dep_type}: '{name}'..."
 
114
 
115
- # Attempt 1: Find Existing
116
- cid, status = search_contact(name, headers)
117
- if cid:
118
- yield f" โœ… Found Existing: {status}"
119
- return cid
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
- # Attempt 3: FALLBACK (The Safety Net)
129
- fallback_name = f"MCP Fallback {dep_type.capitalize()}"
130
- yield f" โš ๏ธ Creation Failed. Switching to Fallback: '{fallback_name}'..."
131
-
132
- # Search Fallback
133
- cid, _ = search_contact(fallback_name, headers)
134
- if cid: return cid
 
 
 
 
 
135
 
136
- # Create Fallback
137
- cid, status = create_contact(fallback_name, dep_type, headers)
138
- if cid: return cid
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
 
140
- yield " ๐Ÿ›‘ All attempts failed."
141
- return None
 
 
142
 
143
- # --- B. ACCOUNTS ---
144
- elif dep_type == 'account':
145
- # Logic: Find ANY expense account
146
- res = _execute_request('GET', 'chartofaccounts', {}, headers)
147
- if res:
148
- accounts = res.json().get("chartofaccounts", [])
149
- for acc in accounts:
150
- if "expense" in acc.get("account_type", "").lower():
151
- yield f" โœ… Using Account: {acc['account_name']}"
152
- return acc['account_id']
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- return res.json().get("chartofaccount", {}).get("account_id")
 
 
 
 
 
 
 
159
 
160
- return None
 
 
 
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
- for item in raw_items:
179
- name = item.get("name") or item.get("description") or "Item"
180
- desc = item.get("description", "")
181
- rate = _clean_amount(item.get("rate", 0))
182
- qty = _clean_amount(item.get("quantity", 1))
 
 
 
 
183
 
184
- if len(str(name)) > 100:
185
- desc = f"{name}\n{desc}"
186
- name = str(name)[:95] + "..."
 
 
 
 
 
 
 
187
 
188
- clean_items.append({
189
- "name": str(name),
190
- "description": str(desc),
191
- "rate": rate,
192
- "quantity": qty
193
- })
 
 
 
 
 
 
194
 
195
- return clean_items
196
-
197
- # =====================================================
198
- # 5. ORCHESTRATOR
199
- # =====================================================
200
- def route_and_execute(ai_output):
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
- # 1. RESOLVE DEPENDENCY (With Fallback)
215
- dep_name = data.get("vendor_name") or data.get("contact_name")
216
-
217
- # We use a generator inside a generator, so we loop to yield logs
218
- dep_id = None
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
- if not final_dep_id:
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
- # 2. BUILD PAYLOAD
266
- payload = {
267
- "date": normalize_date(data.get("date")),
268
- dep_field: final_dep_id
269
- }
270
-
271
- # Handle Items (Fixes "0 items" bug)
272
- payload["line_items"] = map_line_items(data.get("line_items"), data.get("total", 0))
273
-
274
- # IDs & Status
275
- ref_num = data.get("reference_number") or f"AUTO-{int(time.time())}"
276
- if entity == 'invoice': payload['invoice_number'] = ref_num
277
- elif entity == 'bill': payload['bill_number'] = ref_num
278
- elif entity == 'estimate': payload['estimate_number'] = ref_num
279
- payload['status'] = 'draft'
280
-
281
- if entity == 'expense':
282
- payload['amount'] = _clean_amount(data.get("total"))
283
- payload['paid_through_account_id'] = final_dep_id # Hack for MVP
 
 
284
 
285
- yield f"\n๐Ÿ“ฆ Generated Payload with {len(payload['line_items'])} items."
 
 
 
 
 
 
 
 
 
 
 
 
 
286
 
287
- # 3. SEND
288
- method, endpoint = API_MATRIX[(entity, action)]
289
- resp = _execute_request(method, endpoint, payload, headers)
290
-
291
- # Retry Auto-Number
292
- if resp and resp.status_code != 201 and resp.json().get("code") == 4097:
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
- if resp and resp.status_code == 201:
299
- yield f"\nโœ… SUCCESS! {entity.upper()} Created."
300
- else:
301
- yield f"\nโŒ Error: {resp.text if resp else 'None'}"
 
 
 
 
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