vachaspathi commited on
Commit
1b85df7
·
verified ·
1 Parent(s): 5c3f15e

Update zoho_client.py

Browse files
Files changed (1) hide show
  1. zoho_client.py +109 -150
zoho_client.py CHANGED
@@ -6,50 +6,34 @@ import time
6
  from concurrent.futures import ThreadPoolExecutor, as_completed
7
 
8
  # =====================================================
9
- # 1. API ROUTE MAPPING & CONFIG
10
  # =====================================================
11
- # Maps internal JSON keys to Zoho API Routes
12
- # Dynamic segments are marked with {variable}
13
  API_ROUTES = {
14
- # --- SETTINGS & META ---
15
  "taxes": "settings/taxes",
16
  "expense_categories": "expensecategories",
17
  "price_lists": "pricebooks",
18
-
19
- # --- CORE ENTITIES ---
20
  "contacts": "contacts",
21
- "contact_persons": "contacts/contactpersons", # Sub-entity of contact
22
  "items": "items",
23
-
24
- # --- PROJECT MANAGEMENT ---
25
  "projects": "projects",
26
- "tasks": "projects/{project_id}/tasks", # Requires project_id context
27
  "time_entries": "projects/timeentries",
28
-
29
- # --- SALES TRANSACTIONS ---
30
  "estimates": "estimates",
31
  "retainer_invoices": "retainerinvoices",
32
  "invoices": "invoices",
33
  "recurring_invoices": "recurringinvoices",
34
  "credit_notes": "creditnotes",
35
-
36
- # --- PURCHASES & EXPENSES ---
37
  "expenses": "expenses",
38
  "recurring_expenses": "recurringexpenses",
39
-
40
- # --- BANKING & PAYMENTS ---
41
  "customer_payments": "customerpayments"
42
  }
43
 
44
- # ID REGISTRY: Maps "JSON Placeholder IDs" -> "Real Zoho IDs"
45
  ID_REGISTRY = {}
46
 
47
  # =====================================================
48
  # 2. CORE UTILITIES
49
  # =====================================================
50
-
51
  def get_headers():
52
- """Generates fresh OAuth Headers"""
53
  try:
54
  params = {
55
  "refresh_token": config.REFRESH_TOKEN,
@@ -59,214 +43,189 @@ def get_headers():
59
  "redirect_uri": "http://www.google.com"
60
  }
61
  resp = requests.post(config.AUTH_URL, data=params)
62
- if resp.status_code != 200:
63
- print(f"❌ Auth Failed: {resp.text}")
64
- return None
65
  return {"Authorization": f"Zoho-oauthtoken {resp.json().get('access_token')}"}
66
- except Exception as e:
67
- print(f"❌ System Error: {e}")
68
- return None
69
 
70
  def resolve_id(ref_id):
71
- """Looks up Real ID from Registry. Returns original if not found."""
72
  return ID_REGISTRY.get(ref_id, ref_id)
73
 
74
  def register_id(ref_id, real_id):
75
- """Maps a placeholder (e.g., CL-001) to a real ID (e.g., 4000234)"""
76
- if ref_id and real_id:
77
- ID_REGISTRY[ref_id] = real_id
78
 
79
  def get_search_param(entity_key):
80
- """Returns the unique field used to check for duplicates"""
81
  mapping = {
82
  "contacts": "contact_name",
83
  "items": "name",
84
  "invoices": "invoice_number",
85
- "estimates": "estimate_number",
86
- "projects": "project_name",
87
- "taxes": "tax_name",
88
- "customer_payments": "payment_number",
89
- "credit_notes": "creditnote_number"
90
  }
91
  return mapping.get(entity_key)
92
 
93
  # =====================================================
94
- # 3. SMART SYNC ENGINE (The Core Logic)
95
  # =====================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
 
97
  def execute_sync(entity_key, payload, headers):
98
  """
99
- Universal Handler:
100
- 1. Resolves Dependencies (swaps IDs).
101
- 2. Checks for Duplicates (Fetch).
102
- 3. Creates if missing (Post).
103
  """
104
- # A. PREPARE PAYLOAD & CONTEXT
105
  clean_payload = payload.copy()
