forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
salesforce.py
1674 lines (1442 loc) · 58.7 KB
/
salesforce.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""Salesforce source module responsible to fetch documents from Salesforce."""
import os
import re
from datetime import datetime
from functools import cached_property, partial
from itertools import groupby
import aiohttp
import fastjsonschema
from aiohttp.client_exceptions import ClientResponseError
from connectors.access_control import (
ACCESS_CONTROL,
es_access_control_query,
prefix_identity,
)
from connectors.filtering.validation import (
AdvancedRulesValidator,
SyncRuleValidationResult,
)
from connectors.logger import logger
from connectors.source import BaseDataSource
from connectors.utils import (
TIKA_SUPPORTED_FILETYPES,
CancellableSleeps,
RetryStrategy,
iso_utc,
retryable,
)
SALESFORCE_EMULATOR_HOST = os.environ.get("SALESFORCE_EMULATOR_HOST")
RUNNING_FTEST = (
"RUNNING_FTEST" in os.environ
) # Flag to check if a connector is run for ftest or not.
RETRIES = 3
RETRY_INTERVAL = 1
BASE_URL = "https://<domain>.my.salesforce.com"
API_VERSION = "v59.0"
TOKEN_ENDPOINT = "/services/oauth2/token" # noqa S105
QUERY_ENDPOINT = f"/services/data/{API_VERSION}/query"
SOSL_SEARCH_ENDPOINT = f"/services/data/{API_VERSION}/search"
DESCRIBE_ENDPOINT = f"/services/data/{API_VERSION}/sobjects"
DESCRIBE_SOBJECT_ENDPOINT = f"/services/data/{API_VERSION}/sobjects/<sobject>/describe"
# https://developer.salesforce.com/docs/atlas.en-us.api_rest.meta/api_rest/resources_sobject_blob_retrieve.htm
CONTENT_VERSION_DOWNLOAD_ENDPOINT = f"/services/data/{API_VERSION}/sobjects/ContentVersion/<content_version_id>/VersionData"
OFFSET = 200
OBJECT_READ_PERMISSION_USERS = "SELECT AssigneeId FROM PermissionSetAssignment WHERE PermissionSetId IN (SELECT ParentId FROM ObjectPermissions WHERE PermissionsRead = true AND SObjectType = '{sobject}')"
USERNAME_FROM_IDS = "SELECT Name, Email FROM User WHERE Id IN {user_list}"
FILE_ACCESS = "SELECT ContentDocumentId, LinkedEntityId, LinkedEntity.Name FROM ContentDocumentLink WHERE ContentDocumentId = '{document_id}'"
RELEVANT_SOBJECTS = [
"Account",
"Campaign",
"Case",
"CaseComment",
"CaseFeed",
"Contact",
"ContentDocument",
"ContentDocumentLink",
"ContentVersion",
"EmailMessage",
"FeedComment",
"Lead",
"Opportunity",
"User",
]
RELEVANT_SOBJECT_FIELDS = [
"AccountId",
"BccAddress",
"BillingAddress",
"Body",
"CaseNumber",
"CcAddress",
"CommentBody",
"CommentCount",
"Company",
"ContentSize",
"ConvertedAccountId",
"ConvertedContactId",
"ConvertedDate",
"ConvertedOpportunityId",
"Department",
"Description",
"Email",
"EndDate",
"FileExtension",
"FirstOpenedDate",
"FromAddress",
"FromName",
"IsActive",
"IsClosed",
"IsDeleted",
"LastEditById",
"LastEditDate",
"LastModifiedById",
"LatestPublishedVersionId",
"LeadSource",
"LinkUrl",
"MessageDate",
"Name",
"OwnerId",
"ParentId",
"Phone",
"PhotoUrl",
"Rating",
"StageName",
"StartDate",
"Status",
"StatusParentId",
"Subject",
"TextBody",
"Title",
"ToAddress",
"Type",
"VersionDataUrl",
"VersionNumber",
"Website",
"UserType",
]
def _prefix_user(user):
if user:
return prefix_identity("user", user)
def _prefix_user_id(user_id):
return prefix_identity("user_id", user_id)
def _prefix_email(email):
return prefix_identity("email", email)
class RateLimitedException(Exception):
"""Notifies that Salesforce has begun rate limiting the current account"""
pass
class InvalidQueryException(Exception):
"""Notifies that a query was malformed or otherwise incorrect"""
pass
class InvalidCredentialsException(Exception):
"""Notifies that credentials are invalid for fetching a Salesforce token"""
pass
class TokenFetchException(Exception):
"""Notifies that an unexpected error occurred when fetching a Salesforce token"""
pass
class ConnectorRequestError(Exception):
"""Notifies that a general uncaught 400 error occurred during a request, usually this is caused by the connector"""
pass
class SalesforceServerError(Exception):
"""Notifies that an internal server error occurred in Salesforce"""
pass
class SalesforceClient:
def __init__(self, configuration, base_url):
self._logger = logger
self._sleeps = CancellableSleeps()
self._queryable_sobjects = None
self._queryable_sobject_fields = {}
self._sobjects_cache_by_type = None
self._content_document_links_join = None
self.base_url = base_url
self.api_token = SalesforceAPIToken(
self.session,
self.base_url,
configuration["client_id"],
configuration["client_secret"],
)
def set_logger(self, logger_):
self._logger = logger_
@cached_property
def session(self):
return aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=None),
)
async def ping(self):
await self.session.head(self.base_url)
async def close(self):
self.api_token.clear()
await self.session.close()
del self.session
def modify_soql_query(self, query):
lowered_query = query.lower()
match_limit = re.search(r"(?i)(.*)FROM\s+(.*?)(?:LIMIT)(.*)", lowered_query)
match_offset = re.search(r"(?i)(.*)FROM\s+(.*?)(?:OFFSET)(.*)", lowered_query)
if "fields" in lowered_query and not match_limit:
query += " LIMIT 200 OFFSET 0"
elif "fields" in lowered_query and match_limit and not match_offset:
query += " OFFSET 0"
elif "fields" in lowered_query and match_limit and match_offset:
return query
return query
def _add_last_modified_date(self, query):
lowered_query = query.lower()
if (
not ("fields(all)" in lowered_query or "fields(standard)" in lowered_query)
and "lastmodifieddate" not in lowered_query
):
query = re.sub(
r"(?i)SELECT (.*) FROM", r"SELECT \1, LastModifiedDate FROM", query
)
return query
def _add_id(self, query):
lowered_query = query.lower()
if not (
"fields(all)" in lowered_query or "fields(standard)" in lowered_query
) and not re.search(r"\bid\b", lowered_query):
query = re.sub(r"(?i)SELECT (.*) FROM", r"SELECT \1, Id FROM", query)
return query
async def get_sync_rules_results(self, rule):
if rule["language"] == "SOQL":
query_with_id = self._add_id(query=rule["query"])
query = self._add_last_modified_date(query=query_with_id)
if "fields" not in query.lower():
async for records in self._yield_non_bulk_query_pages(soql_query=query):
for record in records:
yield record
# If FIELDS function is present in SOQL query, LIMIT/OFFSET is used for pagination
else:
soql_query = self.modify_soql_query(query=query)
async for records in self._yield_soql_query_pages_with_fields_function(
soql_query=soql_query
):
for record in records:
yield record
else:
async for records in self._yield_sosl_query_pages(sosl_query=rule["query"]):
for record in records:
yield record
async def _custom_objects(self):
response = await self._get_json(f"{self.base_url}{DESCRIBE_ENDPOINT}")
custom_objects = []
for sobject in response.get("sobjects", []):
if sobject.get("custom") and sobject.get("name")[-3:] == "__c":
custom_objects.append(sobject.get("name"))
return custom_objects
async def get_custom_objects(self):
for custom_object in await self._custom_objects():
query = await self._custom_object_query(custom_object=custom_object)
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_salesforce_users(self):
if not await self._is_queryable("User"):
self._logger.warning(
"Object User is not queryable, so they won't be ingested."
)
return
query = await self._user_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_users_with_read_access(self, sobject):
query = OBJECT_READ_PERMISSION_USERS.format(sobject=sobject)
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_username_by_id(self, user_list):
query = USERNAME_FROM_IDS.format(user_list=user_list)
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_file_access(self, document_id):
query = FILE_ACCESS.format(document_id=document_id)
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_accounts(self):
if not await self._is_queryable("Account"):
self._logger.warning(
"Object Account is not queryable, so they won't be ingested."
)
return
query = await self._accounts_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_opportunities(self):
if not await self._is_queryable("Opportunity"):
self._logger.warning(
"Object Opportunity is not queryable, so they won't be ingested."
)
return
query = await self._opportunities_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_contacts(self):
if not await self._is_queryable("Contact"):
self._logger.warning(
"Object Contact is not queryable, so they won't be ingested."
)
return
query = await self._contacts_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
sobjects_by_id = await self.sobjects_cache_by_type()
record["Account"] = sobjects_by_id["Account"].get(
record.get("AccountId"), {}
)
record["Owner"] = sobjects_by_id["User"].get(record.get("OwnerId"), {})
yield record
async def get_leads(self):
if not await self._is_queryable("Lead"):
self._logger.warning(
"Object Lead is not queryable, so they won't be ingested."
)
return
query = await self._leads_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
sobjects_by_id = await self.sobjects_cache_by_type()
record["Owner"] = sobjects_by_id["User"].get(record.get("OwnerId"), {})
record["ConvertedAccount"] = sobjects_by_id["Account"].get(
record.get("ConvertedAccountId"), {}
)
record["ConvertedContact"] = sobjects_by_id["Contact"].get(
record.get("ConvertedContactId"), {}
)
record["ConvertedOpportunity"] = sobjects_by_id["Opportunity"].get(
record.get("ConvertedOpportunityId"), {}
)
yield record
async def get_campaigns(self):
if not await self._is_queryable("Campaign"):
self._logger.warning(
"Object Campaign is not queryable, so they won't be ingested."
)
return
query = await self._campaigns_query()
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
yield record
async def get_cases(self):
if not await self._is_queryable("Case"):
self._logger.warning(
"Object Case is not queryable, so they won't be ingested."
)
return
query = await self._cases_query()
async for records in self._yield_non_bulk_query_pages(query):
case_feeds_by_case_id = {}
if await self._is_queryable("CaseFeed") and records:
all_case_ids = [x.get("Id") for x in records]
case_ids_list = [
all_case_ids[i : i + 800] for i in range(0, len(all_case_ids), 800)
]
all_case_feeds = []
for case_ids in case_ids_list:
case_feeds = await self.get_case_feeds(case_ids)
all_case_feeds.extend(case_feeds)
# groupby requires pre-sorting apparently
all_case_feeds.sort(key=lambda x: x.get("ParentId", ""))
case_feeds_by_case_id = {
k: list(feeds)
for k, feeds in groupby(
all_case_feeds, key=lambda x: x.get("ParentId", "")
)
}
for record in records:
record["Feeds"] = case_feeds_by_case_id.get(record.get("Id"))
yield record
async def get_case_feeds(self, case_ids):
query = await self._case_feeds_query(case_ids)
all_case_feeds = []
async for case_feeds in self._yield_non_bulk_query_pages(query):
all_case_feeds.extend(case_feeds)
return all_case_feeds
async def queryable_sobjects(self):
"""Cached async property"""
if self._queryable_sobjects is not None:
return self._queryable_sobjects
response = await self._get_json(f"{self.base_url}{DESCRIBE_ENDPOINT}")
self._queryable_sobjects = []
for sobject in response.get("sobjects", []):
if sobject["queryable"] is True and sobject["name"] in RELEVANT_SOBJECTS:
self._queryable_sobjects.append(sobject["name"].lower())
return self._queryable_sobjects
async def queryable_sobject_fields(
self,
relevant_objects,
relevant_sobject_fields,
):
"""Cached async property"""
for sobject in relevant_objects:
endpoint = DESCRIBE_SOBJECT_ENDPOINT.replace("<sobject>", sobject)
response = await self._get_json(f"{self.base_url}{endpoint}")
if relevant_sobject_fields is None:
queryable_fields = [
f["name"].lower() for f in response.get("fields", [])
]
else:
queryable_fields = [
f["name"].lower()
for f in response.get("fields", [])
if f["name"] in relevant_sobject_fields
]
self._queryable_sobject_fields[sobject] = queryable_fields
return self._queryable_sobject_fields
async def sobjects_cache_by_type(self):
"""Cached async property
Many sobjects require extra data that is taxing on the rate limiter
to repeatedly fetch each request.
Instead we cache them on the first request for re-use later.
"""
if self._sobjects_cache_by_type is not None:
return self._sobjects_cache_by_type
self._sobjects_cache_by_type = {}
self._sobjects_cache_by_type["Account"] = await self._prepare_sobject_cache(
"Account"
)
self._sobjects_cache_by_type["Contact"] = await self._prepare_sobject_cache(
"Contact"
)
self._sobjects_cache_by_type["Opportunity"] = await self._prepare_sobject_cache(
"Opportunity"
)
self._sobjects_cache_by_type["User"] = await self._prepare_sobject_cache("User")
return self._sobjects_cache_by_type
async def _prepare_sobject_cache(self, sobject):
if not await self._is_queryable(sobject):
self._logger.warning(
f"{sobject} is not queryable, so they won't be cached."
)
return {}
queryable_fields = ["Name"]
if sobject in ["User", "Contact", "Lead"]:
queryable_fields.append("Email")
sobjects = {}
query = (
SalesforceSoqlBuilder(sobject)
.with_id()
.with_fields(queryable_fields)
.build()
)
async for records in self._yield_non_bulk_query_pages(query):
for record in records:
sobjects[record["Id"]] = record
return sobjects
async def _is_queryable(self, sobject):
"""User settings can cause sobjects to be non-queryable
Querying these causes errors, so we try to filter those out in advance
"""
return sobject.lower() in await self.queryable_sobjects()
async def _select_queryable_fields(self, sobject, fields):
"""User settings can cause fields to be non-queryable
Querying these causes errors, so we try to filter those out in advance
"""
if sobject not in RELEVANT_SOBJECTS:
sobject_fields = await self.queryable_sobject_fields(
relevant_objects=[sobject], relevant_sobject_fields=None
)
else:
sobject_fields = await self.queryable_sobject_fields(
relevant_objects=RELEVANT_SOBJECTS,
relevant_sobject_fields=RELEVANT_SOBJECT_FIELDS,
)
queryable_fields = sobject_fields.get(sobject, [])
if fields == []:
return queryable_fields
return [f for f in fields if f.lower() in queryable_fields]
async def _yield_non_bulk_query_pages(self, soql_query, endpoint=QUERY_ENDPOINT):
"""loops through query response pages and yields lists of records"""
url = f"{self.base_url}{endpoint}"
params = {"q": soql_query}
while True:
response = await self._get_json(
url,
params=params,
)
yield response.get("records")
if not response.get("nextRecordsUrl"):
break
url = f"{self.base_url}{response.get('nextRecordsUrl')}"
params = None
async def _yield_soql_query_pages_with_fields_function(self, soql_query):
"""loops through SOQL query response pages and yields lists of records"""
def modify_offset(query, new_offset):
offset_pattern = r"OFFSET (\d+)"
new_query = re.sub(offset_pattern, f"OFFSET {new_offset}", query)
return new_query
url = f"{self.base_url}{QUERY_ENDPOINT}"
offset = OFFSET
while True:
response = await self._get_json(
url,
params={"q": soql_query},
)
yield response.get("records", [])
# Note: we can't set offset more than 2000 if SOQL query contains `FIELDS` function
if not response.get("records") or offset > 2000:
break
soql_query = modify_offset(soql_query, offset)
offset += OFFSET
async def _yield_sosl_query_pages(self, sosl_query):
"""loops through SOSL query response pages and yields lists of records"""
url = f"{self.base_url}{SOSL_SEARCH_ENDPOINT}"
params = {"q": sosl_query}
response = await self._get_json(
url,
params=params,
)
yield response.get("searchRecords", [])
async def _execute_non_paginated_query(self, soql_query):
"""For quick queries, ignores pagination"""
url = f"{self.base_url}{QUERY_ENDPOINT}"
params = {"q": soql_query}
response = await self._get_json(
url,
params=params,
)
return response.get("records")
async def _auth_headers(self):
token = await self.api_token.token()
return {"authorization": f"Bearer {token}"}
@retryable(
retries=RETRIES,
interval=RETRY_INTERVAL,
skipped_exceptions=[RateLimitedException, InvalidQueryException],
)
async def _get_json(self, url, params=None):
response_body = None
try:
response = await self._get(url, params=params)
response_body = await response.json()
# We get the response body before raising for status as it contains vital error information
response.raise_for_status()
return response_body
except ClientResponseError as e:
await self._handle_client_response_error(response_body, e)
except Exception as e:
raise e
async def _get(self, url, params=None):
self._logger.debug(f"Sending request. Url: {url}, params: {params}")
headers = await self._auth_headers()
return await self.session.get(
url,
headers=headers,
params=params,
)
async def _download(self, content_version_id):
endpoint = CONTENT_VERSION_DOWNLOAD_ENDPOINT.replace(
"<content_version_id>", content_version_id
)
response = await self._get(f"{self.base_url}{endpoint}")
yield response
async def _handle_client_response_error(self, response_body, e):
exception_details = f"status: {e.status}, message: {e.message}"
if e.status == 401:
self._logger.warning(
f"Token expired, attempting to fetch new token. Status: {e.status}, message: {e.message}"
)
# The user can alter the lifetime of issued tokens, so we don't know when they expire
# By clearing the bearer token, we force the auth headers to fetch a new token in the next request
self.api_token.clear()
# raise to continue with retry strategy
raise e
elif 400 <= e.status < 500:
errors = self._handle_response_body_error(response_body)
# response format is an array for some reason so we check all of the error codes
# errorCode and message are generally identical, except if the query is invalid
error_codes = [x["errorCode"] for x in errors]
if "REQUEST_LIMIT_EXCEEDED" in error_codes:
msg = f"Salesforce is rate limiting this account. {exception_details}, details: {', '.join(error_codes)}"
raise RateLimitedException(msg) from e
elif any(
error in error_codes
for error in [
"INVALID_FIELD",
"INVALID_TERM",
"MALFORMED_QUERY",
"INVALID_TYPE",
]
):
msg = f"The query was rejected by Salesforce. {exception_details}, details: {', '.join(error_codes)}, query: {', '.join([x['message'] for x in errors])}"
raise InvalidQueryException(msg) from e
else:
msg = f"The request to Salesforce failed. {exception_details}, details: {', '.join(error_codes)}"
raise ConnectorRequestError(msg) from e
else:
msg = (
f"Salesforce experienced an internal server error. {exception_details}."
)
raise SalesforceServerError(msg)
def _handle_response_body_error(self, error_list):
if error_list is None or len(error_list) < 1:
return [{"errorCode": "unknown"}]
return error_list
async def _custom_object_query(self, custom_object):
queryable_fields = await self._select_queryable_fields(
custom_object,
[],
)
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder(custom_object)
.with_fields(queryable_fields)
.with_join(doc_links_join)
.build()
)
async def _user_query(self):
queryable_fields = await self._select_queryable_fields(
"User",
["Name", "Email", "UserType"],
)
return (
SalesforceSoqlBuilder("User")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.build()
)
async def _accounts_query(self):
queryable_fields = await self._select_queryable_fields(
"Account",
[
"Name",
"Description",
"BillingAddress",
"Type",
"Website",
"Rating",
"Department",
],
)
doc_links_join = await self.content_document_links_join()
opportunities_join = None
if await self._is_queryable("Opportunity"):
queryable_join_fields = await self._select_queryable_fields(
"Opportunity",
[
"Name",
"StageName",
],
)
opportunities_join = (
SalesforceSoqlBuilder("Opportunities")
.with_id()
.with_fields(queryable_join_fields)
.with_order_by("CreatedDate DESC")
.with_limit(1)
.build()
)
return (
SalesforceSoqlBuilder("Account")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["Owner.Id", "Owner.Name", "Owner.Email"])
.with_fields(["Parent.Id", "Parent.Name"])
.with_join(opportunities_join)
.with_join(doc_links_join)
.build()
)
async def _opportunities_query(self):
queryable_fields = await self._select_queryable_fields(
"Opportunity",
[
"Name",
"Description",
"StageName",
],
)
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder("Opportunity")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["Owner.Id", "Owner.Name", "Owner.Email"])
.with_join(doc_links_join)
.build()
)
async def _contacts_query(self):
queryable_fields = await self._select_queryable_fields(
"Contact",
[
"Name",
"Description",
"Email",
"Phone",
"Title",
"PhotoUrl",
"LeadSource",
"AccountId",
"OwnerId",
],
)
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder("Contact")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_join(doc_links_join)
.build()
)
async def _leads_query(self):
queryable_fields = await self._select_queryable_fields(
"Lead",
[
"Company",
"ConvertedAccountId",
"ConvertedContactId",
"ConvertedDate",
"ConvertedOpportunityId",
"Description",
"Email",
"LeadSource",
"Name",
"OwnerId",
"Phone",
"PhotoUrl",
"Rating",
"Status",
"Title",
],
)
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder("Lead")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_join(doc_links_join)
.build()
)
async def _campaigns_query(self):
queryable_fields = await self._select_queryable_fields(
"Campaign",
[
"Name",
"IsActive",
"Type",
"Description",
"Status",
"StartDate",
"EndDate",
],
)
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder("Campaign")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["Owner.Id", "Owner.Name", "Owner.Email"])
.with_fields(["Parent.Id", "Parent.Name"])
.with_join(doc_links_join)
.build()
)
async def _cases_query(self):
queryable_fields = await self._select_queryable_fields(
"Case",
[
"Subject",
"Description",
"CaseNumber",
"Status",
"AccountId",
"ParentId",
"IsClosed",
"IsDeleted",
],
)
email_mesasges_join = await self._email_messages_join_query()
case_comments_join = await self._case_comments_join_query()
doc_links_join = await self.content_document_links_join()
return (
SalesforceSoqlBuilder("Case")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["Owner.Id", "Owner.Name", "Owner.Email"])
.with_fields(["CreatedBy.Id", "CreatedBy.Name", "CreatedBy.Email"])
.with_join(email_mesasges_join)
.with_join(case_comments_join)
.with_join(doc_links_join)
.build()
)
async def _email_messages_join_query(self):
"""For join with Case"""
queryable_fields = await self._select_queryable_fields(
"EmailMessage",
[
"ParentId",
"MessageDate",
"LastModifiedById",
"TextBody",
"Subject",
"FromName",
"FromAddress",
"ToAddress",
"CcAddress",
"BccAddress",
"Status",
"IsDeleted",
"FirstOpenedDate",
],
)
return (
SalesforceSoqlBuilder("EmailMessages")
.with_id()
.with_fields(queryable_fields)
.with_fields(["CreatedBy.Id", "CreatedBy.Name", "CreatedBy.Email"])
.with_limit(500)
.build()
)
async def _case_comments_join_query(self):
"""For join with Case"""
queryable_fields = await self._select_queryable_fields(
"CaseComment",
[
"ParentId",
"CommentBody",
"LastModifiedById",
],
)
return (
SalesforceSoqlBuilder("CaseComments")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["CreatedBy.Id", "CreatedBy.Name", "CreatedBy.Email"])
.with_limit(500)
.build()
)
async def _case_feeds_query(self, case_ids):
queryable_fields = await self._select_queryable_fields(
"CaseFeed",
[
"ParentId",
"Type",
"IsDeleted",
"CommentCount",
"Title",
"Body",
"LinkUrl",
],
)
where_in_clause = ",".join(f"'{x}'" for x in case_ids)
join_clause = await self._case_feed_comments_join()
return (
SalesforceSoqlBuilder("CaseFeed")
.with_id()
.with_default_metafields()
.with_fields(queryable_fields)
.with_fields(["CreatedBy.Id", "CreatedBy.Name", "CreatedBy.Email"])
.with_join(join_clause)
.with_where(f"ParentId IN ({where_in_clause})")
.build()
)
async def _case_feed_comments_join(self):
queryable_fields = await self._select_queryable_fields(
"FeedComment",
[
"ParentId",
"CreatedDate",
"LastEditById",
"LastEditDate",
"CommentBody",
"IsDeleted",
"StatusParentId",
],
)
return (
SalesforceSoqlBuilder("FeedComments")
.with_id()
.with_fields(queryable_fields)