vachaspathi commited on
Commit
4e1dcb4
Β·
verified Β·
1 Parent(s): 45ba40d

Update zoho_client.py

Browse files
Files changed (1) hide show
  1. zoho_client.py +283 -74
zoho_client.py CHANGED
@@ -2,6 +2,7 @@ import requests
2
  import json
3
  import config
4
  from utils import normalize_date
 
5
 
6
  # =====================================================
7
  # 1. CORE AUTHENTICATION
@@ -25,13 +26,282 @@ def get_headers():
25
  return None
26
 
27
  # =====================================================
28
- # 2. PDF AGENT LOGIC (The Missing Part)
29
  # =====================================================
30
- def find_or_create_customer(name, headers):
31
- if not name or len(str(name)) < 2: name = "MCP Customer"
32
- search_url = f"{config.API_BASE}/contacts"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- # A. Search
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
  params = {"organization_id": config.ORGANIZATION_ID, "contact_name_contains": name}
37
  resp = requests.get(search_url, headers=headers, params=params)
@@ -39,89 +309,28 @@ def find_or_create_customer(name, headers):
39
  if contacts: return contacts[0]["contact_id"], "Existing"
40
  except: pass
41
 
42
- # B. Create
43
  create_payload = {"contact_name": name, "contact_type": "customer"}
44
  resp = requests.post(search_url, headers=headers, params={"organization_id": config.ORGANIZATION_ID}, json=create_payload)
45
-
46
- if resp.status_code == 201:
47
- return resp.json().get("contact", {}).get("contact_id"), "Created New"
48
- elif resp.json().get("code") == 3062:
49
- # If duplicate, search again recursively
50
- return find_or_create_customer(name, headers)
51
-
52
- return None, f"Error: {resp.text}"
53
 
54
  def push_invoice(payload):
55
- """
56
- REQUIRED function for app.py (PDF Agent Tab).
57
- """
58
  headers = get_headers()
59
  if not headers: return "Auth Failed"
60
 
61
- # 1. Resolve Customer
62
- cid, c_status = find_or_create_customer(payload.get("vendor_name"), headers)
63
- if not cid: return f"❌ Customer Error: {c_status}"
64
 
65
- # 2. Construct Payload
66
  zoho_json = {
67
  "customer_id": cid,
68
  "date": normalize_date(payload.get("date")),
69
- "line_items": payload.get("line_items", [{"name": "Services", "rate": 0, "quantity": 1}]),
70
  "status": "draft"
71
  }
72
 
73
- # 3. Push to Zoho
74
  url = f"{config.API_BASE}/invoices?organization_id={config.ORGANIZATION_ID}"
75
  resp = requests.post(url, headers=headers, json=zoho_json)
76
-
77
  if resp.status_code == 201:
78
- inv = resp.json().get("invoice", {})
79
- link = f"https://books.zoho.in/app/{config.ORGANIZATION_ID}#/invoices/{inv.get('invoice_id')}"
80
- return f"βœ… SUCCESS! Invoice #{inv.get('invoice_number')} Created.\nLink: {link}"
81
-
82
- return f"❌ Zoho API Error: {resp.text}"
83
-
84
- # =====================================================
85
- # 3. BATCH JSON LOGIC (The New Part)
86
- # =====================================================
87
- def generic_post(endpoint, payload, headers):
88
- url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
89
- try:
90
- resp = requests.post(url, headers=headers, json=payload)
91
- if resp.status_code in [200, 201]:
92
- print(f"βœ… Created in {endpoint}")
93
- return True
94
- elif resp.json().get("code") in [3062, 3002]:
95
- print(f"⚠️ {endpoint} Duplicate. Skipping.")
96
- return True
97
- else:
98
- print(f"❌ Error {endpoint}: {resp.text}")
99
- return False
100
- except: return False
101
-
102
- def dispatcher(full_json_data):
103
- headers = get_headers()
104
- if not headers: return "Auth Failed"
105
-
106
- report = []
107
-
108
- # Define execution order
109
- entities = [
110
- ("contacts", "contacts"),
111
- ("items", "items"),
112
- ("invoices", "invoices"),
113
- ("recurring_invoices", "recurringinvoices"),
114
- ("credit_notes", "creditnotes"),
115
- ("payments", "customerpayments")
116
- ]
117
-
118
- for json_key, endpoint in entities:
119
- if json_key in full_json_data:
120
- count = 0
121
- print(f"Processing {json_key}...")
122
- for item in full_json_data[json_key]:
123
- if generic_post(endpoint, item, headers):
124
- count += 1
125
- report.append(f"Processed {count} {json_key}")
126
-
127
- return "\n".join(report)
 
2
  import json
3
  import config
4
  from utils import normalize_date
