/
utils-org.R
1115 lines (1042 loc) · 43.1 KB
/
utils-org.R
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
#' Return Current User Info
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Retrieves personal information for the user associated with the current session.
#'
#' @importFrom httr content
#' @importFrom XML newXMLNode
#' @importFrom xml2 xml_ns_strip xml_find_all
#' @importFrom purrr map_df
#' @template api_type
#' @template verbose
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_user_info()
#' }
#' @export
sf_user_info <- function(api_type=c("SOAP", "Chatter"), verbose=FALSE){
api_type <- match.arg(api_type)
if(api_type == "SOAP"){
base_soap_url <- make_base_soap_url()
if(verbose) {
message(base_soap_url)
}
# build the body
xml_dat <- make_soap_xml_skeleton()
body_node <- newXMLNode("soapenv:Body", parent=xml_dat)
operation_node <- newXMLNode(sprintf("urn:%s", "getUserInfo"), parent=body_node)
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="create",
"Content-Type"="text/xml"),
body = as(xml_dat, "character"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
this_res <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
map_df(xml_nodeset_to_df) %>%
as.list()
} else if(api_type == "Chatter"){
chatter_url <- make_chatter_users_url()
this_url <- sprintf("%s%s", chatter_url, "me")
if(verbose) {
message(this_url)
}
httr_response <- rGET(this_url)
catch_errors(httr_response)
this_res <- content(httr_response, encoding='UTF-8')
} else {
catch_unknown_api(api_type)
}
return(this_res)
}
#' Set User Password
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Sets the specified user’s password to the specified value.
#'
#' @param user_id \code{character}; the unique Salesforce Id assigned to the User
#' @param password \code{character}; a new password that you would like to set for the
#' supplied user that complies to your organizations password requirements
#' @template verbose
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_set_password(user_id = "0056A000000ZZZaaBBB", password="password123")
#' }
#' @export
sf_set_password <- function(user_id, password, verbose=FALSE){
base_soap_url <- make_base_soap_url()
if(verbose) {
message(base_soap_url)
}
# build the body
r <- make_soap_xml_skeleton()
xml_dat <- build_soap_xml_from_list(input_data = list(userId=user_id,
password=password),
operation = "setPassword",
root=r)
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="create",
"Content-Type"="text/xml"),
body = as(xml_dat, "character"))
catch_errors(httr_response)
return(TRUE)
}
#' Reset User Password
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Changes a user’s password to a temporary, system-generated value.
#'
#' @importFrom httr content
#' @importFrom xml2 xml_ns_strip xml_find_all xml_text
#' @param user_id \code{character}; the unique Salesforce Id assigned to the User
#' @template control
#' @param ... arguments passed to \code{\link{sf_control}}
#' @template verbose
#' @return \code{list}
#' @examples
#' \dontrun{
#' # reset a user's password and ensure that an email is triggered to them
#' sf_reset_password(user_id = "0056A000000ZZZaaBBB",
#' EmailHeader = list(triggerAutoResponseEmail = FALSE,
#' triggerOtherEmail = FALSE,
#' triggerUserEmail = TRUE))
#' }
#' @export
sf_reset_password <- function(user_id,
control = list(...), ...,
verbose = FALSE){
base_soap_url <- make_base_soap_url()
if(verbose) {
message(base_soap_url)
}
# build the body
control_args <- return_matching_controls(control)
control_args$api_type <- "SOAP"
control_args$operation <- "resetPassword"
control <- do.call("sf_control", control_args)
r <- make_soap_xml_skeleton(soap_headers = control)
xml_dat <- build_soap_xml_from_list(input_data = list(userId = user_id),
operation = "resetPassword",
root = r)
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="create",
"Content-Type"="text/xml"),
body = as(xml_dat, "character"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
this_res <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_text()
return(this_res)
}
#' Salesforce Server Timestamp
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Retrieves the current system timestamp from the API.
#'
#' @importFrom httr headers
#' @importFrom lubridate dmy_hms
#' @return \code{POSIXct} formatted timestamp
#' @examples
#' \dontrun{
#' sf_server_timestamp()
#' }
#' @export
sf_server_timestamp <- function(){
base_rest_url <- make_base_rest_url()
httr_response <- rGET(base_rest_url,
headers = c("Accept"="application/xml",
"X-PrettyPrint"="1"))
catch_errors(httr_response)
response_parsed <- headers(httr_response)$date
timestamp <- dmy_hms(response_parsed)
return(timestamp)
}
#' List REST API Versions
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Lists summary information about each Salesforce version currently available,
#' including the version, label, and a link to each version\'s root
#'
#' @importFrom httr content
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_list_rest_api_versions()
#' }
#' @export
sf_list_rest_api_versions <- function(){
sf_auth_check()
httr_response <- rGET(sprintf("%s/services/data/", salesforcer_state()$instance_url))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
return(response_parsed)
}
#' List the Resources for an API
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Lists available resources for the specified API version, including resource
#' name and URI.
#'
#' @importFrom httr content
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_list_resources()
#' }
#' @export
sf_list_resources <- function(){
base_rest_url <- make_base_rest_url()
httr_response <- rGET(base_rest_url)
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
return(response_parsed)
}
#' List the Limits for an API
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Lists information about limits in your org.
#'
#' @importFrom httr content
#' @note This resource is available in REST API version 29.0 and later for API
#' users with the View Setup and Configuration permission. The resource returns
#' these limits:
#' \itemize{
#' \item Daily API calls
#' \item Daily asynchronous Apex method executions (batch Apex, future methods, queueable Apex, and scheduled Apex)
#' \item Daily Bulk API calls
#' \item Daily Streaming API events (API version 36.0 and earlier)
#' \item Daily durable Streaming API events (API version 37.0 and later)
#' \item Streaming API concurrent clients (API version 36.0 and earlier)
#' \item Durable Streaming API concurrent clients (API version 37.0 and later)
#' \item Daily generic streaming events (API version 36.0 and earlier)
#' \item Daily durable generic streaming events (API version 37.0 and later)
#' \item Daily number of mass emails that are sent to external email addresses by using Apex or APIs
#' \item Daily number of single emails that are sent to external email addresses by using Apex or APIs
#' \item Concurrent REST API requests for results of asynchronous report runs
#' \item Concurrent synchronous report runs via REST API
#' \item Hourly asynchronous report runs via REST API
#' \item Hourly synchronous report runs via REST API
#' \item Hourly dashboard refreshes via REST API
#' \item Hourly REST API requests for dashboard results
#' \item Hourly dashboard status requests via REST API
#' \item Daily workflow emails
#' \item Hourly workflow time triggers
#' \item Hourly OData callouts
#' \item Daily and active scratch org counts
#' \item Data storage (MB)
#' \item File storage (MB)
#' }
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_list_api_limits()
#' }
#' @export
sf_list_api_limits <- function(){
base_rest_url <- make_base_rest_url()
httr_response <- rGET(sprintf("%s%s", base_rest_url, "limits/"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
return(response_parsed)
}
#' List Organization Objects and their Metadata
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Lists the available objects and their metadata for your organization’s data.
#'
#' @importFrom httr content
#' @return \code{list}
#' @examples
#' \dontrun{
#' sf_list_objects()
#' }
#' @export
sf_list_objects <- function(){
base_rest_url <- make_base_rest_url()
httr_response <- rGET(sprintf("%s%s", base_rest_url, "sobjects/"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
return(response_parsed)
}
#' Find Duplicate Records
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Performs rule-based searches for duplicate records.
#'
#' @importFrom utils head
#' @importFrom dplyr select rename_at rename everything matches as_tibble tibble
#' @importFrom readr cols type_convert col_guess
#' @importFrom purrr map_df
#' @importFrom xml2 xml_ns_strip xml_find_all
#' @importFrom httr content
#' @param search_criteria \code{list}; a list of fields and their values that would
#' constitute a match. For example, list(FirstName="Marc", Company="Salesforce")
#' @template object_name
#' @template include_record_details
#' @template guess_types
#' @template verbose
#' @return \code{tbl_df} of records found to be duplicates by the match rules
#' @note You must have active duplicate rules for the supplied object before running
#' this function. The \code{object_name} argument refers to using that object's duplicate
#' rules on the search criteria to determine which records in other objects are duplicates.
#' @examples
#' \dontrun{
#' # use the duplicate rules associated with the Lead object on the search
#' # criteria (email) in order to find duplicates
#' found_dupes <- sf_find_duplicates(search_criteria =
#' list(Email="bond_john@@grandhotels.com"),
#' object_name = "Lead")
#'
#' # now look for duplicates on email using the Contact object's rules
#' found_dupes <- sf_find_duplicates(search_criteria =
#' list(Email="bond_john@@grandhotels.com"),
#' object_name = "Contact")
#' }
#' @export
sf_find_duplicates <- function(search_criteria,
object_name,
include_record_details = FALSE,
guess_types = TRUE,
verbose = FALSE){
base_soap_url <- make_base_soap_url()
if(verbose) {
message(base_soap_url)
}
r <- make_soap_xml_skeleton(soap_headers =
list(DuplicateRuleHeader =
list(includeRecordDetails =
tolower(include_record_details))))
xml_dat <- build_soap_xml_from_list(input_data = search_criteria,
operation = "findDuplicates",
object_name = object_name,
root = r)
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="findDuplicates",
"Content-Type"="text/xml"),
body = as(xml_dat, "character"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
duplicate_entitytype <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//duplicateRuleEntityType') %>%
xml_text() %>%
head(1)
which_rules <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//duplicateRule') %>%
map(xml_text) %>%
unlist()
message_w_errors_listed(main_text = sprintf("Using %s rules:", duplicate_entitytype),
errors = which_rules)
this_res <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//matchResults//matchRecords//record')
if(length(this_res) > 0){
resultset <- this_res %>%
map_df(extract_records_from_xml_node,
object_name_as_col = TRUE) %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
} else {
resultset <- tibble()
}
return(resultset)
}
#' Find Duplicate Records By Id
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Performs rule-based searches for duplicate records.
#'
#' @importFrom utils head
#' @importFrom dplyr select rename_at rename everything matches as_tibble tibble
#' @importFrom readr cols type_convert col_guess
#' @importFrom purrr map_df
#' @importFrom xml2 xml_ns_strip xml_find_all
#' @importFrom httr content
#' @template sf_id
#' @template include_record_details
#' @template guess_types
#' @template verbose
#' @return \code{tbl_df} of records found to be duplicates by the match rules
#' @note You must have active duplicate rules for the supplied object before running
#' this function. This function uses the duplicate rules for the object that has
#' the same type as the input record IDs. For example, if the record Id represents
#' an Account, this function uses the duplicate rules associated with the
#' Account object.
#' @examples
#' \dontrun{
#' # use the duplicate rules associated with the object that this record
#' # belongs to in order to find duplicates
#' found_dupes <- sf_find_duplicates_by_id(sf_id = "00Q6A00000aABCnZZZ")
#' }
#' @export
sf_find_duplicates_by_id <- function(sf_id,
include_record_details = FALSE,
guess_types = TRUE,
verbose = FALSE){
stopifnot(length(sf_id) == 1)
base_soap_url <- make_base_soap_url()
if(verbose) {
message(base_soap_url)
}
# build the body
r <- make_soap_xml_skeleton(soap_headers =
list(DuplicateRuleHeader =
list(includeRecordDetails =
tolower(include_record_details))))
xml_dat <- build_soap_xml_from_list(input_data = sf_id,
operation = "findDuplicatesByIds",
root = r)
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="findDuplicatesByIds",
"Content-Type"="text/xml"),
body = as(xml_dat, "character"))
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding='UTF-8')
duplicate_entitytype <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//duplicateRuleEntityType') %>%
xml_text() %>%
head(1)
which_rules <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//duplicateRule') %>%
map(xml_text) %>%
unlist()
message_w_errors_listed(main_text = sprintf("Using %s rules:", duplicate_entitytype),
errors = which_rules)
this_res <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
xml_find_all('.//duplicateResults//matchResults//matchRecords//record')
if(length(this_res) > 0){
resultset <- this_res %>%
map_df(extract_records_from_xml_node,
object_name_as_col = TRUE) %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
} else {
resultset <- tibble()
}
return(resultset)
}
#' Convert Leads
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Converts Leads each into an Account, Contact, as well as (optionally) an Opportunity.
#'
#' @importFrom readr cols type_convert
#' @importFrom httr content
#' @importFrom xml2 xml_ns_strip xml_find_all
#' @importFrom purrr map_df
#' @importFrom dplyr bind_rows
#' @importFrom stats quantile
#' @importFrom utils head
#' @param input_data \code{named vector}, \code{matrix}, \code{data.frame}, or
#' \code{tbl_df}; data can be coerced into a \code{data.frame}. See the details
#' below on how format your input data to control things like whether an opportunity
#' will be created, an email will be sent to the new owner, and other control options.
#' @template guess_types
#' @template api_type
#' @template control
#' @param ... arguments passed to \code{\link{sf_control}}
#' @template verbose
#' @return \code{tbl_df} with details of the converted record
#' @details When converting leads owned by a queue, the owner must be specified.
#' This is because accounts and contacts cannot be owned by a queue. Below is a
#' complete list of options to control the conversion process. Include a column
#' in your input data to specify an option for each record. For example, if you
#' want opportunities to not be created for each converted lead then add a column
#' in your input data called \code{doNotCreateOpportunity} and set its value to
#' \code{TRUE}. The default is \code{FALSE} which creates opportunities. The order
#' of columns in the input data does not matter, just that the names
#' match (case-insensitive).
#' \describe{
#' \item{leadId}{ID of the Lead to convert. Required.}
#' \item{convertedStatus}{Valid LeadStatus value for a converted lead. Required.}
#' \item{accountId}{Id of the Account into which the lead will be merged. Required
#' only when updating an existing account, including person accounts. If no
#' accountId is specified, then the API creates a new account.}
#' \item{contactId}{Id of the Contact into which the lead will be merged (this
#' contact must be associated with the specified accountId, and an accountId
#' must be specified). Required only when updating an existing contact. If no
#' contactId is specified, then the API creates a new contact that is implicitly
#' associated with the Account.}
#' \item{ownerId}{Specifies the Id of the person to own any newly created account,
#' contact, and opportunity. If the client application does not specify this
#' value, then the owner of the new object will be the owner of the lead.}
#' \item{opportunityId}{The Id of an existing opportunity to relate to the lead.
#' The opportunityId and opportunityName arguments are mutually exclusive. Specifying
#' a value for both results in an error. If doNotCreateOpportunity argument is
#' \code{TRUE}, then no Opportunity is created and this field must be left blank;
#' otherwise, an error is returned.}
#' \item{doNotCreateOpportunity}{Specifies whether to create an Opportunity during
#' lead conversion (\code{FALSE}, the default) or not (\code{TRUE}). Set this flag
#' to \code{TRUE} only if you do not want to create an opportunity from the lead.
#' An opportunity is created by default.}
#' \item{opportunityName}{Name of the opportunity to create. If no name is specified,
#' then this value defaults to the company name of the lead. The maximum length
#' of this field is 80 characters. The opportunityId and opportunityName arguments
#' are mutually exclusive. Specifying a value for both results in an error. If
#' doNotCreateOpportunity argument is \code{TRUE}, then no Opportunity is created and
#' this field must be left blank; otherwise, an error is returned.}
#' \item{overwriteLeadSource}{Specifies whether to overwrite the LeadSource field
#' on the target Contact object with the contents of the LeadSource field in
#' the source Lead object (\code{TRUE}), or not (\code{FALSE}, the default). To
#' set this field to \code{TRUE}, the client application must specify a contactId
#' for the target contact.}
#' \item{sendNotificationEmail}{Specifies whether to send a notification email
#' to the owner specified in the ownerId (\code{TRUE}) or not (\code{FALSE},
#' the default).}
#' }
#' \href{https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_convertlead.htm}{Salesforce Documentation}
#' @examples
#' \dontrun{
#' # create a new lead at Grand Hotels & Resorts Ltd
#' new_lead <- tibble(FirstName = "Test", LastName = "Prospect",
#' Company = "Grand Hotels & Resorts Ltd")
#' rec <- sf_create(new_lead, "Lead")
#'
#' # find the Id of matching account to link to
#' acct_id <- sf_query("SELECT Id from Account WHERE name = 'Grand Hotels & Resorts Ltd' LIMIT 1")
#'
#' # create the row(s) for the leads to convert
#' to_convert <- tibble(leadId = rec$id,
#' convertedStatus = "Closed - Converted",
#' accountId = acct_id$Id)
#' converted_lead <- sf_convert_lead(to_convert)
#' }
#' @export
sf_convert_lead <- function(input_data,
guess_types = TRUE,
api_type = c("SOAP"),
control = list(...), ...,
verbose = FALSE){
# validate the input
input_data <- sf_input_data_validation(operation='convertLead', input_data)
# specify the following defaults (all FALSE by default), if not included
expected_options <- c("doNotCreateOpportunity",
"overwriteLeadSource",
"sendNotificationEmail")
for(e in expected_options){
if(!(e %in% names(input_data))){
input_data[e] <- FALSE
}
}
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
control_args$operation <- "convertLead"
control <- do.call("sf_control", control)
# chunk into batches of 100 (the max per this operation)
base_soap_url <- make_base_soap_url()
batch_size <- 100
row_num <- nrow(input_data)
batch_id <- (seq.int(row_num)-1) %/% batch_size
if(verbose) message("Submitting data in ", max(batch_id) + 1, " Batches")
message_flag <- unique(as.integer(quantile(0:max(batch_id), c(0.25,0.5,0.75,1))))
resultset <- NULL
for(batch in seq(0, max(batch_id))){
if(verbose){
batch_msg_flg <- batch %in% message_flag
if(batch_msg_flg){
message(paste0("Processing Batch # ", head(batch, 1) + 1))
}
}
batched_data <- input_data[batch_id == batch, , drop=FALSE]
r <- make_soap_xml_skeleton(soap_headers = control)
xml_dat <- build_soap_xml_from_list(input_data = batched_data,
operation = "convertLead",
root = r)
request_body <- as(xml_dat, "character")
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="convertLead",
"Content-Type"="text/xml"),
body = request_body)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,
request_body)
}
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding="UTF-8")
this_set <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
map_df(extract_records_from_xml_node)
resultset <- safe_bind_rows(list(resultset, this_set))
}
resultset <- resultset %>%
sf_reorder_cols() %>%
sf_guess_cols(guess_types)
return(resultset)
}
#' Merge Records
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' This function combines records of the same object type into one of the records,
#' known as the master record. The other records, known as the victim records, will
#' be deleted. If a victim record has related records the master record the new
#' parent of the related records.
#'
#' @importFrom httr content
#' @importFrom readr type_convert cols
#' @importFrom xml2 xml_ns_strip xml_find_all as_list
#' @importFrom purrr map_df
#' @importFrom dplyr tibble
#' @param master_id \code{character}; a Salesforce generated Id that identifies the master record,
#' which is the record to which the victim records will be merged into
#' @param victim_ids \code{character}; one or two Salesforce Ids of records to be merged into
#' the master record. Up to three records can be merged in a single request, including
#' the master record. This limit is the same as the limit enforced by the Salesforce user
#' interface. To merge more than 3 records, successively merge records by running
#' \code{\link{sf_merge}} repeatedly.
#' @template object_name
#' @param master_fields \code{named vector}; a vector of field names and values to
#' supersede the master record values. Otherwise, the field values on the master record
#' will prevail.
#' @template api_type
#' @template control
#' @param ... arguments passed to \code{\link{sf_control}}
#' @template verbose
#' @return \code{tbl_df} of records with success indicator
#' @examples
#' \dontrun{
#' n <- 3
#' new_contacts <- tibble(FirstName = rep("Test", n),
#' LastName = paste0("Contact", 1:n),
#' Description = paste0("Description", 1:n))
#' new_recs1 <- sf_create(new_contacts, object_name = "Contact")
#'
#' # merge the second and third into the first record, but set the
#' # description field equal to the description of the second. All other fields
#' # will from the first record or, if blank, from the other records
#' merge_res <- sf_merge(master_id = new_recs1$id[1],
#' victim_ids = new_recs1$id[2:3],
#' object_name = "Contact",
#' master_fields = tibble("Description" = new_contacts$Description[2]))
#' # check the second and third records now have the same Master Record Id as the first
#' merge_check <- sf_query(sprintf("SELECT Id, MasterRecordId, Description
#' FROM Contact WHERE Id IN ('%s')",
#' paste0(new_recs1$id, collapse="','")),
#' queryall = TRUE)
#' }
#' @export
sf_merge <- function(master_id,
victim_ids,
object_name,
master_fields = character(0),
api_type = c("SOAP"),
control = list(...), ...,
verbose = FALSE){
master_fields <- unlist(master_fields)
master_fields["Id"] <- master_id
master_fields <- c(master_fields["Id"],
master_fields[names(master_fields) != 'Id'])
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
control_args$operation <- "merge"
control <- do.call("sf_control", control)
base_soap_url <- make_base_soap_url()
r <- make_soap_xml_skeleton(soap_headers = control)
xml_dat <- build_soap_xml_from_list(input_data = list(victim_ids = victim_ids,
master_fields = master_fields),
operation = "merge",
object_name = object_name,
root = r)
request_body <- as(xml_dat, "character")
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="merge",
"Content-Type"="text/xml"),
body = request_body)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,
request_body)
}
catch_errors(httr_response)
response_parsed <- content(httr_response, as="parsed", encoding="UTF-8")
this_set <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result') %>%
# we must use XML because character elements are not automatically unboxed
# see https://github.com/r-lib/xml2/issues/215
map(.f=function(x){
xmlToList(xmlParse(as(object=x, Class="character")))
}) %>%
.[[1]]
resultset <- tibble(
id = merge_null_to_na(this_set$id),
success = merge_null_to_na(this_set$success),
mergedRecordIds = merge_null_to_na(list(unname(unlist(this_set[names(this_set) == "mergedRecordIds"])))),
updatedRelatedIds = merge_null_to_na(list(unname(unlist(this_set[names(this_set) == "updatedRelatedIds"])))),
errors = merge_null_to_na(list(this_set$errors))
) %>%
type_convert(col_types = cols(.default = col_guess()))
return(resultset)
}
#' Get Deleted Records from a Timeframe
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Retrieves the list of individual records that have been deleted within the given
#' timespan for the specified object.
#'
#' @importFrom lubridate as_datetime
#' @importFrom httr content
#' @importFrom xml2 xml_ns_strip xml_find_all xml_text
#' @importFrom purrr map_df
#' @importFrom readr type_convert cols
#' @template object_name
#' @param start \code{date} or \code{datetime}; starting datetime of the timespan
#' for which to retrieve the data.
#' @param end \code{date} or \code{datetime}; ending datetime of the timespan for
#' which to retrieve the data.
#' @template verbose
#' @examples
#' \dontrun{
#' # get all deleted Contact records from midnight until now
#' deleted_recs <- sf_get_deleted("Contact", Sys.Date(), Sys.time())
#' }
#' @note This API ignores the seconds portion of the supplied datetime values.
#' @export
sf_get_deleted <- function(object_name,
start, end,
verbose = FALSE){
stopifnot(any(class(start) %in% c("Date", "POSIXct", "POSIXt", "POSIXlt")))
stopifnot(any(class(end) %in% c("Date", "POSIXct", "POSIXt", "POSIXlt")))
base_soap_url <- make_base_soap_url()
r <- make_soap_xml_skeleton()
xml_dat <- build_soap_xml_from_list(input_data = list(start = sf_format_time(start),
end = sf_format_time(end)),
object_name = object_name,
operation = "getDeleted",
root = r)
request_body <- as(xml_dat, "character")
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="getDeleted",
"Content-Type"="text/xml"),
body = request_body)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,
request_body)
}
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding="UTF-8")
if(verbose){
earliest <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result/earliestDateAvailable') %>%
xml_text()
latest <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result/latestDateCovered') %>%
xml_text()
message(sprintf("Earliest Date Available: %s UTC - Latest Date Covered: %s UTC",
as_datetime(earliest), as_datetime(latest)))
}
resultset <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result//deletedRecords') %>%
map_df(xml_nodeset_to_df) %>%
type_convert(col_types = cols())
return(resultset)
}
#' Get Updated Records from a Timeframe
#'
#' @description
#' `r lifecycle::badge("stable")`
#'
#' Retrieves the list of individual records that have been inserted or updated
#' within the given timespan in the specified object.
#'
#' @importFrom lubridate as_datetime
#' @importFrom httr content
#' @importFrom xml2 xml_ns_strip xml_find_all xml_text as_list
#' @importFrom purrr map_df
#' @importFrom dplyr tibble
#' @importFrom readr type_convert cols
#' @template object_name
#' @param start \code{date} or \code{datetime}; starting datetime of the timespan
#' for which to retrieve the data.
#' @param end \code{date} or \code{datetime}; ending datetime of the timespan for
#' which to retrieve the data.
#' @template verbose
#' @examples
#' \dontrun{
#' # get all updated Contact records from midnight until now
#' updated_recs <- sf_get_updated("Contact", Sys.Date(), Sys.time())
#' }
#' @note This API ignores the seconds portion of the supplied datetime values.
#' @export
sf_get_updated <- function(object_name,
start, end,
verbose = FALSE){
stopifnot(any(class(start) %in% c("Date", "POSIXct", "POSIXt", "POSIXlt")))
stopifnot(any(class(end) %in% c("Date", "POSIXct", "POSIXt", "POSIXlt")))
base_soap_url <- make_base_soap_url()
r <- make_soap_xml_skeleton()
xml_dat <- build_soap_xml_from_list(input_data = list(start = sf_format_time(start),
end = sf_format_time(end)),
object_name = object_name,
operation = "getUpdated",
root = r)
request_body <- as(xml_dat, "character")
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="getUpdated",
"Content-Type"="text/xml"),
body = request_body)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,
request_body)
}
catch_errors(httr_response)
response_parsed <- content(httr_response, encoding="UTF-8")
if(verbose){
latest <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result/latestDateCovered') %>%
xml_text()
message(sprintf("Latest Date Covered: %s UTC", as_datetime(latest)))
}
resultset <- response_parsed %>%
xml_ns_strip() %>%
xml_find_all('.//result/ids') %>%
as_list() %>%
unlist()
if(length(resultset) > 0){
resultset <- tibble(id = resultset)
} else {
resultset <- tibble()
}
return(resultset)
}
#' Undelete Records
#'
#' @description
#' `r lifecycle::badge("experimental")`
#'
#' Undeletes records from the Recycle Bin.
#'
#' @importFrom httr content
#' @importFrom readr type_convert cols
#' @importFrom dplyr bind_rows
#' @importFrom xml2 xml_ns_strip xml_find_all
#' @importFrom purrr map_df
#' @param ids \code{vector}, \code{matrix}, \code{data.frame}, or
#' \code{tbl_df}; if not a vector, there must be a column called Id (case-insensitive)
#' that can be passed in the request
#' @template api_type
#' @template control
#' @param ... arguments passed to \code{\link{sf_control}}
#' @template verbose
#' @return \code{tbl_df} of records with success indicator
#' @note Because the SOAP and REST calls chunk data into batches of 200 records
#' the AllOrNoneHeader will only apply to the success or failure of every batch
#' of records and not all records submitted to the function.
#' @references \url{https://developer.salesforce.com/docs/atlas.en-us.api.meta/api/sforce_api_calls_undelete.htm}
#' @examples
#' \dontrun{
#' new_contact <- c(FirstName = "Test", LastName = "Contact")
#' new_records <- sf_create(new_contact, object_name = "Contact")
#' delete <- sf_delete(new_records$id[1],
#' AllOrNoneHeader = list(allOrNone = TRUE))
#' is_deleted <- sf_query(sprintf("SELECT Id, IsDeleted FROM Contact WHERE Id='%s'",
#' new_records$id[1]),
#' queryall = TRUE)
#' undelete <- sf_undelete(new_records$id[1])
#' is_not_deleted <- sf_query(sprintf("SELECT Id, IsDeleted FROM Contact WHERE Id='%s'",
#' new_records$id[1]))
#' }
#' @export
sf_undelete <- function(ids,
api_type = c("SOAP"),
control = list(...), ...,
verbose = FALSE){
ids <- sf_input_data_validation(ids, operation='undelete')
control_args <- return_matching_controls(control)
control_args$api_type <- api_type
control_args$operation <- "undelete"
control <- do.call("sf_control", control)
# limit this type of request to only 200 records at a time to prevent
# the XML from exceeding a size limit
batch_size <- 200
row_num <- nrow(ids)
batch_id <- (seq.int(row_num)-1) %/% batch_size
base_soap_url <- make_base_soap_url()
if(verbose) message("Submitting data in ", max(batch_id) + 1, " Batches")
message_flag <- unique(as.integer(quantile(0:max(batch_id), c(0.25,0.5,0.75,1))))
resultset <- NULL
for(batch in seq(0, max(batch_id))){
if(verbose){
batch_msg_flg <- batch %in% message_flag
if(batch_msg_flg){
message(paste0("Processing Batch # ", head(batch, 1) + 1))
}
}
batched_data <- ids[batch_id == batch, , drop=FALSE]
r <- make_soap_xml_skeleton(soap_headers = control)
xml_dat <- build_soap_xml_from_list(input_data = batched_data,
operation = "undelete",
root = r)
request_body <- as(xml_dat, "character")
httr_response <- rPOST(url = base_soap_url,
headers = c("SOAPAction"="undelete",
"Content-Type"="text/xml"),
body = request_body)
if(verbose){
make_verbose_httr_message(httr_response$request$method,
httr_response$request$url,
httr_response$request$headers,