-
Notifications
You must be signed in to change notification settings - Fork 2
/
sugarcrm.py
381 lines (296 loc) · 11.6 KB
/
sugarcrm.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# SugarCRM
# --------
# Python client for SugarCRM API.
#
# Author: ryanss <[email protected]>
# Website: https://github.com/ryanss/sugarcrm
# License: MIT (see LICENSE file)
# Version: 0.1.2 (February 4, 2016)
__version__ = '0.1.2'
import base64
import hashlib
import json
import os
import sys
import requests
class Session:
def __init__(self, url, username, password, app="Python", lang="en_us",
verify=True):
self.url = url
self.username = username
self.application = app
self.language = lang
self.verify = verify
result = self.login(username, password)
self.session_id = result['id']
def _request(self, method, params):
data = {
'method': method,
'input_type': "JSON",
'response_type': "JSON",
'rest_data': json.dumps(params),
}
r = requests.post(self.url, data=data, verify=self.verify)
if r.status_code == 200:
return json.loads(r.text.replace("'", "'"))
raise SugarError("SugarCRM API _request returned status code %d (%s)"
% (r.status_code, r.reason))
def get_available_modules(self, filter="default"):
"""Retrieves a list of available modules in the system."""
data = [self.session_id, filter]
results = self._request('get_available_modules', data)['modules']
ret = []
for module in results:
m = Module()
for key, value in module.items():
setattr(m, key, value)
ret.append(m)
return ret
def get_document_revision(self):
raise SugarError("Method not implemented yet.")
def get_entry(self, module, id, links=dict(), track_view=False):
"""Retrieves a single object based on object ID."""
relationships = []
for key, value in links.items():
relationships.append({'name': key.lower(), 'value': value})
data = [self.session_id, module, id, [], relationships, track_view]
result = self._request('get_entry', data)
obj = SugarObject(module=module)
obj_data = result['entry_list'][0]['name_value_list']
for key in obj_data:
if isinstance(key, dict):
# No object found
return None
setattr(obj, key, obj_data[key]['value'])
if result['relationship_list']:
for m in result['relationship_list'][0]:
setattr(obj, m['name'], [])
for record in m['records']:
robj = SugarObject(module=m['name'])
for key in record:
setattr(robj, key, record[key]['value'])
getattr(obj, m['name']).append(robj)
return obj
def get_entries(self, module, ids, track_view=False):
"""Retrieves a list of objects based on specified object IDs."""
if not isinstance(ids, list):
ids = [ids, ]
data = [self.session_id, module, ids, [], [], track_view]
results = self._request('get_entries', data)['entry_list']
ret = []
for result in results:
obj = SugarObject(module=module)
for key in result['name_value_list']:
if isinstance(key, dict):
# No objects found
return []
setattr(obj, key, result['name_value_list'][key]['value'])
ret.append(obj)
return ret
def get_entries_count(self, q, deleted=False):
"""Retrieves a count of beans based on query specifications."""
data = [self.session_id, q.module, q.query, int(deleted)]
return int(self._request('get_entries_count', data)['result_count'])
def get_entry_list(self, q, fields=(), links=dict(), order_by="",
max_results=0, offset=0,
deleted=False, favorites=False):
"""Retrieves a list of objects based on query specifications."""
relationships = []
for key, value in links.items():
relationships.append({'name': key.lower(), 'value': value})
data = [self.session_id, q.module, q.query, order_by, offset, fields,
relationships, max_results, int(deleted), int(favorites)]
results = self._request('get_entry_list', data)
entry_list = results['entry_list']
ret = []
for i, result in enumerate(entry_list):
obj = SugarObject(module=q.module, __class__=q.__class__)
for key in result['name_value_list']:
setattr(obj, key, result['name_value_list'][key]['value'])
if results['relationship_list']:
for m in results['relationship_list'][i]['link_list']:
setattr(obj, m['name'], [])
for record in m['records']:
robj = SugarObject(module=m['name'])
for k in record['link_value']:
setattr(robj, k, record['link_value'][k]['value'])
getattr(obj, m['name']).append(robj)
ret.append(obj)
return ret
def get_language_definition(self):
raise SugarError("Method not implemented yet.")
def get_last_viewed(self):
raise SugarError("Method not implemented yet.")
def get_modified_relationships(self):
raise SugarError("Method not implemented yet.")
def get_module_fields(self):
raise SugarError("Method not implemented yet.")
def get_module_fields_md5(self):
raise SugarError("Method not implemented yet.")
def get_module_layout(self):
raise SugarError("Method not implemented yet.")
def get_note_attachment(self):
raise SugarError("Method not implemented yet.")
def get_quotes_pdf(self):
raise SugarError("Method not implemented yet.")
def get_relationships(self):
raise SugarError("Method not implemented yet.")
def get_report_entries(self):
raise SugarError("Method not implemented yet.")
def get_report_pdf(self):
raise SugarError("Method not implemented yet.")
def get_server_info(self):
raise SugarError("Method not implemented yet.")
def get_upcoming_activities(self):
raise SugarError("Method not implemented yet.")
def get_user_id(self):
raise SugarError("Method not implemented yet.")
def get_user_team_id(self):
raise SugarError("Method not implemented yet.")
def job_queue_cycle(self):
raise SugarError("Method not implemented yet.")
def job_queue_next(self):
raise SugarError("Method not implemented yet.")
def job_queue_run(self):
raise SugarError("Method not implemented yet.")
def login(self, username, password, app="Python", lang="en_us"):
"""Logs a user into the SugarCRM application."""
data = [
{
'user_name': username,
'password': hashlib.md5(password.encode('utf8')).hexdigest()
},
app,
[{
'name': "language",
'value': lang
}]
]
return self._request('login', data)
def logout(self):
raise SugarError("Method not implemented yet.")
def oauth_access(self):
raise SugarError("Method not implemented yet.")
def seamless_login(self):
raise SugarError("Method not implemented yet.")
def search_by_module(self):
raise SugarError("Method not implemented yet.")
def set_campaign_merge(self):
raise SugarError("Method not implemented yet.")
def set_document_revision(self, doc, f, revision=None):
"""Creates a new document revision for a specific document record."""
if isinstance(f, str) or isinstance(f, unicode):
f = open(f, 'rb')
fields = {
'id': doc.id,
'filename': f.name.split(os.sep)[-1],
'file': base64.b64encode(f.read()),
'revision': revision or doc.revision,
}
data = [self.session_id, fields]
return self._request('set_document_revision', data)
def set_entries(self):
raise SugarError("Method not implemented yet.")
def set_entry(self, obj):
"""Creates or updates a specific object."""
data = [self.session_id, obj.module, obj.fields]
result = self._request('set_entry', data)
obj.id = result['id']
return obj
def set_note_attachment(self, note, f):
"""Creates an attachmentand associates it to a specific note object."""
if isinstance(f, str) or isinstance(f, unicode):
f = open(f, 'rb')
fields = {
'id': note.id,
'filename': f.name,
'file': base64.b64encode(f.read())
}
data = [self.session_id, fields]
return self._request('set_note_attachment', data)
def set_relationship(self, parent, child, delete=False):
"""Sets relationships between two records."""
delete = int(delete)
related_ids = [child.id, ]
name_value_list = [{
'name': "%s_%s" % (parent.module.lower(), child.module.lower()),
'value': 'Other',
}]
data = [self.session_id, parent.module, parent.id,
child.module.lower(), related_ids, name_value_list, delete]
return self._request('set_relationship', data)
def set_relationships(self):
raise SugarError("Method not implemented yet.")
def snip_import_emails(self):
raise SugarError("Method not implemented yet.")
def snip_update_contacts(self):
raise SugarError("Method not implemented yet.")
class SugarObject:
def __init__(self, **kwargs):
for key, value in kwargs.items():
setattr(self, key, value)
if key == "module":
try:
cls = value[:-1].replace('ie', 'y').title()
self.__class__ = getattr(sys.modules['sugarcrm'], cls)
except:
pass
@property
def fields(self):
params = []
for key, value in self.__dict__.items():
if not value:
continue
params.append({
'name': key,
'value': value
})
return params
@property
def query(self):
q = ""
for key, value in self.__dict__.items():
if not value:
continue
if q:
q += "AND "
if value.find('%') >= 0:
q += "%s.%s LIKE '%s' " \
% (self.module.lower(), key, str(value))
else:
q += "%s.%s='%s' " % (self.module.lower(), key, str(value))
return q
class Call(SugarObject):
module = "Calls"
class Campaign(SugarObject):
module = "Campaigns"
class Contact(SugarObject):
module = "Contacts"
class Document(SugarObject):
module = "Documents"
class Email(SugarObject):
module = "Emails"
class Lead(SugarObject):
module = "Leads"
class Module(SugarObject):
module = "Modules"
class Note(SugarObject):
module = "Notes"
class Opportunity(SugarObject):
module = "Opportunities"
class Product(SugarObject):
module = "Products"
class Prospect(SugarObject):
module = "Prospects"
class ProspectList(SugarObject):
module = "ProspectLists"
class Quote(SugarObject):
module = "Quotes"
class Report(SugarObject):
module = "Reports"
class User(SugarObject):
module = "Users"
class Account(SugarObject):
module = "Accounts"
class SugarError(Exception):
pass