106
- ref_id = clean_payload.get("ref_id") # The placeholder ID from JSON
107
  if "ref_id" in clean_payload: del clean_payload["ref_id"]
108
 
109
- # B. RESOLVE DEPENDENCIES (Swap all _id fields)
110
- for key, val in clean_payload.items():
111
- if key.endswith("_id") or key.endswith("_ref"):
112
- clean_payload[key] = resolve_id(val)
113
-
114
- # C. CONSTRUCT URL (Handle Dynamic Routes)
115
- route_template = API_ROUTES.get(entity_key, entity_key)
116
- url_path = route_template
117
-
118
- # If route has {variable}, fill it from payload
119
- if "{" in route_template:
120
- try:
121
- var_name = route_template.split("{")[1].split("}")[0] # e.g., project_id
122
- var_val = resolve_id(clean_payload.get(var_name))
123
-
124
- if not var_val: return None, f"Missing Context: {var_name}"
125
-
126
- url_path = route_template.replace(f"{{{var_name}}}", str(var_val))
127
- # Optional: Remove context ID from body if API complains (Zoho usually ignores)
128
- except:
129
- return None, "URL Builder Failed"
130
-
131
- full_url = f"{config.API_BASE}/{url_path}?organization_id={config.ORGANIZATION_ID}"
132
 
133
- # D. FETCH (Duplicate Check)
134
  search_field = get_search_param(entity_key)
135
  if search_field and search_field in clean_payload:
136
- search_val = clean_payload[search_field]
137
-
138
- # Zoho Search Param Logic
139
- api_filter = f"{search_field}_contains"
140
- if entity_key == "invoices": api_filter = "invoice_number"
141
-
 
 
 
 
142
  try:
143
- # Quick Search
144
- res = requests.get(full_url, headers=headers, params={api_filter: search_val})
145
- if res.status_code == 200:
146
- # Extract List
147
- root_key = url_path.split("/")[-1] # e.g., contacts
148
- existing_items = res.json().get(root_key, [])
149
- for item in existing_items:
150
- if item.get(search_field) == search_val:
151
- # Found exact match!
152
- real_id = item.get(f"{root_key.rstrip('s')}_id") or item.get(f"{root_key}_id")
153
- if real_id:
154
- if ref_id: register_id(ref_id, real_id)
155
- return real_id, "Existing"
156
- except: pass
157
 
158
- # E. CREATE (Post)
 
159
  try:
160
- resp = requests.post(full_url, headers=headers, json=clean_payload)
161
 
 
162
  if resp.status_code in [200, 201]:
163
  data = resp.json()
164
- # Heuristic to find ID in response
165
- # Endpoint 'contacts' -> Response 'contact' -> Field 'contact_id'
166
- res_key = url_path.split("/")[-1].rstrip('s')
167
  if entity_key == "expense_categories": res_key = "expense_category"
168
 
169
  new_id = data.get(res_key, {}).get(f"{res_key}_id")
170
-
171
  if new_id:
172
  if ref_id: register_id(ref_id, new_id)
173
  return new_id, "Created"
174
-
175
- # Handle Specific Zoho Errors
176
  if resp.json().get("code") == 3062:
177
- return None, "Duplicate (API Rejected)"
178
-
 
 
 
 
 
 
179
  return None, f"API Error: {resp.text}"
180
-
181
  except Exception as e:
182
- return None, f"Exception: {e}"
183
 
184
  # =====================================================
185
- # 4. ORCHESTRATOR (Parallel Dispatcher)
186
  # =====================================================
187
-
188
  def process_stage_parallel(entity_key, items, headers):
189
- """Runs a single stage (e.g., 'contacts') in parallel threads"""
190
  if not items: return []
191
-
192
  results = []
193
- print(f"⚡ Processing {len(items)} {entity_key} (Parallel)...")
194
 
195
- with ThreadPoolExecutor(max_workers=5) as executor:
196
- # Map futures to items
197
  future_map = {executor.submit(execute_sync, entity_key, item, headers): item for item in items}
198
-
199
  for future in as_completed(future_map):