5
+ import time
6
 
7
  # =====================================================
8
  # 1. CORE AUTHENTICATION
 
26
  return None
27
 
28
  # =====================================================
29
+ # 2. ID MAPPING SYSTEM (The Brain of Batch Sync)
30
  # =====================================================
31
+ # Stores mapping from JSON Ref IDs (e.g., "CL-001") to Real Zoho IDs (e.g., "4000001")
32
+ ID_REGISTRY = {}
33
+
34
+ def register_id(ref_id, real_id):
35
+ """Saves the link between JSON ID and Zoho ID"""
36
+ if ref_id and real_id:
37
+ ID_REGISTRY[ref_id] = real_id
38
+ # print(f" πŸ”— Mapped {ref_id} -> {real_id}")
39
+
40
+ def resolve_id(ref_id):
41
+ """Looks up the Real Zoho ID. Returns ref_id if not found (fallback)."""
42
+ return ID_REGISTRY.get(ref_id, ref_id)
43
+
44
+ # =====================================================
45
+ # 3. GENERIC API HANDLER
46
+ # =====================================================
47
+ def zoho_post(endpoint, payload):
48
+ headers = get_headers()
49
+ if not headers: return None, "Auth Failed"
50
+
51
+ url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
52
+
53
+ # Special handling for 'payments_received' endpoint quirk
54
+ if endpoint == "payments_received": endpoint = "customerpayments"
55
 
