Commit 72c20681 authored by Volkov Gherman's avatar Volkov Gherman

Merge branch 'feature/docusign_app' into 'develop'

Feature/docusign_app

See merge request !2
parents a0d62440 3a90cc19
......@@ -4,3 +4,8 @@ DATABASE_USER='your database owner'
DATABASE_PASSWORD='your database password'
DATABASE_HOST='your database host'
DATABASE_PORT='your database port'
DOCUSIGN_INTEGRATION_KEY='your integation key'
EMAIL_HOST_USER='host user mail'
EMAIL_HOST_PASSWORD='host user password'
\ No newline at end of file
......@@ -151,4 +151,5 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
.DS_Store
docusign_test_app-python/
private.key
from os import path
import re
demo_docs_path = path.abspath(path.join(path.dirname(path.realpath(__file__)), "static/demo_documents"))
# Pattern for validating signer name and email
pattern = re.compile("([^\w \-\@\.\,])+")
signer_client_id = 1000 # Used to indicate that the signer will use embedded
# signing. Represents the signer"s userId within
# your application.
authentication_method = "None" # How is this application authenticating
minimum_buffer_min = 3
# Template name for create template example
template_name = "Example Signer and CC template v2"
# Name of static doc file
doc_file = "World_Wide_Corp_fields.pdf"
# Name of static pdf file
pdf_file = "World_Wide_Corp_lorem.pdf"
# Base uri for callback function
base_uri_suffix = "/restapi"
# Default languages for brand
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"
}
# Default settings for updating and creating permissions
settings = {
"useNewDocuSignExperienceInterface": "optional",
"allowBulkSending": "true",
"allowEnvelopeSending": "true",
"allowSignerAttachments": "true",
"allowTaggingInSendAndCorrect": "true",
"allowWetSigningOverride": "true",
"allowedAddressBookAccess": "personalAndShared",
"allowedTemplateAccess": "share",
"enableRecipientViewingNotifications": "true",
"enableSequentialSigningInterface": "true",
"receiveCompletedSelfSignedDocumentsAsEmailLinks": "false",
"signingUiVersion": "v2",
"useNewSendingInterface": "true",
"allowApiAccess": "true",
"allowApiAccessToAccount": "true",
"allowApiSendingOnBehalfOfOthers": "true",
"allowApiSequentialSigning": "true",
"enableApiRequestLogging": "true",
"allowDocuSignDesktopClient": "false",
"allowSendersToSetRecipientEmailLanguage": "true",
"allowVaulting": "false",
"allowedToBeEnvelopeTransferRecipient": "true",
"enableTransactionPointIntegration": "false",
"powerFormRole": "admin",
"vaultingMode": "none"
}
API_TYPE = {
"ESIGNATURE": "eSignature",
"MONITOR": "Monitor",
"CLICK": "Click",
"ROOMS": "Rooms",
"ADMIN": "Admin"
}
import base64
from os import path
from docusign_esign import EnvelopesApi, EnvelopeDefinition, Document, Signer, CarbonCopy, SignHere, \
Tabs, Recipients
from ...consts import demo_docs_path, pattern
from ...jwt_helpers import create_api_client
class Eg002SigningViaEmailController:
@classmethod
def worker(cls, args, doc_docx_path, doc_pdf_path):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
# 1. Create the envelope request object
envelope_definition = cls.make_envelope(envelope_args, doc_docx_path, doc_pdf_path)
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
# 2. call Envelopes::create API method
# Exceptions will be caught by the calling function
envelopes_api = EnvelopesApi(api_client)
results = envelopes_api.create_envelope(account_id=args["account_id"], envelope_definition=envelope_definition)
envelope_id = results.envelope_id
return {"envelope_id": envelope_id}
@classmethod
def make_envelope(cls, args, doc_docx_path, doc_pdf_path):
"""
Creates envelope
Document 1: An HTML document.
Document 2: A Word .docx document.
Document 3: A PDF document.
DocuSign will convert all of the documents to the PDF format.
The recipients" field tags are placed using <b>anchor</b> strings.
"""
# document 1 (html) has sign here anchor tag **signature_1**
# document 2 (docx) has sign here anchor tag /sn1/
# document 3 (pdf) has sign here anchor tag /sn1/
#
# The envelope has two recipients.
# recipient 1 - signer
# recipient 2 - cc
# The envelope will be sent first to the signer.
# After it is signed, a copy is sent to the cc person.
# create the envelope definition
env = EnvelopeDefinition(
email_subject="Please sign this document set"
)
doc1_b64 = base64.b64encode(bytes(cls.create_document1(args), "utf-8")).decode("ascii")
# read files 2 and 3 from a local directory
# The reads could raise an exception if the file is not available!
with open(path.join(demo_docs_path, doc_docx_path), "rb") as file:
doc2_docx_bytes = file.read()
doc2_b64 = base64.b64encode(doc2_docx_bytes).decode("ascii")
with open(path.join(demo_docs_path, doc_pdf_path), "rb") as file:
doc3_pdf_bytes = file.read()
doc3_b64 = base64.b64encode(doc3_pdf_bytes).decode("ascii")
# Create the document models
document1 = Document( # create the DocuSign document object
document_base64=doc1_b64,
name="Order acknowledgement", # can be different from actual file name
file_extension="html", # many different document types are accepted
document_id="1" # a label used to reference the doc
)
document2 = Document( # create the DocuSign document object
document_base64=doc2_b64,
name="Battle Plan", # can be different from actual file name
file_extension="docx", # many different document types are accepted
document_id="2" # a label used to reference the doc
)
document3 = Document( # create the DocuSign document object
document_base64=doc3_b64,
name="Lorem Ipsum", # can be different from actual file name
file_extension="pdf", # many different document types are accepted
document_id="3" # a label used to reference the doc
)
# The order in the docs array determines the order in the envelope
env.documents = [document1, document2, document3]
# Create the signer recipient model
signer1 = Signer(
email=args["signer_email"],
name=args["signer_name"],
recipient_id="1",
routing_order="1"
)
# routingOrder (lower means earlier) determines the order of deliveries
# to the recipients. Parallel routing order is supported by using the
# same integer as the order for two or more recipients.
# create a cc recipient to receive a copy of the documents
cc1 = CarbonCopy(
email=args["cc_email"],
name=args["cc_name"],
recipient_id="2",
routing_order="2"
)
# Create signHere fields (also known as tabs) on the documents,
# We"re using anchor (autoPlace) positioning
#
# The DocuSign platform searches throughout your envelope"s
# documents for matching anchor strings. So the
# signHere2 tab will be used in both document 2 and 3 since they
# use the same anchor string for their "signer 1" tabs.
sign_here1 = SignHere(
anchor_string="**signature_1**",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
sign_here2 = SignHere(
anchor_string="/sn1/",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
# Add the tabs model (including the sign_here tabs) to the signer
# The Tabs object wants arrays of the different field/tab types
signer1.tabs = Tabs(sign_here_tabs=[sign_here1, sign_here2])
# Add the recipients to the envelope object
recipients = Recipients(signers=[signer1], carbon_copies=[cc1])
env.recipients = recipients
# Request that the envelope be sent by setting |status| to "sent".
# To request that the envelope be created as a draft, set to "created"
env.status = args["status"]
return env
@classmethod
def create_document1(cls, args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
color: darkblue;margin-bottom: 0;">World Wide Corp</h1>
<h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;
color: darkblue;">Order Processing Division</h2>
<h4>Ordered by {args["signer_name"]}</h4>
<p style="margin-top:0em; margin-bottom:0em;">Email: {args["signer_email"]}</p>
<p style="margin-top:0em; margin-bottom:0em;">Copy to: {args["cc_name"]}, {args["cc_email"]}</p>
<p style="margin-top:3em;">
Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie.
Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée.
Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice.
Donut jujubes oat cake jelly-o.
Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.
</p>
<!-- Note the anchor tag for the signature field is in white. -->
<h3 style="margin-top:3em;">Agreed: <span style="color:white;">**signature_1**/</span></h3>
</body>
</html>
"""
from core.settings import DOCUSIGN_PRIVATE_KEY_PATH, DOCUSIGN_DOCUMENT_PATH_DOCX, DOCUSIGN_DOCUMENT_PATH_PDF
DS_JWT = {
"ds_client_id": "a2ecda0a-ebda-48f6-b784-a75a51608e07",
"ds_impersonated_user_id": "6c83e6cd-4cac-4aeb-a20e-22ab78b1f020", # The id of the user.
"private_key_file": DOCUSIGN_PRIVATE_KEY_PATH, # Create a new file in your repo source folder named private.key then copy and paste your RSA private key there and save it.
"authorization_server": "account-d.docusign.com",
"doc_docx": DOCUSIGN_DOCUMENT_PATH_DOCX,
"doc_pdf": DOCUSIGN_DOCUMENT_PATH_PDF,
}
\ No newline at end of file
from .jwt_helper import create_api_client, get_jwt_token, get_private_key
from docusign_esign import ApiClient
from os import path
def get_jwt_token(private_key, scopes, auth_server, client_id, impersonated_user_id):
"""Get the jwt token"""
api_client = ApiClient()
api_client.set_base_path(auth_server)
response = api_client.request_jwt_user_token(
client_id=client_id,
user_id=impersonated_user_id,
oauth_host_name=auth_server,
private_key_bytes=private_key,
expires_in=4000,
scopes=scopes
)
return response
def get_private_key(private_key_path):
"""
Check that the private key present in the file and if it is, get it from the file.
In the opposite way get it from config variable.
"""
private_key_file = path.abspath(private_key_path)
if path.isfile(private_key_file):
with open(private_key_file) as private_key_file:
private_key = private_key_file.read()
else:
private_key = private_key_path
return private_key
def create_api_client(base_path, access_token):
"""Create api client and construct API headers"""
api_client = ApiClient()
api_client.host = base_path
api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {access_token}")
return api_client
import sys
import subprocess
from docusign_esign import ApiClient
from docusign_esign.client.api_exception import ApiException
from .docusign_app.jwt_helpers import get_jwt_token, get_private_key
from .docusign_app.eSignature.examples.eg002_signing_via_email import Eg002SigningViaEmailController
from .docusign_app.jwt_config import DS_JWT
# pip install DocuSign SDK
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'docusign_esign'])
SCOPES = [
"signature", "impersonation"
]
def get_consent_url():
url_scopes = "+".join(SCOPES)
# Construct consent URL
redirect_uri = "https://developers.docusign.com/platform/auth/consent"
consent_url = f"https://{DS_JWT['authorization_server']}/oauth/auth?response_type=code&" \
f"scope={url_scopes}&client_id={DS_JWT['ds_client_id']}&redirect_uri={redirect_uri}"
return consent_url
def get_token(private_key, api_client):
# Call request_jwt_user_token method
token_response = get_jwt_token(private_key, SCOPES, DS_JWT["authorization_server"], DS_JWT["ds_client_id"],
DS_JWT["ds_impersonated_user_id"])
access_token = token_response.access_token
# Save API account ID
user_info = api_client.get_user_info(access_token)
accounts = user_info.get_accounts()
api_account_id = accounts[0].account_id
base_path = accounts[0].base_uri + "/restapi"
return {"access_token": access_token, "api_account_id": api_account_id, "base_path": base_path}
def get_args(api_account_id, access_token, base_path):
signer_email = input("Please enter the signer's email address: ")
signer_name = input("Please enter the signer's name: ")
cc_email = input("Please enter the cc email address: ")
cc_name = input("Please enter the cc name: ")
envelope_args = {
"signer_email": signer_email,
"signer_name": signer_name,
"cc_email": cc_email,
"cc_name": cc_name,
"status": "sent",
}
args = {
"account_id": api_account_id,
"base_path": base_path,
"access_token": access_token,
"envelope_args": envelope_args
}
return args
def run_example(private_key, api_client):
jwt_values = get_token(private_key, api_client)
args = get_args(jwt_values["api_account_id"], jwt_values["access_token"], jwt_values["base_path"])
envelope_id = Eg002SigningViaEmailController.worker(args, DS_JWT["doc_docx"], DS_JWT["doc_pdf"])
print("Your envelope has been sent.")
print(envelope_id)
def main():
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
api_client.set_oauth_host_name(DS_JWT["authorization_server"])
private_key = get_private_key(DS_JWT["private_key_file"]).encode("ascii").decode("utf-8")
try:
run_example(private_key, api_client)
except ApiException as err:
body = err.body.decode('utf8')
if "consent_required" in body:
consent_url = get_consent_url()
print("Open the following URL in your browser to grant consent to the application:")
print(consent_url)
consent_granted = input("Consent granted? Select one of the following: \n 1)Yes \n 2)No \n")
if consent_granted == "1":
run_example(private_key, api_client)
else:
sys.exit("Please grant consent")
import sys
from docusign_esign import ApiClient, ApiException
from api.jwt_console import get_consent_url, get_token
from api.docusign_app.jwt_helpers import get_private_key
from api.models import DocumentNDA
from api.docusign_app.jwt_config import DS_JWT
from api.docusign_app.eSignature.examples.eg002_signing_via_email import Eg002SigningViaEmailController
def get_args(api_account_id, access_token, base_path):
document = DocumentNDA.objects.last()
signer_email = document.owner_email
signer_name = document.owner_name
cc_email = 'example@mail.com'
cc_name = 'name'
envelope_args = {
"signer_email": signer_email,
"signer_name": signer_name,
"cc_email": cc_email,
"cc_name": cc_name,
"status": "sent",
}
args = {
"account_id": api_account_id,
"base_path": base_path,
"access_token": access_token,
"envelope_args": envelope_args
}
return args
def run_docusign(private_key, api_client):
jwt_values = get_token(private_key, api_client)
args = get_args(jwt_values["api_account_id"], jwt_values["access_token"], jwt_values["base_path"])
envelope_id = Eg002SigningViaEmailController.worker(args, DS_JWT["doc_docx"], DS_JWT["doc_pdf"])
print("Your envelope has been sent.")
print(envelope_id)
def send_docusign_email():
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
api_client.set_oauth_host_name(DS_JWT["authorization_server"])
private_key = get_private_key(DS_JWT["private_key_file"]).encode("ascii").decode("utf-8")
try:
run_docusign(private_key, api_client)
except ApiException as err:
body = err.body.decode('utf8')
if "consent_required" in body:
consent_url = get_consent_url()
print("Open the following URL in your browser to grant consent to the application:")
print(consent_url)
consent_granted = input("Consent granted? Select one of the following: \n 1)Yes \n 2)No \n")
if consent_granted == "1":
run_docusign(private_key, api_client)
else:
sys.exit("Please grant consent")
return {'status': 'success'}
......@@ -10,22 +10,31 @@
crossorigin="anonymous"></script>
</head>
<body>
<form id='form' method="POST">
<h1 style="text-align: center; margin-top: 10vh" class="display-6">DocuSign Esign <br>
<small class="text-muted">Подпишите документ с помощью docusign</small>
</h1>
<main style="background: lightgray; width: 70vh; margin-inline: auto">
<form style="width: 70vh; margin: 10vh auto; padding: 20px 30px;" id='form' method="POST">
<div class="form-group">
<label for="formGroupExampleInput">Введите свое имя</label>
<input name="owner_name" type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input" required>
<input name="owner_name" type="text" class="form-control" id="formGroupExampleInput" placeholder="Вася"
required>
</div>
<div class="form-group">
<label for="formGroupExampleInput2">Введите свою фамилию</label>
<input name="owner_surname" type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input" required>
<input name="owner_surname" type="text" class="form-control" id="formGroupExampleInput2"
placeholder="Пупкин" required>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Введите свой Email</label>
<input name="owner_email" type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
placeholder="Enter email" required>
<input name="owner_email" type="email" class="form-control" id="exampleInputEmail1"
aria-describedby="emailHelp"
placeholder="vasyaPupkin@.mail.com" required>
</div>
<button type="submit" class="btn btn-primary">Подтвердить и подписать документ</button>
</form>
<button type="submit" class="btn btn-primary">Подтвердить и подписать документ
</button>
</form>
</main>
</body>
<script>
......
from http.client import HTTPException
from django.shortcuts import redirect
from rest_framework.renderers import TemplateHTMLRenderer
from rest_framework.response import Response
from rest_framework.views import APIView
from api.serializers import DocumentNDASerializer
from api.services import send_docusign_email
def index_view(request):
return redirect('send_email')
class IndexView(APIView):
class SendDocumentView(APIView):
renderer_classes = [TemplateHTMLRenderer]
template_name = 'index.html'
def get(self, request):
return Response(template_name=self.template_name)
return Response(template_name=self.template_name, status=200)
def post(self, request):
serializer = DocumentNDASerializer(data=request.data)
if serializer.is_valid():
serializer.save()
# отправка в докусайн
try:
send_docusign_email()
return Response(status=200, data=serializer.data)
except HTTPException as e:
return Response({'error': e}, status=503)
return Response({'error': 'Bad Request'}, status=400)
......@@ -14,12 +14,13 @@ import os
from pathlib import Path
from dotenv import load_dotenv
load_dotenv()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/
......@@ -31,7 +32,6 @@ DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
......@@ -83,7 +83,6 @@ REST_FRAMEWORK = {
WSGI_APPLICATION = 'core.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.2/ref/settings/#databases
......@@ -98,7 +97,6 @@ DATABASES = {
},
}
# Password validation
# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators
......@@ -123,7 +121,6 @@ CORS_ORIGIN_WHITELIST = [
'http://127.0.0.1:8000/api/v1/'
]
# Internationalization
# https://docs.djangoproject.com/en/4.2/topics/i18n/
......@@ -135,16 +132,31 @@ USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.2/howto/static-files/
STATIC_URL = 'static/'
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'demo')
MEDIA_URL = '/demo/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'api/docusign_app/static')
MEDIA_URL = '/api/docusign_app/static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
DOCUSIGN_INTEGRATION_KEY = os.getenv('DOCUSIGN_INTEGRATION_KEY')
DOCUSIGN_PRIVATE_KEY_PATH = os.path.join(BASE_DIR, 'api/docusign_app/private.key')
DOCUSIGN_DOCUMENT_PATH_DOCX = os.path.join(BASE_DIR, 'api/docusign_app/static/demo_documents'
'/World_Wide_Corp_Battle_Plan_Trafalgar.docx')
DOCUSIGN_DOCUMENT_PATH_PDF = os.path.join(BASE_DIR, 'api/docusign_app/static/demo_documents/World_Wide_Corp_lorem.pdf')
DOCUSIGN_AUTH_SERVER = 'https://account-d.docusign.com'
DOCUSIGN_API_SERVER = 'https://api-d.docusign.com'
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')
EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')
EMAIL_PORT = 587
APPEND_SLASH = False
......@@ -17,10 +17,11 @@ Including another URLconf
from django.contrib import admin
from django.urls import path
from api.views import IndexView
from api.views import index_view, SendDocumentView
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', IndexView.as_view()),
path('', index_view, name='index'),
path('api/v1/', SendDocumentView.as_view(), name='send_email'),
]
......@@ -3,4 +3,3 @@ djangorestframework==3.14.*
psycopg2-binary==2.9.*
python-dotenv==1.0.*
docusign-esign==3.22.*
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment