Skip to content

Commit 1d86598

Browse files
committed
Eg 3, 4, 5, and 6
1 parent b148cf1 commit 1d86598

6 files changed

Lines changed: 488 additions & 520 deletions

File tree

app/eg003_list_envelopes.py

Lines changed: 110 additions & 124 deletions
Original file line numberDiff line numberDiff line change
@@ -1,126 +1,112 @@
1-
/**
2-
* @file
3-
* Example 003: List envelopes in the user's account
4-
* @author DocuSign
5-
*/
6-
7-
const docusign = require('docusign-esign')
8-
, dsConfig = require('../../ds_configuration.js').config
9-
, moment = require('moment')
10-
, path = require('path')
11-
, {promisify} = require('util') // http://2ality.com/2017/05/util-promisify.html
12-
;
13-
14-
const eg003ListEnvelopes = exports
15-
, eg = 'eg003' // This example reference.
16-
, mustAuthenticate = '/ds/mustAuthenticate'
17-
, minimumBufferMin = 3
18-
;
19-
20-
/**
21-
* Form page for this application
22-
*/
23-
eg003ListEnvelopes.getController = (req, res) => {
24-
// Check that the authentication token is ok with a long buffer time.
25-
// If needed, now is the best time to ask the user to authenticate
26-
// since they have not yet entered any information into the form.
27-
let tokenOK = req.dsAuthCodeGrant.checkToken();
28-
if (tokenOK) {
29-
res.render('pages/examples/eg003ListEnvelopes', {
30-
csrfToken: req.csrfToken(),
31-
title: "List envelopes",
32-
sourceFile: path.basename(__filename),
33-
sourceUrl: dsConfig.githubExampleUrl + path.basename(__filename),
34-
documentation: dsConfig.documentation + eg,
35-
showDoc: dsConfig.documentation
36-
});
37-
} else {
38-
// Save the current operation so it will be resumed after authentication
39-
req.dsAuthCodeGrant.setEg(req, eg);
40-
res.redirect(mustAuthenticate);
41-
}
42-
}
43-
44-
/**
45-
* List envelopes in the user's account
46-
* @param {object} req Request obj
47-
* @param {object} res Response obj
48-
*/
49-
eg003ListEnvelopes.createController = async (req, res) => {
50-
// Step 1. Check the token
51-
// At this point we should have a good token. But we
52-
// double-check here to enable a better UX to the user.
53-
let tokenOK = req.dsAuthCodeGrant.checkToken(minimumBufferMin);
54-
if (! tokenOK) {
55-
req.flash('info', 'Sorry, you need to re-authenticate.');
56-
// We could store the parameters of the requested operation
57-
// so it could be restarted automatically.
58-
// But since it should be rare to have a token issue here,
59-
// we'll make the user re-enter the form data after
60-
// authentication.
61-
req.dsAuthCodeGrant.setEg(req, eg);
62-
res.redirect(mustAuthenticate);
63-
}
64-
65-
// Step 2. Call the worker method
66-
let accountId = req.dsAuthCodeGrant.getAccountId()
67-
, dsAPIclient = req.dsAuthCodeGrant.getDSApi()
68-
, args = {
69-
dsAPIclient: dsAPIclient,
70-
accountId: accountId,
1+
"""Example 003: List envelopes in the user's account"""
2+
3+
from flask import render_template, url_for, redirect, session, flash, request
4+
from os import path
5+
import json
6+
from app import app, ds_config, views
7+
from datetime import datetime, timedelta
8+
from docusign_esign import *
9+
from docusign_esign.rest import ApiException
10+
11+
eg = "eg003" # reference (and url) for this example
12+
13+
def controller():
14+
"""Controller router using the HTTP method"""
15+
if request.method == 'GET':
16+
return get_controller()
17+
elif request.method == 'POST':
18+
return create_controller()
19+
else:
20+
return render_template('404.html'), 404
21+
22+
23+
def create_controller():
24+
"""
25+
1. Check the token
26+
2. Call the worker method
27+
3. Show results
28+
"""
29+
minimum_buffer_min = 3
30+
if views.ds_token_ok(minimum_buffer_min):
31+
# 2. Call the worker method
32+
args = {
33+
'account_id': session['ds_account_id'],
34+
'base_path': session['ds_base_path'],
35+
'ds_access_token': session['ds_access_token'],
7136
}
72-
, results = null
73-
;
74-
75-
try {
76-
results = await eg003ListEnvelopes.worker (args)
77-
}
78-
catch (error) {
79-
let errorBody = error && error.response && error.response.body
80-
// we can pull the DocuSign error code and message from the response body
81-
, errorCode = errorBody && errorBody.errorCode
82-
, errorMessage = errorBody && errorBody.message
83-
;
84-
// In production, may want to provide customized error messages and
85-
// remediation advice to the user.
86-
res.render('pages/error', {err: error, errorCode: errorCode, errorMessage: errorMessage});
87-
}
88-
if (results) {
89-
res.render('pages/example_done', {
90-
title: "List envelopes results",
91-
h1: "List envelopes results",
92-
message: `Results from the Envelopes::listStatusChanges method:`,
93-
json: JSON.stringify(results)
94-
});
95-
}
96-
}
97-
98-
/**
99-
* This function does the work of listing the envelopes
100-
* @param {object} args An object with the following elements: <br/>
101-
* <tt>dsAPIclient</tt>: The DocuSign API Client object, already set with an access token and base url <br/>
102-
* <tt>accountId</tt>: Current account Id <br/>
103-
*/
104-
// ***DS.worker.start ***DS.snippet.1.start
105-
eg003ListEnvelopes.worker = async (args) => {
106-
let envelopesApi = new docusign.EnvelopesApi(args.dsAPIclient)
107-
, listStatusChangesP = promisify(envelopesApi.listStatusChanges).bind(envelopesApi)
108-
, results = null
109-
;
110-
111-
// Step 1. List the envelopes
112-
// The Envelopes::listStatusChanges method has many options
113-
// See https://developers.docusign.com/esign-rest-api/reference/Envelopes/Envelopes/listStatusChanges
114-
115-
// The list status changes call requires at least a from_date OR
116-
// a set of envelopeIds. Here we filter using a from_date.
117-
// Here we set the from_date to filter envelopes for the last month
118-
// Use ISO 8601 date format
119-
let options = {fromDate: moment().subtract(30, 'days').format()};
120-
121-
// Exceptions will be caught by the calling function
122-
results = await listStatusChangesP(args.accountId, options);
123-
return results;
124-
}
125-
// ***DS.worker.end ***DS.snippet.1.end
37+
38+
try:
39+
results = worker(args)
40+
except ApiException as err:
41+
error_body_json = err and hasattr(err, 'body') and err.body
42+
# we can pull the DocuSign error code and message from the response body
43+
error_body = json.loads(error_body_json)
44+
error_code = error_body and 'errorCode' in error_body and error_body['errorCode']
45+
error_message = error_body and 'message' in error_body and error_body['message']
46+
# In production, may want to provide customized error messages and
47+
# remediation advice to the user.
48+
return render_template('error.html',
49+
err=err,
50+
error_code=error_code,
51+
error_message=error_message
52+
)
53+
return render_template("example_done.html",
54+
title="List envelopes results",
55+
h1="List envelopes results",
56+
message="Results from the Envelopes::listStatusChanges method:",
57+
json=json.dumps(json.dumps(results.to_dict()))
58+
)
59+
else:
60+
flash('Sorry, you need to re-authenticate.')
61+
# We could store the parameters of the requested operation
62+
# so it could be restarted automatically.
63+
# But since it should be rare to have a token issue here,
64+
# we'll make the user re-enter the form data after
65+
# authentication.
66+
session['eg'] = url_for(eg)
67+
return redirect(url_for('ds_must_authenticate'))
68+
69+
70+
def worker(args):
71+
"""
72+
1. Call the envelope status change method to list the envelopes
73+
that have changed in the last 10 days
74+
"""
75+
76+
# Exceptions will be caught by the calling function
77+
api_client = ApiClient()
78+
api_client.host = args['base_path']
79+
api_client.set_default_header("Authorization", "Bearer " + args['ds_access_token'])
80+
envelope_api = EnvelopesApi(api_client)
81+
82+
# The Envelopes::listStatusChanges method has many options
83+
# See https://developers.docusign.com/esign-rest-api/reference/Envelopes/Envelopes/listStatusChanges
84+
85+
# The list status changes call requires at least a from_date OR
86+
# a set of envelopeIds. Here we filter using a from_date.
87+
# Here we set the from_date to filter envelopes for the last month
88+
# Use ISO 8601 date format
89+
from_date = (datetime.utcnow() - timedelta(days=10)).isoformat()
90+
results = envelope_api.list_status_changes(args['account_id'], from_date = from_date)
91+
92+
return results
93+
94+
# ***DS.worker.end ***DS.snippet.1.end
95+
96+
97+
def get_controller():
98+
"""responds with the form for the example"""
99+
100+
if views.ds_token_ok():
101+
return render_template("eg003_list_envelopes.html",
102+
title="List changed envelopes",
103+
source_file=path.basename(__file__),
104+
source_url=ds_config.DS_CONFIG['github_example_url'] + path.basename(__file__),
105+
documentation=ds_config.DS_CONFIG['documentation'] + eg,
106+
show_doc=ds_config.DS_CONFIG['documentation'],
107+
)
108+
else:
109+
# Save the current operation so it will be resumed after authentication
110+
session['eg'] = url_for(eg)
111+
return redirect(url_for('ds_must_authenticate'))
126112

0 commit comments

Comments
 (0)