56
+ try:
57
+ resp = requests.post(url, headers=headers, json=payload)
58
+
59
+ # Success Codes (200 OK, 201 Created)
60
+ if resp.status_code in [200, 201]:
61
+ data = resp.json()
62
+ # Determine the singular key name (e.g., contacts -> contact)
63
+ # Zoho API naming convention is usually singular key in response
64
+ key_map = {
65
+ "contacts": "contact",
66
+ "items": "item",
67
+ "estimates": "estimate",
68
+ "invoices": "invoice",
69
+ "recurring_invoices": "recurring_invoice", # Check API docs, usually recurring_invoice
70
+ "recurringinvoices": "recurring_invoice",
71
+ "delivery_challans": "delivery_challan",
72
+ "deliverychallans": "delivery_challan",
73
+ "credit_notes": "creditnote",
74
+ "creditnotes": "creditnote",
75
+ "customerpayments": "payment",
76
+ "expenses": "expense"
77
+ }
78
+
79
+ # Handle variations in endpoint naming vs response naming
80
+ clean_end = endpoint.replace("_", "").lower() # delivery_challans -> deliverychallans
81
+ # Try to find the matching key in response
82
+ res_key = key_map.get(endpoint, key_map.get(clean_end, "message"))
83
+
84
+ obj = data.get(res_key, {})
85
+ # ID field is usually {key}_id, e.g., contact_id
86
+ new_id = obj.get(f"{res_key}_id")
87
+
88
+ return new_id, "Success"
89
+
90
+ # Handle Duplicates (Code 3062, 3002)
91
+ elif resp.json().get("code") in [3062, 3002]:
92
+ return None, "Duplicate"
93
+
94
+ else:
95
+ return None, f"Error: {resp.text}"
96
+ except Exception as e:
97
+ return None, str(e)
98
+
99
+ # =====================================================
100
+ # 4. ENTITY TRANSFORMERS (Prepare JSON for Zoho)
101
+ # =====================================================
102
+
103
+ def process_contact(item):
104
+ """
105
+ Input: JSON Item from 'clients' list
106
+ Output: Zoho API Payload + Ref ID to Map
107
+ """
108
+ # Extract the inner 'contact' object if wrapped
109
+ data = item.get("contact", item)
110
+ ref_id = item.get("client_id") # Capture the CL-001 ID
111
+
112
+ payload = {
113
+ "contact_name": data.get("contact_name"),
114
+ "company_name": data.get("company_name", ""),
115
+ "contact_type": "customer", # Defaulting to customer for this dataset
116
+ "billing_address": data.get("billing_address", {}),
117
+ "shipping_address": data.get("shipping_address", {}),
118
+ "email": data.get("email", ""),
119
+ "phone": data.get("phone", "")
120
+ }
121
+ return payload, ref_id
122
+
123
+ def process_transaction(item, type_key):
124
+ """
125
+ Handles Invoices, Quotes, Credit Notes
126
+ Swaps customer_ref -> customer_id
127
+ """
128
+ payload = item.copy()
129
+
130
+ # 1. SWAP CUSTOMER ID
131
+ if "customer_ref" in payload:
132
+ real_cid = resolve_id(payload["customer_ref"])
133
+ payload["customer_id"] = real_cid
134
+ del payload["customer_ref"] # Remove invalid key
135
+
136
+ # 2. SWAP ITEM IDs (Optional - if line items use refs)
137
+ # (Assuming line items in JSON use names/rates which Zoho accepts directly)
138
+
139
+ # 3. Capture Ref ID for Mapping (e.g., invoice_id mapping for Payments)
140
+ # The JSON uses different ID keys per type
141
+ ref_key_map = {
142
+ "invoices": "invoice_id",
143
+ "quotes": "estimate_id",
144
+ "credit_notes": "credit_note_id"
145
+ }
146
+ ref_id = payload.get(ref_key_map.get(type_key, "unknown_id"))
147
+
148
+ # Cleanup keys Zoho doesn't want in POST
149
+ for k in [ref_key_map.get(type_key), "generated_on"]:
150
+ if k in payload: del payload[k]
151
+
152
+ return payload, ref_id
153
+
154
+ def process_payment(item):
155
+ """
156
+ Handles Payments. Needs to link to specific Invoices.
157
+ """
158
+ payload = item.copy()
159
+
160
+ # Swap Customer ID
161
+ if "customer_ref" in payload:
162
+ payload["customer_id"] = resolve_id(payload["customer_ref"])
163
+ del payload["customer_ref"]
164
+
165
+ # Swap Invoice IDs in 'invoices' list
166
+ clean_invoices_list = []
167
+ for inv in payload.get("invoices", []):
168
+ # The JSON says 'applied_to_invoice': 'INV-001'.
169
+ # But strictly, Zoho Payments need 'invoices': [{'invoice_id': 'REAL_ID', 'amount_applied': 100}]
170
+
171
+ # Look for 'applied_to_invoice' at top level or inside list?
172
+ # The user JSON has 'applied_to_invoice' at top level AND 'invoices' list.
173
+ # Let's trust the top level logic if simple
174
+
175
+ ref_inv_id = payload.get("applied_to_invoice") # e.g. INV-00101
176
+ if ref_inv_id:
177
+ real_inv_id = resolve_id(ref_inv_id)
178
+ # Construct the list Zoho wants
179
+ clean_invoices_list.append({
180
+ "invoice_id": real_inv_id,
181
+ "amount_applied": payload.get("amount")
182
+ })
183
+
184
+ # Remove non-API fields
185
+ if "applied_to_invoice" in payload: del payload["applied_to_invoice"]
186
+ if "invoices" in payload: del payload["invoices"] # Replace with ours
187
+ if "payment_id" in payload: del payload["payment_id"]
188
+
189
+ if clean_invoices_list:
190
+ payload["invoices"] = clean_invoices_list
191
+
192
+ return payload, None
193
+
194
+ # =====================================================
195
+ # 5. MAIN DISPATCHER
196
+ # =====================================================
197
+ def dispatcher(json_data):
198
+ report = ["πŸš€ Starting Batch Sync..."]
199
+
200
+ # 1. CONTACTS (Clients)
201
+ # The JSON key is "clients" or "contacts" - supporting both
202
+ contacts_data = json_data.get("clients", json_data.get("contacts", []))
203
+ if contacts_data:
204
+ print("Processing Contacts...")
205
+ success = 0
206
+ for c in contacts_data:
207
+ payload, ref_id = process_contact(c)
208
+ real_id, status = zoho_post("contacts", payload)
209
+ if real_id:
210
+ register_id(ref_id, real_id)
211
+ success += 1
212
+ report.append(f"βœ” Contacts: {success}/{len(contacts_data)}")
213
+
214
+ # 2. ITEMS
215
+ if "items" in json_data:
216
+ print("Processing Items...")
217
+ success = 0
218
+ for i in json_data["items"]:
219
+ # Simple pass-through usually works for items
220
+ real_id, status = zoho_post("items", i)
221
+ success += 1 if real_id else 0
222
+ report.append(f"βœ” Items: {success}/{len(json_data['items'])}")
223
+
224
+ # 3. QUOTES (Estimates)
225
+ if "quotes" in json_data:
226
+ print("Processing Quotes...")
227
+ success = 0
228
+ for q in json_data["quotes"]:
229
+ payload, ref_id = process_transaction(q, "quotes")
230
+ real_id, status = zoho_post("estimates", payload)
231
+ if real_id: register_id(ref_id, real_id)
232
+ success += 1 if real_id else 0
233
+ report.append(f"βœ” Quotes: {success}/{len(json_data['quotes'])}")
234
+
235
+ # 4. INVOICES
236
+ if "invoices" in json_data:
237
+ print("Processing Invoices...")
238
+ success = 0
239
+ for inv in json_data["invoices"]:
240
+ payload, ref_id = process_transaction(inv, "invoices")
241
+ real_id, status = zoho_post("invoices", payload)
242
+ if real_id: register_id(ref_id, real_id)
243
+ success += 1 if real_id else 0
244
+ report.append(f"βœ” Invoices: {success}/{len(json_data['invoices'])}")
245
+
246
+ # 5. DELIVERY CHALLANS
247
+ if "delivery_challans" in json_data:
248
+ print("Processing Challans...")
249
+ success = 0
250
+ for dc in json_data["delivery_challans"]:
251
+ payload, _ = process_transaction(dc, "delivery_challans")
252
+ real_id, _ = zoho_post("deliverychallans", payload)
253
+ success += 1 if real_id else 0
254
+ report.append(f"βœ” Challans: {success}/{len(json_data['delivery_challans'])}")
255
+
256
+ # 6. CREDIT NOTES
257
+ if "credit_notes" in json_data:
258
+ print("Processing Credit Notes...")
259
+ success = 0
260
+ for cn in json_data["credit_notes"]:
261
+ payload, ref_id = process_transaction(cn, "credit_notes")
262
+ real_id, _ = zoho_post("creditnotes", payload)
263
+ if real_id: register_id(ref_id, real_id)
264
+ success += 1 if real_id else 0
265
+ report.append(f"βœ” Credit Notes: {success}/{len(json_data['credit_notes'])}")
266
+
267
+ # 7. PAYMENTS (Depend on Invoices)
268
+ if "payments_received" in json_data:
269
+ print("Processing Payments...")
270
+ success = 0
271
+ for p in json_data["payments_received"]:
272
+ payload, _ = process_payment(p)
273
+ real_id, _ = zoho_post("customerpayments", payload)
274
+ success += 1 if real_id else 0
275
+ report.append(f"βœ” Payments: {success}/{len(json_data['payments_received'])}")
276
+
277
+ # 8. EXPENSES
278
+ if "expenses" in json_data:
279
+ print("Processing Expenses...")
280
+ success = 0
281
+ for exp in json_data["expenses"]:
282
+ payload = exp.copy()
283
+ # Swap client ref
284
+ if "client_ref" in payload:
285
+ payload["customer_id"] = resolve_id(payload["client_ref"])
286
+ del payload["client_ref"]
287
+ if "expense_id" in payload: del payload["expense_id"]
288
+
289
+ # Remove 'amounts' summary if present (Zoho calculates it)
290
+ if "amounts" in payload: del payload["amounts"]
291
+
292
+ real_id, _ = zoho_post("expenses", payload)
293
+ success += 1 if real_id else 0
294
+ report.append(f"βœ” Expenses: {success}/{len(json_data['expenses'])}")
295
+
296
+ return "\n".join(report)
297
+
298
+ # =====================================================
299
+ # 6. SINGLE INVOICE PUSHER (Legacy Support)
300
+ # =====================================================
301
+ def find_or_create_customer_simple(name, headers):
302
+ """Simple lookup for the PDF Agent"""
303
+ if not name: name = "MCP Customer"
304
+ search_url = f"{config.API_BASE}/contacts"
305
  try:
