vachaspathi commited on
Commit
7e340fe
Β·
verified Β·
1 Parent(s): 39bc8a4

Update zoho_client.py

Browse files
Files changed (1) hide show
  1. 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. API ROUTE MAP (Based on your Documentation)
9
  # =====================================================
10
- ROUTE_MAP = {
11
- # Sales
12
- "invoice": "invoices",
13
- "estimate": "estimates",
14
- "credit_note": "creditnotes",
15
- "retainer_invoice": "retainerinvoices",
16
- "recurring_invoice": "recurringinvoices",
17
-
18
- # Purchases / Expenses
19
- "expense": "expenses",
20
- "recurring_expense": "recurringexpenses",
21
- "bill": "bills",
22
-
23
- # Core
24
- "contact": "contacts",
25
- "item": "items",
26
- "project": "projects"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  }
28
 
29
- ID_REGISTRY = {}
30
-
31
  # =====================================================
32
- # 2. UTILITIES
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. GENERIC CRUD ENGINE
68
  # =====================================================
69
- def execute_api_call(endpoint, payload, method="POST"):
70
- headers = get_headers()
71
- if not headers: return None, "Auth Failed"
72
-
73
- url = f"{config.API_BASE}/{endpoint}?organization_id={config.ORGANIZATION_ID}"
74
 
75
- try:
76
- if method == "POST":
77
- resp = requests.post(url, headers=headers, json=payload)
78
- elif method == "GET":
79
- resp = requests.get(url, headers=headers, params=payload)
80
-
81
- if resp.status_code in [200, 201]:
82
- data = resp.json()
83
- # Dynamic ID extraction
84
- # Endpoint 'invoices' -> Key 'invoice' -> Field 'invoice_id'
85
- res_key = endpoint.split("/")[-1].rstrip('s')
86
- obj = data.get(res_key, {})
87
- new_id = obj.get(f"{res_key}_id")
88
- return new_id, f"Success ({res_key} created)"
89
-
90
- if resp.json().get("code") == 3062:
91
- return None, "Duplicate Entry"
 
92
 
93
- return None, f"API Error: {resp.text}"
94
- except Exception as e:
95
- return None, str(e)
96
-
97
- # =====================================================
98
- # 4. DEPENDENCY HANDLERS
99
- # =====================================================
100
- def ensure_customer(name):
101
- """Finds or Creates a Contact (Required for Sales Docs)"""
102
- headers = get_headers()
103
- if not name: name = "MCP Customer"
104
-
105
- # Search
106
- search_url = f"{config.API_BASE}/contacts?organization_id={config.ORGANIZATION_ID}&contact_name_contains={name}"
107
- try:
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
- def ensure_expense_account():
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
- # 5. INTELLIGENT ROUTER (The "Brain")
133
  # =====================================================
134
- def route_and_execute(ai_output):
135
  """
136
- Takes the AI JSON {doc_type, data} and routes to the correct function.
137
  """
138
- doc_type = ai_output.get("doc_type", "unknown").lower()
139
- data = sanitize_payload(ai_output.get("data", {}))
140
 
141
- print(f"πŸ”„ Routing Document Type: {doc_type}")
 
142
 
143
- # --- ROUTE 1: SALES DOCUMENTS (Invoice, Estimate, Credit Note) ---
144
- if doc_type in ["invoice", "estimate", "credit_note", "retainer_invoice"]:
145
- endpoint = ROUTE_MAP.get(doc_type, "invoices")
146
-
147
- # Dependency: Customer
148
- cid = ensure_customer(data.get("vendor_name")) # AI usually calls it vendor_name for everything
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
- # --- ROUTE 2: EXPENSES ---
167
- elif doc_type in ["expense", "receipt"]:
168
- # Dependency: Account & Customer(Optional)
169
- acc_id = ensure_expense_account()
170
- cid = ensure_customer(data.get("vendor_name")) # Optional but good
171
 
172
- payload = {
173
- "date": normalize_date(data.get("date")),
174
- "amount": data.get("total", 0),
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
- obj_id, msg = execute_api_call("expenses", payload)
182
- if obj_id: return f"βœ… Expense Logged! ID: {obj_id}"
183
- return f"❌ Expense Failed: {msg}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
 
185
- # --- ROUTE 3: CONTACTS ---
186
- elif doc_type == "contact":
187
- payload = {
188
- "contact_name": data.get("vendor_name") or data.get("contact_name"),
189
- "contact_type": "customer"
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
- # --- FALLBACK ---
196
- else:
197
- return f"⚠️ Unknown Document Type: '{doc_type}'. Logic not implemented."
198
 
199
  # =====================================================
200
- # 6. DISPATCHER (For Batch JSON)
201
  # =====================================================
202
- def dispatcher(full_data):
203
- # Keep existing batch logic or reuse execute_api_call loop
204
- # (Simplified for brevity - uses the generic caller)
205
- report = []
206
- headers = get_headers() # Warm up auth
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
207
 
208
- order = ["contacts", "items", "estimates", "invoices", "expenses"]
 
209
 
210
- for key in order:
211
- if key in full_data:
212
- endpoint = ROUTE_MAP.get(key.rstrip('s'), key)
213
- for item in full_data[key]:
214
- # Basic post logic
215
- execute_api_call(endpoint, item)
216
- report.append(f"Processed {key}")
 
 
 
217
 
218
- return "\n".join(report)
 
 
 
 
 
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}"