-
Notifications
You must be signed in to change notification settings - Fork 165
/
client.rb
2051 lines (1768 loc) · 79.8 KB
/
client.rb
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
require 'openssl'
require 'open-uri'
module DocusignRest
class Client
# Define the same set of accessors as the DocusignRest module
attr_accessor *Configuration::VALID_CONFIG_KEYS
attr_accessor :docusign_authentication_headers, :acct_id
attr_accessor :previous_call_log
def initialize(options={})
# Merge the config values from the module and those passed to the client.
merged_options = DocusignRest.options.merge(options)
# Copy the merged values to this client and ignore those not part
# of our configuration
Configuration::VALID_CONFIG_KEYS.each do |key|
send("#{key}=", merged_options[key])
end
# Set up the DocuSign Authentication headers with the values passed from
# our config block
if access_token.nil?
@docusign_authentication_headers = {
'X-DocuSign-Authentication' => {
'Username' => username,
'Password' => password,
'IntegratorKey' => integrator_key
}.to_json
}
else
@docusign_authentication_headers = {
'Authorization' => "Bearer #{access_token}"
}
end
# Set the account_id from the configure block if present, but can't call
# the instance var @account_id because that'll override the attr_accessor
# that is automatically configured for the configure block
@acct_id = account_id
#initialize the log cache
@previous_call_log = []
end
# Internal: sets the default request headers allowing for user overrides
# via options[:headers] from within other requests. Additionally injects
# the X-DocuSign-Authentication header to authorize the request.
#
# Client can pass in header options to any given request:
# headers: {'Some-Key' => 'some/value', 'Another-Key' => 'another/value'}
#
# Then we pass them on to this method to merge them with the other
# required headers
#
# Example:
#
# headers(options[:headers])
#
# Returns a merged hash of headers overriding the default Accept header if
# the user passes in a new 'Accept' header key and adds any other
# user-defined headers along with the X-DocuSign-Authentication headers
def headers(user_defined_headers={})
default = {
'Accept' => 'json' #this seems to get added automatically, so I can probably remove this
}
default.merge!(user_defined_headers) if user_defined_headers
@docusign_authentication_headers.merge(default)
end
# Internal: builds a URI based on the configurable endpoint, api_version,
# and the passed in relative url
#
# url - a relative url requiring a leading forward slash
#
# Example:
#
# build_uri('/login_information')
#
# Returns a parsed URI object
def build_uri(url)
URI.parse("#{endpoint}/#{api_version}#{url}")
end
# Internal: configures Net:HTTP with some default values that are required
# for every request to the DocuSign API
#
# Returns a configured Net::HTTP object into which a request can be passed
def initialize_net_http_ssl(uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = uri.scheme == 'https'
if defined?(Rails) && Rails.env.test?
in_rails_test_env = true
else
in_rails_test_env = false
end
if http.use_ssl? && !in_rails_test_env
if ca_file
if File.exists?(ca_file)
http.ca_file = ca_file
else
raise 'Certificate path not found.'
end
end
# Explicitly verifies that the certificate matches the domain.
# Requires that we use www when calling the production DocuSign API
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
http.verify_depth = 5
else
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
end
http.open_timeout = open_timeout
http.read_timeout = read_timeout
http
end
# Public: creates an OAuth2 authorization server token endpoint.
#
# email - email of user authenticating
# password - password of user authenticating
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.get_token(integrator_key, 'someone@example.com', 'p@ssw0rd01')
#
# Returns:
# access_token - Access token information
# scope - This should always be "api"
# token_type - This should always be "bearer"
def get_token(integrator_key, email, password)
content_type = { 'Content-Type' => 'application/x-www-form-urlencoded', 'Accept' => 'application/json' }
uri = build_uri('/oauth2/token')
request = Net::HTTP::Post.new(uri.request_uri, content_type)
request.body = "grant_type=password&client_id=#{integrator_key}&username=#{email}&password=#{password}&scope=api"
http = initialize_net_http_ssl(uri)
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public: gets info necessary to make additional requests to the DocuSign API
#
# options - hash of headers if the client wants to override something
#
# Examples:
#
# client = DocusignRest::Client.new
# response = client.login_information
# puts response.body
#
# Returns:
# accountId - For the username, password, and integrator_key specified
# baseUrl - The base URL for all future DocuSign requests
# email - The email used when signing up for DocuSign
# isDefault - # TODO identify what this is
# name - The account name provided when signing up for DocuSign
# userId - # TODO determine what this is used for, if anything
# userName - Full name provided when signing up for DocuSign
def get_login_information(options={})
uri = build_uri('/login_information')
request = Net::HTTP::Get.new(uri.request_uri, headers(options[:headers]))
http = initialize_net_http_ssl(uri)
response = http.request(request)
generate_log(request, response, uri)
response
end
# Internal: uses the get_login_information method to determine the client's
# accountId and then caches that value into an instance variable so we
# don't end up hitting the API for login_information more than once per
# request.
#
# This is used by the rake task in lib/tasks/docusign_task.rake to add
# the config/initialzers/docusign_rest.rb file with the proper config block
# which includes the account_id in it. That way we don't require hitting
# the /login_information URI in normal requests
#
# Returns the accountId string
def get_account_id
unless acct_id
response = get_login_information.body
hashed_response = JSON.parse(response)
login_accounts = hashed_response['loginAccounts']
@acct_id ||= login_accounts.first['accountId']
end
acct_id
end
# Internal: takes in an array of hashes of signers and concatenates all the
# hashes with commas
#
# embedded - Tells DocuSign if this is an embedded signer which determines
# whether or not to deliver emails. Also lets us authenticate
# them when they go to do embedded signing. Behind the scenes
# this is setting the clientUserId value to the signer's email.
# name - The name of the signer
# email - The email of the signer
# role_name - The role name of the signer ('Attorney', 'Client', etc.).
# tabs - Array of tab pairs grouped by type (Example type: 'textTabs')
# { textTabs: [ { tabLabel: "label", name: "name", value: "value" } ] }
#
# Returns a hash of users that need to be embedded in the template to
# create an envelope
def get_template_roles(signers)
template_roles = []
signers.each_with_index do |signer, index|
template_role = {
name: signer[:name],
email: signer[:email],
roleName: signer[:role_name],
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs])
}
}
if signer[:email_notification]
template_role[:emailNotification] = signer[:email_notification]
end
template_role['clientUserId'] = (signer[:client_id] || signer[:email]).to_s if signer[:embedded] == true
template_roles << template_role
end
template_roles
end
def get_sign_here_tabs(tabs)
Array(tabs).map do |tab|
{
documentId: tab[:document_id],
recipientId: tab[:recipient_id],
anchorString: tab[:anchor_string],
anchorXOffset: tab[:anchorXOffset],
anchorYOffset: tab[:anchorYOffset]
}
end
end
# TODO (2014-02-03) jonk => document
def get_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'tabLabel' => tab[:label],
'name' => tab[:name],
'value' => tab[:value],
'documentId' => tab[:document_id],
'selected' => tab[:selected],
'locked' => tab[:locked]
}
end
end
def get_radio_signer_tabs(tabs)
Array(tabs).map do |tab|
{
'documentId' => tab[:document_id],
'groupName' => tab[:group_name],
'radios' => tab[:radios],
}
end
end
# TODO (2014-02-03) jonk => document
def get_event_notification(event_notification)
return {} unless event_notification
{
useSoapInterface: event_notification[:use_soap_interface] || false,
includeCertificateWithSoap: event_notification[:include_certificate_with_soap] || false,
url: event_notification[:url],
loggingEnabled: event_notification[:logging],
'envelopeEvents' => Array(event_notification[:envelope_events]).map do |envelope_event|
{
includeDocuments: envelope_event[:include_documents] || false,
envelopeEventStatusCode: envelope_event[:envelope_event_status_code]
}
end,
'recipientEvents' => Array(event_notification[:recipient_events]).map do |recipient_event|
{
includeDocuments: recipient_event[:include_documents] || false,
recipientEventStatusCode: recipient_event[:recipient_event_status_code]
}
end
}
end
# Internal: takes an array of hashes of signers required to complete a
# document and allows for setting several options. Not all options are
# currently dynamic but that's easy to change/add which I (and I'm
# sure others) will be doing in the future.
#
# template - Includes other optional fields only used when
# being called from a template
# email - The signer's email
# name - The signer's name
# embedded - Tells DocuSign if this is an embedded signer which
# determines whether or not to deliver emails. Also
# lets us authenticate them when they go to do
# embedded signing. Behind the scenes this is setting
# the clientUserId value to the signer's email.
# email_notification - Send an email or not
# role_name - The signer's role, like 'Attorney' or 'Client', etc.
# template_locked - Doesn't seem to work/do anything
# template_required - Doesn't seem to work/do anything
# anchor_string - The string of text to anchor the 'sign here' tab to
# document_id - If the doc you want signed isn't the first doc in
# the files options hash
# page_number - Page number of the sign here tab
# x_position - Distance horizontally from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# y_position - Distance vertically from the anchor string for the
# 'sign here' tab to appear. Note: doesn't seem to
# currently work.
# sign_here_tab_text - Instead of 'sign here'. Note: doesn't work
# tab_label - TODO: figure out what this is
def get_signers(signers, options={})
doc_signers = []
signers.each_with_index do |signer, index|
doc_signer = {
accessCode: '',
addAccessCodeToEmail: false,
customFields: signer[:custom_fields],
idCheckConfigurationName: signer[:id_check_configuration_name],
idCheckInformationInput: nil,
inheritEmailNotificationConfiguration: false,
note: signer[:note],
phoneAuthentication: nil,
recipientAttachment: nil,
requireIdLookup: signer[:require_id_lookup],
requireSignOnPaper: signer[:require_sign_on_paper] || false,
roleName: signer[:role_name],
routingOrder: signer[:routing_order] || index + 1,
socialAuthentications: nil
}
recipient_id = signer[:recipient_id] || index + 1
doc_signer[:recipientId] = recipient_id
doc_signer[:clientUserId] = recipient_id if signer[:embedded_signing]
if signer[:id_check_information_input]
doc_signer[:idCheckInformationInput] =
get_id_check_information_input(signer[:id_check_information_input])
end
if signer[:phone_authentication]
doc_signer[:phoneAuthentication] =
get_phone_authentication(signer[:phone_authentication])
end
if signer[:signing_group_id]
doc_signer[:signingGroupId] = signer[:signing_group_id]
else
doc_signer[:email] = signer[:email]
doc_signer[:name] = signer[:name]
end
if signer[:email_notification]
doc_signer[:emailNotification] = signer[:email_notification]
end
if signer[:embedded]
doc_signer[:clientUserId] = signer[:client_id] || signer[:email]
end
if options[:template] == true
doc_signer[:templateAccessCodeRequired] = false
doc_signer[:templateLocked] = signer[:template_locked].nil? ? true : signer[:template_locked]
doc_signer[:templateRequired] = signer[:template_required].nil? ? true : signer[:template_required]
end
doc_signer[:autoNavigation] = false
doc_signer[:defaultRecipient] = false
doc_signer[:signatureInfo] = nil
doc_signer[:tabs] = {
approveTabs: nil,
checkboxTabs: get_tabs(signer[:checkbox_tabs], options, index),
companyTabs: nil,
dateSignedTabs: get_tabs(signer[:date_signed_tabs], options, index),
dateTabs: nil,
declineTabs: nil,
emailTabs: get_tabs(signer[:email_tabs], options, index),
envelopeIdTabs: nil,
fullNameTabs: get_tabs(signer[:full_name_tabs], options, index),
listTabs: get_tabs(signer[:list_tabs], options, index),
noteTabs: nil,
numberTabs: get_tabs(signer[:number_tabs], options, index),
radioGroupTabs: get_tabs(signer[:radio_group_tabs], options, index),
initialHereTabs: get_tabs(signer[:initial_here_tabs], options.merge!(initial_here_tab: true), index),
signHereTabs: get_tabs(signer[:sign_here_tabs], options.merge!(sign_here_tab: true), index),
signerAttachmentTabs: nil,
ssnTabs: nil,
textTabs: get_tabs(signer[:text_tabs], options, index),
titleTabs: get_tabs(signer[:title_tabs], options, index),
zipTabs: nil
}
# append the fully build string to the array
doc_signers << doc_signer
end
doc_signers
end
# Internal: people to be Carbon Copied on the document that is created
# https://docs.docusign.com/esign/restapi/Envelopes/Envelopes/create/
#
# Expecting options to be an array of hashes, with each hash representing a person to carbon copy
#
# email - The email of the recipient to be copied on the document
# name - The name of the recipient
# signer_count - Used to generate required attributes recipientId and routingOrder which must be unique in the document
#
def get_carbon_copies(options, signer_count)
copies = []
(options || []).each do |cc|
signer_count += 1
raise "Missing required data [:email, :name]" unless (cc[:email] && cc[:name])
cc.merge!(recipient_id: signer_count, routing_order: signer_count)
copies << camelize_keys(cc)
end
copies
end
# Public: Translate ruby oriented keys to camel cased keys recursively through the hash received
#
# The method expects symbol parameters in ruby form ":access_code" and translates them to camel cased "accessCode"
#
# example [{access_code: '12345', email_notification: {email_body: 'abcdef'}}] -> [{'accessCode': '12345', 'emailNotification': {'emailBody': 'abcdef'}}]
#
def camelize_keys(hash)
new_hash={}
hash.each do |k,v|
new_hash[camelize(k.to_s)] = (v.is_a?(Hash) ? camelize_keys(v) : v)
end
new_hash
end
# Generic implementation to avoid having to pull in Rails dependencies
#
def camelize(str)
str.gsub(/_([a-z])/) { $1.upcase }
end
# Internal: takes an array of hashes of certified deliveries
#
# email - The recipient email
# name - The recipient name
# recipient_id - The recipient's id
# embedded - Tells DocuSign if this is an embedded recipient which
# determines whether or not to deliver emails.
def get_certified_deliveries(certified_deliveries)
doc_certified_deliveries = []
certified_deliveries.each do |certified_delivery|
doc_certified_delivery = {
email: certified_delivery[:email],
name: certified_delivery[:name],
recipientId: certified_delivery[:recipient_id]
}
if certified_delivery[:embedded]
doc_certified_delivery[:clientUserId] = certified_delivery[:client_id] || certified_delivery[:email]
end
doc_certified_deliveries << doc_certified_delivery
end
doc_certified_deliveries
end
# TODO (2014-02-03) jonk => document
def get_tabs(tabs, options, index)
tab_array = []
Array(tabs).map do |tab|
tab_hash = {}
if tab[:anchor_string]
tab_hash[:anchorString] = tab[:anchor_string]
tab_hash[:anchorXOffset] = tab[:anchor_x_offset] || '0'
tab_hash[:anchorYOffset] = tab[:anchor_y_offset] || '0'
tab_hash[:anchorIgnoreIfNotPresent] = tab[:ignore_anchor_if_not_present] || false
tab_hash[:anchorUnits] = 'pixels'
end
tab_hash[:conditionalParentLabel] = tab[:conditional_parent_label] if tab.key?(:conditional_parent_label)
tab_hash[:conditionalParentValue] = tab[:conditional_parent_value] if tab.key?(:conditional_parent_value)
tab_hash[:documentId] = tab[:document_id] || '1'
tab_hash[:pageNumber] = tab[:page_number] || '1'
tab_hash[:recipientId] = index + 1
tab_hash[:required] = tab[:required] || false
if options[:template] == true
tab_hash[:templateLocked] = tab[:template_locked].nil? ? true : tab[:template_locked]
tab_hash[:templateRequired] = tab[:template_required].nil? ? true : tab[:template_required]
end
if options[:sign_here_tab] == true || options[:initial_here_tab] == true
tab_hash[:scaleValue] = tab[:scale_value] || 1
end
tab_hash[:xPosition] = tab[:x_position] || '0'
tab_hash[:yPosition] = tab[:y_position] || '0'
tab_hash[:name] = tab[:name] if tab[:name]
tab_hash[:optional] = tab[:optional] || false
tab_hash[:tabLabel] = tab[:label] || 'Signature 1'
tab_hash[:width] = tab[:width] if tab[:width]
tab_hash[:height] = tab[:height] if tab[:height]
tab_hash[:value] = tab[:value] if tab[:value]
tab_hash[:fontSize] = tab[:font_size] if tab[:font_size]
tab_hash[:fontColor] = tab[:font_color] if tab[:font_color]
tab_hash[:bold] = tab[:bold] if tab[:bold]
tab_hash[:italic] = tab[:italic] if tab[:italic]
tab_hash[:underline] = tab[:underline] if tab[:underline]
tab_hash[:selected] = tab[:selected] if tab[:selected]
tab_hash[:locked] = tab[:locked] || false
tab_hash[:list_items] = tab[:list_items] if tab[:list_items]
tab_hash[:groupName] = tab[:group_name] if tab.key?(:group_name)
tab_hash[:radios] = get_tabs(tab[:radios], options, index) if tab.key?(:radios)
tab_hash[:validationMessage] = tab[:validation_message] if tab[:validation_message]
tab_hash[:validationPattern] = tab[:validation_pattern] if tab[:validation_pattern]
tab_array << tab_hash
end
tab_array
end
# Internal: sets up the file ios array
#
# files - a hash of file params
#
# Returns the properly formatted ios used to build the file_params hash
def create_file_ios(files)
# UploadIO is from the multipart-post gem's lib/composite_io.rb:57
# where it has this documentation:
#
# ********************************************************************
# Create an upload IO suitable for including in the params hash of a
# Net::HTTP::Post::Multipart.
#
# Can take two forms. The first accepts a filename and content type, and
# opens the file for reading (to be closed by finalizer).
#
# The second accepts an already-open IO, but also requires a third argument,
# the filename from which it was opened (particularly useful/recommended if
# uploading directly from a form in a framework, which often save the file to
# an arbitrarily named RackMultipart file in /tmp).
#
# Usage:
#
# UploadIO.new('file.txt', 'text/plain')
# UploadIO.new(file_io, 'text/plain', 'file.txt')
# ********************************************************************
#
# There is also a 4th undocumented argument, opts={}, which allows us
# to send in not only the Content-Disposition of 'file' as required by
# DocuSign, but also the documentId parameter which is required as well
#
ios = []
files.each_with_index do |file, index|
ios << UploadIO.new(
file[:io] || file[:path],
file[:content_type] || 'application/pdf',
file[:name],
'Content-Disposition' => "file; documentid=#{index + 1}"
)
end
ios
end
# Internal: sets up the file_params for inclusion in a multipart post request
#
# ios - An array of UploadIO formatted file objects
#
# Returns a hash of files params suitable for inclusion in a multipart
# post request
def create_file_params(ios)
# multi-doc uploading capabilities, each doc needs to be it's own param
file_params = {}
ios.each_with_index do |io,index|
file_params.merge!("file#{index + 1}" => io)
end
file_params
end
# Internal: takes in an array of hashes of documents and calculates the
# documentId
#
# Returns a hash of documents that are to be uploaded
def get_documents(ios)
ios.each_with_index.map do |io, index|
{
documentId: "#{index + 1}",
name: io.original_filename
}
end
end
# Internal: takes in an array of server template ids and an array of the signers
# and sets up the composite template
#
# Takes an optional array of files, which consist of documents to be used instead of templates
#
# Returns an array of server template hashes
def get_composite_template(server_template_ids, signers, files)
composite_array = []
server_template_ids.each_with_index do |template_id, idx|
server_template_hash = {
sequence: (idx+1).to_s,
templateId: template_id,
templateRoles: get_template_roles(signers),
}
templates_hash = {
serverTemplates: [server_template_hash],
inlineTemplates: get_inline_signers(signers, (idx+1).to_s)
}
if files
document_hash = {
documentId: (idx+1).to_s,
name: "#{files[idx][:name] if files[idx]}"
}
templates_hash[:document] = document_hash
end
composite_array << templates_hash
end
composite_array
end
# Internal: takes signer info and the inline template sequence number
# and sets up the inline template
#
# Returns an array of signers
def get_inline_signers(signers, sequence)
signers_array = []
signers.each do |signer|
signers_hash = {
email: signer[:email],
name: signer[:name],
recipientId: signer[:recipient_id],
roleName: signer[:role_name],
clientUserId: signer[:client_id] || signer[:email],
requireSignOnPaper: signer[:require_sign_on_paper] || false,
tabs: {
textTabs: get_signer_tabs(signer[:text_tabs]),
radioGroupTabs: get_radio_signer_tabs(signer[:radio_group_tabs]),
checkboxTabs: get_signer_tabs(signer[:checkbox_tabs]),
numberTabs: get_signer_tabs(signer[:number_tabs]),
fullNameTabs: get_signer_tabs(signer[:fullname_tabs]),
dateTabs: get_signer_tabs(signer[:date_tabs]),
signHereTabs: get_sign_here_tabs(signer[:sign_here_tabs])
}
}
signers_array << signers_hash
end
template_hash = {sequence: sequence, recipients: { signers: signers_array }}
[template_hash]
end
# Internal sets up the Net::HTTP request
#
# uri - The fully qualified final URI
# post_body - The custom post body including the signers, etc
# file_params - Formatted hash of ios to merge into the post body
# headers - Allows for passing in custom headers
#
# Returns a request object suitable for embedding in a request
def initialize_net_http_multipart_post_request(uri, post_body, file_params, headers)
# Net::HTTP::Post::Multipart is from the multipart-post gem's lib/multipartable.rb
#
# path - The fully qualified URI for the request
# params - A hash of params (including files for uploading and a
# customized request body)
# headers={} - The fully merged, final request headers
# boundary - Optional: you can give the request a custom boundary
#
headers = headers.dup.merge(parts: {post_body: {'Content-Type' => 'application/json'}})
request = Net::HTTP::Post::Multipart.new(
uri.request_uri,
{ post_body: post_body }.merge(file_params),
headers
)
# DocuSign requires that we embed the document data in the body of the
# JSON request directly so we need to call '.read' on the multipart-post
# provided body_stream in order to serialize all the files into a
# compatible JSON string.
request.body = request.body_stream.read
request
end
# Public: creates an envelope from a document directly without a template
#
# file_io - Optional: an opened file stream of data (if you don't
# want to save the file to the file system as an incremental
# step)
# file_path - Required if you don't provide a file_io stream, this is
# the local path of the file you wish to upload. Absolute
# paths recommended.
# file_name - The name you want to give to the file you are uploading
# content_type - (for the request body) application/json is what DocuSign
# is expecting
# email[subject] - (Optional) short subject line for the email
# email[body] - (Optional) custom text that will be injected into the
# DocuSign generated email
# signers - A hash of users who should receive the document and need
# to sign it. More info about the options available for
# this method are documented above it's method definition.
# carbon_copies - An array of hashes that includes users names and email who
# should receive a copy of the document once it is complete.
# status - Options include: 'sent', 'created', 'voided' and determine
# if the envelope is sent out immediately or stored for
# sending at a later time
# customFields - (Optional) A hash of listCustomFields and textCustomFields.
# Each contains an array of corresponding customField hashes.
# For details, please see: http://bit.ly/1FnmRJx
# headers - Allows a client to pass in some headers
# wet_sign - (Optional) If true, the signer is allowed to print the
# document and sign it on paper. False if not defined.
#
# Returns a JSON parsed response object containing:
# envelopeId - The envelope's ID
# status - Sent, created, or voided
# statusDateTime - The date/time the envelope was created
# uri - The relative envelope uri
def create_envelope_from_document(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
recipients = if options[:certified_deliveries].nil? || options[:certified_deliveries].empty?
{ signers: get_signers(options[:signers]) }
else
{ certifiedDeliveries: get_signers(options[:certified_deliveries]) }
end
post_hash = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers]),
carbonCopies: get_carbon_copies(options[:carbon_copies],options[:signers].size)
},
eventNotification: get_event_notification(options[:event_notification]),
status: "#{options[:status]}",
customFields: options[:custom_fields]
}
post_hash[:enableWetSign] = options[:wet_sign] if options.has_key? :wet_sign
post_body = post_hash.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public: allows a template to be dynamically created with several options.
#
# files - An array of hashes of file parameters which will be used
# to create actual files suitable for upload in a multipart
# request.
#
# Options: io, path, name. The io is optional and would
# require creating a file_io object to embed as the first
# argument of any given file hash. See the create_file_ios
# method definition above for more details.
#
# email/body - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# email/subject - (Optional) sets the text in the email. Note: the envelope
# seems to override this, not sure why it needs to be
# configured here as well. I usually leave it blank.
# signers - An array of hashes of signers. See the
# get_signers method definition for options.
# description - The template description
# name - The template name
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the template's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_template(options={})
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
post_body = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
documents: get_documents(ios),
recipients: {
signers: get_signers(options[:signers], template: true)
},
envelopeTemplateDefinition: {
description: options[:description],
name: options[:name],
pageCount: 1,
password: '',
shared: false
}
}.to_json
uri = build_uri("/accounts/#{acct_id}/templates")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# TODO (2014-02-03) jonk => document
def get_template(template_id, options = {})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
uri = build_uri("/accounts/#{acct_id}/templates/#{template_id}")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', 'created', 'voided' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# template_id - The id of the template upon which we want to base this
# envelope
# template_roles - See the get_template_roles method definition for a list
# of options to pass. Note: for consistency sake we call
# this 'signers' and not 'templateRoles' when we build up
# the request in client code.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
#
# Returns a JSON parsed response body containing the envelope's:
# name - Name given above
# templateId - The auto-generated ID provided by DocuSign
# Uri - the URI where the template is located on the DocuSign servers
def create_envelope_from_template(options={})
content_type = { 'Content-Type' => 'application/json' }
content_type.merge(options[:headers]) if options[:headers]
post_body = {
status: options[:status],
emailBlurb: options[:email][:body],
emailSubject: options[:email][:subject],
templateId: options[:template_id],
enableWetSign: options[:wet_sign],
brandId: options[:brand_id],
eventNotification: get_event_notification(options[:event_notification]),
templateRoles: get_template_roles(options[:signers]),
customFields: options[:custom_fields],
allowReassign: options[:allow_reassign]
}.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Post.new(uri.request_uri, headers(content_type))
request.body = post_body
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public: create an envelope for delivery from a composite template
#
# headers - Optional hash of headers to merge into the existing
# required headers for a POST request.
# status - Options include: 'sent', or 'created' and
# determine if the envelope is sent out immediately or
# stored for sending at a later time
# email/body - Sets the text in the email body
# email/subject - Sets the text in the email subject line
# files - Sets documents to be used instead of inline or server templates
# signers - See get_template_roles/get_inline_signers for a list
# of options to pass.
# headers - Optional hash of headers to merge into the existing
# required headers for a multipart request.
# server_template_ids - Array of ids for templates uploaded to DocuSign. Templates
# will be added in the order they appear in the array.
#
# Returns a JSON parsed response body containing the envelope's:
# envelopeId - autogenerated ID provided by Docusign
# uri - the URI where the template is located on the DocuSign servers
# statusDateTime - The date/time the envelope was created
# status - Sent, created, or voided
def create_envelope_from_composite_template(options={})
file_params = {}
if options[:files]
ios = create_file_ios(options[:files])
file_params = create_file_params(ios)
end
post_hash = {
emailBlurb: "#{options[:email][:body] if options[:email]}",
emailSubject: "#{options[:email][:subject] if options[:email]}",
status: options[:status],
brandId: options[:brand_id],
eventNotification: get_event_notification(options[:event_notification]),
allowReassign: options[:allow_reassign],
compositeTemplates: get_composite_template(options[:server_template_ids], options[:signers], options[:files])
}
post_body = post_hash.to_json
uri = build_uri("/accounts/#{acct_id}/envelopes")
http = initialize_net_http_ssl(uri)
request = initialize_net_http_multipart_post_request(
uri, post_body, file_params, headers(options[:headers])
)
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public fetches custom fields for a document
#
# options[:envelope_id] - ID of the envelope which you want to send
# options[:document_id] - ID of the envelope which you want to send
#
# Returns the custom fields Hash.
def get_document_tabs(options)
content_type = { 'Content-Type' => 'application/json' }
uri = build_uri("/accounts/#{acct_id}/envelopes/#{options[:envelope_id]}/documents/#{options[:document_id]}/tabs")
http = initialize_net_http_ssl(uri)
request = Net::HTTP::Get.new(uri.request_uri, headers(content_type))
response = http.request(request)
generate_log(request, response, uri)
JSON.parse(response.body)
end
# Public marks an envelope as sent
#