306
  params = {"organization_id": config.ORGANIZATION_ID, "contact_name_contains": name}
307
  resp = requests.get(search_url, headers=headers, params=params)
 
309
  if contacts: return contacts[0]["contact_id"], "Existing"
310
  except: pass
311
 
 
312
  create_payload = {"contact_name": name, "contact_type": "customer"}
313
  resp = requests.post(search_url, headers=headers, params={"organization_id": config.ORGANIZATION_ID}, json=create_payload)
314
+ if resp.status_code == 201: return resp.json().get("contact", {}).get("contact_id"), "Created"
315
+ return None, "Error"
 
 
 
 
 
 
316
 
317
  def push_invoice(payload):
318
+ """Used by the PDF Upload Tab"""
 
 
319
  headers = get_headers()
320
  if not headers: return "Auth Failed"
321
 
322
+ cid, status = find_or_create_customer_simple(payload.get("vendor_name"), headers)
323
+ if not cid: return "Customer Failed"
 
324
 
 
325
  zoho_json = {
326
  "customer_id": cid,
327
  "date": normalize_date(payload.get("date")),
328
+ "line_items": payload.get("line_items", [{"name": "Service", "rate": 0, "quantity": 1}]),
329
  "status": "draft"
330
  }
331
 
 
332
  url = f"{config.API_BASE}/invoices?organization_id={config.ORGANIZATION_ID}"
333
  resp = requests.post(url, headers=headers, json=zoho_json)
 
334
  if resp.status_code == 201:
335
+ return f"βœ… Created Invoice: {resp.json().get('invoice', {}).get('invoice_number')}"
336
+ return f"❌ Error: {resp.text}"