Skip to content

Brands apply to template #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 165 additions & 0 deletions app/eg024_brand_creating.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,165 @@
"""Example 024: Creating a brand"""

import json
from os import path

from docusign_esign import ApiClient, AccountsApi, Brand
from docusign_esign.client.api_exception import ApiException
from flask import render_template, url_for, redirect, session, flash, request

from app import app, ds_config, views

eg = 'eg024' # reference and url for this example

LANGUAGES = {
"Arabic": "ar",
"Armenian": "hy",
"Bahasa Indonesia": "id",
"Bahasa Malay": "ms",
"Bulgarian": "bg",
"Chinese Simplified": "zh_CN",
"Chinese Traditional": "zh_TW",
"Croatian": "hr",
"Czech": "cs",
"Danish": "da",
"Dutch": "nl",
"English UK": "en_GB",
"English US": "en",
"Estonian": "et",
"Farsi": "fa",
"Finnish": "fi",
"French": "fr",
"French Canada": "fr_CA",
"German": "de",
"Greek": "el",
"Hebrew": "he",
"Hindi": "hi",
"Hungarian": "hu",
"Italian": "it",
"Japanese": "ja",
"Korean": "ko",
"Latvian": "lv",
"Lithuanian": "lt",
"Norwegian": "no",
"Polish": "pl",
"Portuguese": "pt",
"Portuguese Brasil": "pt_BR",
"Romanian": "ro",
"Russian": "ru",
"Serbian": "sr",
"Slovak": "sk",
"Slovenian": "sl",
"Spanish": "es",
"Spanish Latin America": "es_MX",
"Swedish": "sv",
"Thai": "th",
"Turkish": "tr",
"Ukrainian": "uk",
"Vietnamese": "vi"
}


def controller():
"""Controller router using the HTTP method"""
if request.method == "GET":
return get_controller()
elif request.method == "POST":
return create_controller()
else:
return render_template("404.html"), 404


def create_controller():
"""
1. Check the token
2. Call the worker method
3. Render response
"""
minimum_buffer_min = 3
if views.ds_token_ok(minimum_buffer_min):
# Step 1: Obtain your OAuth token
args = {
'account_id': '213', # represent your {ACCOUNT_ID}
'base_path': session['ds_base_path'],
'access_token': session['ds_access_token'], # represent your {ACCESS_TOKEN}
'brand_name': request.form.get('brand_name'),
'default_language': request.form.get('default_language')
}
try:
# Step 2: Call the worker method to create a new brand
response = worker(args)
brand_id = response.brands[0].brand_id
app.logger.info(f"Brand has been created. Brand id {brand_id}")

# Step 3: Render response
return render_template('example_done.html',
title='Brand creating',
h1='Brand creating',
message=f"""The brand has been created and sent!<br/>
Brand ID {brand_id}."""
)

except ApiException as err:
error_body_json = err and hasattr(err, 'body') and err.body
# We can pull the DocuSign error code and message from the response body
error_body = json.loads(error_body_json)
error_code = error_body and 'errorCode' in error_body and error_body['errorCode']
error_message = error_body and "message" in error_body and error_body["message"]
# In production, you may want to provide customized error messages and
# remediation advice to the user
return render_template('error.html',
err=err,
error_code=error_code,
error_message=error_message
)

else:
flash("Sorry, you need to re-authenticate.")
# We could store the parameters of the requested operation so it could be restarted
# automatically. But since it should be rare to have a token issue here,
# we'll make the user re-enter the form data after authentication
session["eg"] = url_for(eg)
return redirect(url_for("ds_must_authenticate"))


def worker(args):
"""
1. Create api client with headers
2. Create a brand object
3. Post the brand using SDK
"""

# Step 1: create API client
api_client = ApiClient()
api_client.host = args['base_path']
api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {args['access_token']}")

# Step 2: Create a brand object
brand = Brand(
brand_name=args['brand_name'],
default_brand_language=args['default_language'],
)

# Step 3: a) Call the eSignature SDK
# b) Display the JSON response
account_api = AccountsApi(api_client)
response = account_api.create_brand(account_id=args['account_id'], brand=brand)
return response


def get_controller():
"""Responds with the form for the example"""

if views.ds_token_ok():
return render_template("eg024_brand_creating.html",
title="Brand creating",
source_file=path.basename(__file__),
source_url=ds_config.DS_CONFIG["github_example_url"] + path.basename(__file__),
documentation=ds_config.DS_CONFIG["documentation"] + eg,
show_doc=ds_config.DS_CONFIG["documentation"],
languages=LANGUAGES
)
else:
# Save the current operation so it will be resumed after authentication
session["eg"] = url_for(eg)
return redirect(url_for("ds_must_authenticate"))
212 changes: 212 additions & 0 deletions app/eg025_brands_apply_to_envelope.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,212 @@
"""Example 025: Applying a brand to an envelope"""

from flask import render_template, url_for, redirect, session, flash, request
from os import path
from app import app, ds_config, views
import base64
import json
import re
from docusign_esign import ApiClient, EnvelopesApi, Document, Signer, SignHere, EnvelopeDefinition, Tabs, Recipients, \
AccountsApi
from docusign_esign.client.api_exception import ApiException

eg = 'eg025' # reference and url for this example
demo_docs_path = path.abspath(path.join(path.dirname(path.realpath(__file__)), "static/demo_documents"))
doc_file = "World_Wide_Corp_lorem.pdf"