200
- r_id, status = future.result()
201
- if r_id:
202
- results.append(f"✔ {entity_key}: {status}")
203
- else:
204
- results.append(f"❌ {entity_key} Failed: {status}")
205
-
206
  return results
207
 
208
  def dispatcher(full_data):
209
  headers = get_headers()
210
  if not headers: return "Auth Failed"
 
211
 
212
- report = ["🚀 STARTING PARALLEL ORCHESTRATION..."]
213
-
214
- # STAGE DEFINITIONS (Strict Dependency Order)
215
- # We must finish Stage 1 before starting Stage 2
216
  stages = [
217
- # Stage 1: Metadata (No dependencies)
218
- ["taxes", "expense_categories", "price_lists"],
219
-
220
- # Stage 2: Core Entities
221
- ["contacts", "items"],
222
-
223
- # Stage 3: Sub-Entities & Parents
224
- ["contact_persons", "projects"],
225
-
226
- # Stage 4: Project Operations
227
- ["tasks", "time_entries"],
228
-
229
- # Stage 5: Sales Transactions
230
- ["estimates", "retainer_invoices"],
231
-
232
- # Stage 6: Final Invoices & Credits
233
  ["invoices", "recurring_invoices", "credit_notes"],
234
-
235
- # Stage 7: Expenses
236
- ["expenses", "recurring_expenses"],
237
-
238
- # Stage 8: Settlements
239
- ["customer_payments"]
240
  ]
241
 
242
  for stage in stages:
243
  for entity in stage:
244
- if entity in full_data:
245
- logs = process_stage_parallel(entity, full_data[entity], headers)
 
 
 
 
 
246
  report.extend(logs)
247
 
248
  return "\n".join(report)
249
 
250
  # =====================================================
251
- # 5. LEGACY SUPPORT (PDF Agent)
252
  # =====================================================
253
  def push_invoice(payload):
254
- """Wrapper for the PDF Agent Tab"""
255
  headers = get_headers()
 
256
 
257
- # 1. Ensure Customer
258
- cust_data = {"contact_name": payload.get("vendor_name"), "contact_type": "customer"}
259
- cid, _ = execute_sync("contacts", cust_data, headers)
260
- if not cid: return "Customer Creation Failed"
 
 
 
 
261
 
262
- # 2. Create Invoice
 
 
263
  inv_data = {
264
  "customer_id": cid,
265
  "date": normalize_date(payload.get("date")),
266
  "line_items": payload.get("line_items", [{"name": "Service", "rate": 0, "quantity": 1}]),
267
  "status": "draft"
268
  }
269
- iid, status = execute_sync("invoices", inv_data, headers)
270
 
271
- if iid: return f"✅ Invoice Created: {iid} ({status})"
272
- return "❌ Invoice Creation Failed"
 
 
 
6
  from concurrent.futures import ThreadPoolExecutor, as_completed
7
 
8
  # =====================================================
9
+ # 1. API ROUTE MAPPING
10
  # =====================================================
 
 
11
  API_ROUTES = {
 
12
  "taxes": "settings/taxes",
13
  "expense_categories": "expensecategories",
14
  "price_lists": "pricebooks",
 
 
15
  "contacts": "contacts",
16
+ "contact_persons": "contacts/contactpersons",
17
  "items": "items",
 
 
18
  "projects": "projects",
19
+ "tasks": "projects/{project_id}/tasks",
20
  "time_entries": "projects/timeentries",
 
 
21
  "estimates": "estimates",
22
  "retainer_invoices": "retainerinvoices",
23
  "invoices": "invoices",
24
  "recurring_invoices": "recurringinvoices",
25
  "credit_notes": "creditnotes",
 
 
26
  "expenses": "expenses",
27
  "recurring_expenses": "recurringexpenses",
 
 
28
  "customer_payments": "customerpayments"
29
  }
30
 
 
31
  ID_REGISTRY = {}
32
 
33
  # =====================================================
34
  # 2. CORE UTILITIES
35
  # =====================================================
 
36
  def get_headers():
 
37
  try:
38
  params = {
39
  "refresh_token": config.REFRESH_TOKEN,
 
43
  "redirect_uri": "http://www.google.com"
44
  }
45
  resp = requests.post(config.AUTH_URL, data=params)
46
+ if resp.status_code != 200: return None
 
 
47
  return {"Authorization": f"Zoho-oauthtoken {resp.json().get('access_token')}"}
48
+ except: return None
 
 
49
 
50
  def resolve_id(ref_id):
 
51
  return ID_REGISTRY.get(ref_id, ref_id)
52
 
53
  def register_id(ref_id, real_id):
54
+ if ref_id and real_id: ID_REGISTRY[ref_id] = real_id
 
 
55
 
56
  def get_search_param(entity_key):
57
+ """Mapping for Search Filters"""
58
  mapping = {
59
  "contacts": "contact_name",
60
  "items": "name",
61
  "invoices": "invoice_number",
62
+ "projects": "project_name"
 
 
 
 
63
  }
64
  return mapping.get(entity_key)
65
 
66
  # =====================================================
67
+ # 3. SMART SYNC ENGINE (Robust)
68
  # =====================================================
69
+ def execute_search(entity_key, search_val, headers):
70
+ """Helper to find ID by Name/Number"""
71
+ if not search_val: return None
72
+
73
+ endpoint = API_ROUTES.get(entity_key, entity_key)
74
+ url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
75
+
76
+ # Filter Keys
77
+ search_field = get_search_param(entity_key)
78
+ filter_key = f"{search_field}_contains"
79
+ if entity_key == "invoices": filter_key = "invoice_number"
80
+
81
+ try:
82
+ res = requests.get(url, headers=headers, params={filter_key: search_val})
83
+ if res.status_code == 200:
84
+ root_key = endpoint.split("/")[-1]
85
+ items = res.json().get(root_key, [])
86
+ for item in items:
87
+ # Loose matching
88
+ if search_val.lower() in str(item.get(search_field, "")).lower():
89
+ # ID Extraction Logic
90
+ return item.get(f"{root_key.rstrip('s')}_id") or item.get(f"{root_key}_id")
91
+ except: pass
92
+ return None
93
 
94
  def execute_sync(entity_key, payload, headers):
95
  """
96
+ 1. Search -> 2. Create -> 3. Retry on Duplicate
 
 
 
97
  """
98
+ # A. DEPENDENCY RESOLUTION
99
  clean_payload = payload.copy()
100
+ ref_id = clean_payload.get("ref_id")
101
  if "ref_id" in clean_payload: del clean_payload["ref_id"]
102
 
103
+ for k, v in clean_payload.items():
104
+ if k.endswith("_id") or k.endswith("_ref"):
105
+ clean_payload[k] = resolve_id(v)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ # B. INITIAL SEARCH (Prevent Duplicates)
108
  search_field = get_search_param(entity_key)
109
  if search_field and search_field in clean_payload:
110
+ existing_id = execute_search(entity_key, clean_payload[search_field], headers)
111
+ if existing_id:
112
+ if ref_id: register_id(ref_id, existing_id)
113
+ return existing_id, "Existing"
114
+
115
+ # C. CREATE ATTEMPT
116
+ route = API_ROUTES.get(entity_key, entity_key)
117
+
118
+ # Dynamic URL handling (e.g. tasks inside projects)
119
+ if "{" in route:
120
  try:
121
+ var = route.split("{")[1].split("}")[0]
122
+ val = resolve_id(clean_payload.get(var))
123
+ if not val: return None, f"Missing {var}"
124
+ route = route.replace(f"{{{var}}}", str(val))
125
+ except: return None, "URL Error"
 
 
 
 
 
 
 
 
 
126
 
127
+ url = f"{config.API_BASE}/{route}?organization_id={config.ORGANIZATION_ID}"
128
+
129
  try:
130
+ resp = requests.post(url, headers=headers, json=clean_payload)
131
 
132
+ # SUCCESS
133
  if resp.status_code in [200, 201]:
134
  data = resp.json()
135
+ res_key = route.split("/")[-1].rstrip('s')
 
 
136
  if entity_key == "expense_categories": res_key = "expense_category"
137
 
138
  new_id = data.get(res_key, {}).get(f"{res_key}_id")
 