def controller():
"""Controller router using the HTTP method"""
if request.method == "GET":
return get_controller()
elif request.method == "POST":
return create_controller()
else:
return render_template("404.html"), 404


def create_controller():
"""
1. Check the token
2. Call the worker method
3. Render response
"""
minimum_buffer_min = 3
if views.ds_token_ok(minimum_buffer_min):

# More data validation would be a good idea here
# Strip anything other than the characters listed
pattern = re.compile("([^\w \-\@\.\,])+")
signer_email = pattern.sub("", request.form.get("signer_email"))
signer_name = pattern.sub("", request.form.get("signer_name"))

# Step 1: Obtain your OAuth token
args = {
'account_id': session['ds_account_id'], # represent your {ACCOUNT_ID}
'base_path': session['ds_base_path'],
'access_token': session['ds_access_token'], # represent your {ACCESS_TOKEN}
'envelope_args': {
'signer_name': signer_name,
'signer_email': signer_email,
'brand_id': request.form.get('brand')
}

}
try:
# Step 2: Call the worker method to apply brand to the envelope
response = worker(args)
envelope_id = response.envelope_id
app.logger.info(f"Brand has been applied to envelope. Envelope id {envelope_id}")

# Step 3: Render a response
return render_template('example_done.html',
title='Brand applying to envelope',
h1='Brand applying to envelope',
message=f"""The brand has been applied to envelope!<br/>
Envelope ID: {envelope_id}."""
)

except ApiException as err:
error_body_json = err and hasattr(err, 'body') and err.body
# We can pull the DocuSign error code and message from the response body
error_body = json.loads(error_body_json)
error_code = error_body and 'errorCode' in error_body and error_body['errorCode']
error_message = error_body and "message" in error_body and error_body["message"]
# In production, you may want to provide customized error messages and
# remediation advice to the user
return render_template('error.html',
err=err,
error_code=error_code,
error_message=error_message
)

else:
flash("Sorry, you need to re-authenticate.")
# We could store the parameters of the requested operation so it could be restarted
# automatically. But since it should be rare to have a token issue here,
# we'll make the user re-enter the form data after authentication
session["eg"] = url_for(eg)
return redirect(url_for("ds_must_authenticate"))


def worker(args):
"""
1. Call create_api_client method
2. Call make_envelope method
3. Apply the brand to the envelope using SDK
"""

# Step 1: Call create_api_client method
api_client = create_api_client(args)

# Step 2: Call make_envelope method
envelope_api = EnvelopesApi(api_client)
envelope_definition = make_envelope(args['envelope_args'])

# Step 3: Apply the brand to the envelope using SDK
response = envelope_api.create_envelope(args['account_id'], envelope_definition=envelope_definition)

return response


def create_api_client(args):
"""Create api client and construct API headers"""
api_client = ApiClient()
api_client.host = args['base_path']
api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {args['access_token']}")

return api_client


def make_envelope(args):
"""
Creates envelope
"""

# Open example file
with open(path.join(demo_docs_path, doc_file), "rb") as file:
content_bytes = file.read()
base64_file_content = base64.b64encode(content_bytes).decode("ascii")

document = Document(
document_base64=base64_file_content,
name='lorem',
file_extension='pdf',
document_id=1
)

signer = Signer(
email=args['signer_email'],
name=args['signer_name'],
recipient_id="1",
routing_order="1"
)

sign_here = SignHere(
anchor_string='/sn1/',
anchor_units='pixels',
anchor_y_offset="572",
anchor_x_offset="75"
)

signer.tabs = Tabs(sign_here_tabs=[sign_here])

envelope_definition = EnvelopeDefinition(
email_subject='Please Sign',
documents=[document],
recipients=Recipients(signers=[signer]),
status='sent',
brand_id=args['brand_id'],
)

return envelope_definition


def get_brands():
"""Retrieve all brands using the AccountBrands::List"""
args = {
'account_id': session['ds_account_id'], # represent your {ACCOUNT_ID}
'base_path': session['ds_base_path'],
'access_token': session['ds_access_token'], # represent your {ACCESS_TOKEN}

}
api_client = create_api_client(args)
try:
account_api = AccountsApi(api_client)
response = account_api.list_brands(args['account_id'])
return response.brands
except ApiException as err:
error_body_json = err and hasattr(err, 'body') and err.body
# We can pull the DocuSign error code and message from the response body
error_body = json.loads(error_body_json)
error_code = error_body and 'errorCode' in error_body and error_body['errorCode']
error_message = error_body and "message" in error_body and error_body["message"]
# In production, you may want to provide customized error messages and
# remediation advice to the user
return render_template('error.html',
err=err,
error_code=error_code,
error_message=error_message
)


def get_controller():
"""Responds with the form for the example"""
if views.ds_token_ok():
# Get all brands to render it in the template
brands = get_brands()

return render_template("eg025_brands_apply_to_envelope.html",
title="Applying a brand to a template",
source_file=path.basename(__file__),
source_url=ds_config.DS_CONFIG["github_example_url"] + path.basename(__file__),
documentation=ds_config.DS_CONFIG["documentation"] + eg,
show_doc=ds_config.DS_CONFIG["documentation"],
brands=brands,
signer_name=ds_config.DS_CONFIG["signer_name"],
signer_email=ds_config.DS_CONFIG["signer_email"]
)
else:
# Save the current operation so it will be resumed after authentication
session["eg"] = url_for(eg)
return redirect(url_for("ds_must_authenticate"))
Loading