139
  if new_id:
140
  if ref_id: register_id(ref_id, new_id)
141
  return new_id, "Created"
142
+
143
+ # RECOVERY: DUPLICATE ERROR (Code 3062)
144
  if resp.json().get("code") == 3062:
145
+ print(f"⚠️ Duplicate detected for {clean_payload.get(search_field)}. Retrying Fetch...")
146
+ # Force search again (The API says it exists, so search MUST find it)
147
+ retry_id = execute_search(entity_key, clean_payload.get(search_field), headers)
148
+ if retry_id:
149
+ if ref_id: register_id(ref_id, retry_id)
150
+ return retry_id, "Recovered"
151
+ return None, "Duplicate - Retrieval Failed"
152
+
153
  return None, f"API Error: {resp.text}"
154
+
155
  except Exception as e:
156
+ return None, str(e)
157
 
158
  # =====================================================
159
+ # 4. ORCHESTRATOR (Parallel)
160
  # =====================================================
 
161
  def process_stage_parallel(entity_key, items, headers):
 
162
  if not items: return []
 
163
  results = []
164
+ print(f"⚡ Syncing {len(items)} {entity_key}...")
165
 
166
+ with ThreadPoolExecutor(max_workers=4) as executor:
 
167
  future_map = {executor.submit(execute_sync, entity_key, item, headers): item for item in items}
 
168
  for future in as_completed(future_map):
169
+ rid, status = future.result()
170
+ if rid: results.append(f"✔ {entity_key}: {status}")
171
+ else: results.append(f"❌ {entity_key}: {status}")
 
 
 
172
  return results
173
 
174
  def dispatcher(full_data):
175
  headers = get_headers()
176
  if not headers: return "Auth Failed"
177
+ report = []
178
 
179
+ # Strict Order
 
 
 
180
  stages = [
181
+ ["taxes", "expense_categories", "items", "price_lists"],
182
+ ["contacts"],
183
+ ["projects", "contact_persons"],
184
+ ["tasks", "time_entries", "estimates", "retainer_invoices"],
 
 
 
 
 
 
 
 
 
 
 
 
185
  ["invoices", "recurring_invoices", "credit_notes"],
186
+ ["customer_payments", "expenses"]
 
 
 
 
 
187
  ]
188
 
189
  for stage in stages:
190
  for entity in stage:
191
+ # Handle Aliases (clients -> contacts)
192
+ data_key = entity
193
+ if entity == "contacts" and "clients" in full_data: data_key = "clients"
194
+ if entity == "customer_payments" and "payments_received" in full_data: data_key = "payments_received"
195
+
196
+ if data_key in full_data:
197
+ logs = process_stage_parallel(entity, full_data[data_key], headers)
198
  report.extend(logs)
199
 
200
  return "\n".join(report)
201
 
202
  # =====================================================
203
+ # 5. PDF AGENT WRAPPER (Fixed)
204
  # =====================================================
205
  def push_invoice(payload):
 
206
  headers = get_headers()
207
+ if not headers: return "Auth Failed"
208
 
209
+ # 1. Validate Name
210
+ v_name = payload.get("vendor_name")
211
+ if not v_name or str(v_name).lower() == "unknown":
212
+ v_name = "MCP Customer" # Fallback name
213
+
214
+ # 2. Create/Find Contact
215
+ c_data = {"contact_name": v_name, "contact_type": "customer"}
216
+ cid, c_msg = execute_sync("contacts", c_data, headers)
217
 
218
+ if not cid: return f"❌ Customer Failed: {c_msg}"
219
+
220
+ # 3. Create Invoice
221
  inv_data = {
222
  "customer_id": cid,
223
  "date": normalize_date(payload.get("date")),
224
  "line_items": payload.get("line_items", [{"name": "Service", "rate": 0, "quantity": 1}]),
225
  "status": "draft"
226
  }
 
227
 
228
+ iid, i_msg = execute_sync("invoices", inv_data, headers)
229
+
230
+ if iid: return f"✅ Invoice Created: {iid} ({i_msg})"
231
+ return f"❌ Invoice Failed: {i_msg}"