Exemplo n.º 1
0
def get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        documents_ok = 'envelope_documents' in session
        document_options = []
        if documents_ok:
            # Prepare the select items
            envelope_documents = session["envelope_documents"]
            document_options = map(
                lambda item: {
                    'text': item['name'],
                    'document_id': item['document_id']
                }, envelope_documents['documents'])

        return render_template(
            "eg007_envelope_get_doc.html",
            title="Download an Envelope's Document",
            envelope_ok='envelope_id' in session,
            documents_ok=documents_ok,
            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'],
            document_options=document_options)
    else:
        # Save the current operation so it will be resumed after authentication
        session['eg'] = url_for(eg)
        return redirect(url_for('ds_must_authenticate'))
Exemplo n.º 2
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Redirect the user to the signing ceremony
    """
    minimum_buffer_min = 3
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile('([^\w \-\@\.\,])+')
        signer_email = pattern.sub('', request.form.get('signer_email'))
        signer_name = pattern.sub('', request.form.get('signer_name'))
        envelope_args = {
            'signer_email': signer_email,
            'signer_name': signer_name,
            'signer_client_id': signer_client_id,
            'ds_return_url': url_for('ds_return', _external=True),
        }
        args = {
            'account_id': session['ds_account_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
            'envelope_args': envelope_args
        }

        try:
            results = worker(args)
        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, 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)
        if results:
            # Redirect the user to the Signing Ceremony
            # Don't use an iFrame!
            # State can be stored/recovered using the framework's session or a
            # query parameter on the returnUrl (see the makeRecipientViewRequest method)
            return redirect(results["redirect_url"])

    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'))
Exemplo n.º 3
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Show results
    """
    minimum_buffer_min = 3
    token_ok = views.ds_token_ok(minimum_buffer_min)
    if token_ok and 'envelope_id' in session:
        # 2. Call the worker method
        args = {
            'account_id': session['ds_account_id'],
            'envelope_id': session['envelope_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
        }

        try:
            results = worker(args)
        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, 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)
        return render_template(
            "example_done.html",
            title="Get envelope status results",
            h1="Get envelope status results",
            message="Results from the Envelopes::get method:",
            json=json.dumps(json.dumps(results.to_dict())))
    elif not token_ok:
        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'))
    elif not 'envelope_id' in session:
        return render_template(
            "eg004_envelope_info.html",
            title="Envelope information",
            envelope_ok=False,
            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'],
        )
def get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        form = ClientForm()

        if form.validate() == False:
            flash:('All fields are required.')

        return render_template('form.html', form = form)
    else:
        # Save the current operation so it will be resumed after authentication
        session["eg"] = url_for(eg)
        return redirect(url_for("ds_login"))
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    """
    minimum_buffer_min = 3
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        args = {
            'account_id': session['ds_account_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token']
        }

        try:
            results = worker(args)
        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, 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
                                   )
        if results:
            # Save the templateId in the session so they can be used in future examples
            session['template_id'] = results['template_id']
            msg = "The template has been created!" if results['created_new_template'] else \
                  "Done. The template already existed in your account."
            return render_template('example_done.html',
                        title="Template results",
                        h1="Template results",
                        message=f"""{msg}<br/>Template name: {results['template_name']}, 
                        ID {results['template_id']}."""
            )
    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 get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        return render_template("eg008_create_template.html",
                               title="Create 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'],
        )
    else:
        # Save the current operation so it will be resumed after authentication
        session['eg'] = url_for(eg)
        return redirect(url_for('ds_must_authenticate'))
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Show results
    """
    minimum_buffer_min = 3
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        args = {
            'account_id': session['ds_account_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
        }

        try:
            results = worker(args)
        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, 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
                                   )
        return render_template("example_done.html",
                                title="List envelopes results",
                                h1="List envelopes results",
                                message="Results from the Envelopes::listStatusChanges method:",
                                json=json.dumps(json.dumps(results.to_dict()))
                                )
    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 get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        return render_template("eg011_embedded_sending.html",
                               title="Embedded Sending",
                               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"],
                               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)
        print(session["eg"])
        return redirect(url_for("ds_must_authenticate"))
Exemplo n.º 9
0
def get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        return render_template(
            "eg013_add_doc_to_template.html",
            title="Embedded Signing Ceremony from template and extra doc",
            template_ok="template_id" in session,
            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'],
            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'))
Exemplo n.º 10
0
def get_controller():
    """responds with the form for the example"""

    if views.ds_token_ok():
        gateway = ds_config.DS_CONFIG['gateway_account_id']
        gateway_ok = gateway and len(gateway) > 25

        return render_template(
            "eg014_collect_payment.html",
            title="Order form with payment",
            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'],
            signer_name=ds_config.DS_CONFIG['signer_name'],
            signer_email=ds_config.DS_CONFIG['signer_email'],
            gateway_ok=gateway_ok)
    else:
        # Save the current operation so it will be resumed after authentication
        session['eg'] = url_for(eg)
        return redirect(url_for('ds_must_authenticate'))
Exemplo n.º 11
0
def create_controller():
    """
    1. Check the token and presence of a saved template_id
    2. Call the worker method
    """
    minimum_buffer_min = 3
    token_ok = views.ds_token_ok(minimum_buffer_min)
    if token_ok and 'template_id' in session:
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile('([^\w \-\@\.\,])+')
        signer_email = pattern.sub('', request.form.get('signer_email'))
        signer_name = pattern.sub('', request.form.get('signer_name'))
        cc_email = pattern.sub('', request.form.get('cc_email'))
        cc_name = pattern.sub('', request.form.get('cc_name'))
        item = pattern.sub('', request.form.get('item'))
        quantity = pattern.sub('', request.form.get('quantity'))
        quantity = int(quantity)
        template_id = session['template_id']
        envelope_args = {
            'signer_email': signer_email,
            'signer_name': signer_name,
            'cc_email': cc_email,
            'cc_name': cc_name,
            'template_id': template_id,
            'signer_client_id': signer_client_id,
            'item': item,
            'quantity': quantity,
            'ds_return_url': url_for('ds_return', _external=True)
        }
        args = {
            'account_id': session['ds_account_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
            'envelope_args': envelope_args
        }

        try:
            results = worker(args)
        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, 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)
        if results:
            # Redirect the user to the Signing Ceremony
            # Don't use an iFrame!
            # State can be stored/recovered using the framework's session
            return redirect(results["redirect_url"])

    elif not token_ok:
        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'))
    elif not 'template_id' in session:
        return render_template(
            "eg013_add_doc_to_template.html",
            title="Embedded Signing Ceremony from template and extra doc",
            template_ok=False,
            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'],
        )
Exemplo n.º 12
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    """
    minimum_buffer_min = 3
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile('([^\w \-\@\.\,])+')
        signer_email = pattern.sub('', request.form.get('signer_email'))
        signer_name = pattern.sub('', request.form.get('signer_name'))
        cc_email = pattern.sub('', request.form.get('cc_email'))
        cc_name = pattern.sub('', request.form.get('cc_name'))
        envelope_args = {
            'signer_email': signer_email,
            'signer_name': signer_name,
            'cc_email': cc_email,
            'cc_name': cc_name,
            'status': 'sent',
            'gateway_account_id': ds_config.DS_CONFIG['gateway_account_id'],
            'gateway_name': ds_config.DS_CONFIG['gateway_name'],
            'gateway_display_name': ds_config.DS_CONFIG['gateway_display_name']
        }
        args = {
            'account_id': session['ds_account_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
            'envelope_args': envelope_args
        }

        try:
            results = worker(args)
        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, 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)
        if results:
            return render_template(
                'example_done.html',
                title="Envelope sent",
                h1="Envelope sent",
                message=f"""The envelope has been created and sent!<br/>
                        Envelope ID {results["envelope_id"]}.""")

    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'))
Exemplo n.º 13
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Show results
    """
    minimum_buffer_min = 3
    token_ok = views.ds_token_ok(minimum_buffer_min)
    if token_ok and 'envelope_id' in session:
        # 2. Call the worker method
        args = {
            'account_id': session['ds_account_id'],
            'envelope_id': session['envelope_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
        }

        try:
            results = worker(args)
        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, 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
                                   )

        # Save the envelopeId and its list of documents in the session so
        # they can be used in example 7 (download a document)
        standard_doc_items = [
            {'name': 'Combined'   , 'type': 'content', 'document_id': 'combined'},
            {'name': 'Zip archive', 'type': 'zip'    , 'document_id': 'archive'}]
            # The certificate of completion is named "summary".
            # We give it a better name below.
        envelope_doc_items = list(map(lambda doc :
            ({'document_id': doc.document_id, 'name': "Certificate of completion", 'type': doc.type})
            if (doc.document_id == "certificate") else
            ({'document_id': doc.document_id, 'name': doc.name                   , 'type': doc.type}),
            results.envelope_documents))
        envelope_documents = {'envelope_id': session['envelope_id'],
            'documents': standard_doc_items + envelope_doc_items} # See https://stackoverflow.com/a/6005217/64904

        session['envelope_documents'] = envelope_documents # Save


        return render_template("example_done.html",
                                title="List an envelope's documents",
                                h1="List an envelope's documents",
                                message="Results from the EnvelopeDocuments::list method:",
                                json=json.dumps(json.dumps(results.to_dict()))
                                )
    elif not token_ok:
        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'))
    elif not 'envelope_id' in session:
        return render_template("eg006_envelope_docs.html",
                               title="Envelope documents",
                               envelope_ok=False,
                               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'],
                               )
Exemplo n.º 14
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Show results
    """
    minimum_buffer_min = 3
    token_ok = views.ds_token_ok(minimum_buffer_min)
    if token_ok and 'envelope_id' in session and 'envelope_documents' in session:
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile('([^\w \-\@\.\,])+')
        document_id = pattern.sub('', request.form.get('document_id'))

        args = {
            'account_id': session['ds_account_id'],
            'envelope_id': session['envelope_id'],
            'base_path': session['ds_base_path'],
            'ds_access_token': session['ds_access_token'],
            'document_id': document_id,
            'envelope_documents': session['envelope_documents']
        }

        try:
            results = worker(args)
        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, 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)

        return send_file(results["data"],
                         mimetype=results["mimetype"],
                         as_attachment=True,
                         attachment_filename=results["doc_name"])

    elif not token_ok:
        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'))
    elif not 'envelope_id' in session or not 'envelope_documents' in session:
        return render_template(
            "eg007_envelope_get_doc.html",
            title="Download an Envelope's Document",
            envelope_ok=False,
            documents_ok=False,
            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'],
        )
Exemplo n.º 15
0
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    """
    minimum_buffer_min = 3
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile("([^\w \-\@\.\,])+")
        signer_email = pattern.sub("", request.form.get("signer_email"))
        signer_name = pattern.sub("", request.form.get("signer_name"))
        cc_email = pattern.sub("", request.form.get("cc_email"))
        cc_name = pattern.sub("", request.form.get("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": session["ds_account_id"],
            "base_path": session["ds_base_path"],
            "ds_access_token": session["ds_access_token"],
            "envelope_args": envelope_args
        }

        try:
            results = worker(args)
        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, 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)
        if results:
            session["envelope_id"] = results[
                "envelope_id"]  # Save for use by other examples
            # which need an envelopeId
            return render_template(
                "example_done.html",
                title="Envelope sent",
                h1="Envelope sent",
                message=f"""The envelope has been created and sent!<br/>
                        Envelope ID {results["envelope_id"]}.""")

    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 create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Redirect the user to the signing ceremony
    """

    # Names of the variables from forms.py
    form_variable_names = [
        FormEntry("select", "pdf_aaatest", "eh_pdf_aaatest"),
        FormEntry("select", "pdf_aarp", "eh_pdf_name"),
        FormEntry("select", "pdf_aetna", "eh_pdf_name"),
        FormEntry("select", "pdf_alignment", "eh_pdf_name"),
        FormEntry("select", "pdf_anthem", "eh_pdf_name"),

        FormEntry("bool", "include_SOA", "eh_include_SOA"),

        FormEntry("radio", "title", "eh_title"),
        FormEntry("text", "first_name", "eh_first_name"),
        FormEntry("text", "middle_initial", "eh_middle_initial"),
        FormEntry("text", "last_name", "eh_last_name"),
        FormEntry("text", "home_address", "eh_home_address"),
        FormEntry("text", "city", "eh_city"),
        FormEntry("text", "state", "eh_state"),
        FormEntry("text", "zip", "eh_zip"),
        FormEntry("bool", "diff_mail_addr", "eh_diff_mail_addr"),
        FormEntry("text", "mailing_address", "eh_mailing_address"),
        FormEntry("text", "mailing_city", "eh_mailing_city"),
        FormEntry("text", "mailing_state", "eh_mailing_state"),
        FormEntry("text", "mailing_zip", "eh_mailing_zip"),
        FormEntry("text", "home_tel", "eh_home_tel"),
        FormEntry("text", "email", "eh_email"),
        FormEntry("text", "dob", "eh_dob"),
        FormEntry("text", "aarp", "eh_aarp"),
        FormEntry("select_mult", "add_coverage", "eh_add_coverage"),
        FormEntry("text", "claim_num", "eh_claim_num"),
        FormEntry("select", "hospital_month", "eh_hospital_month"),
        FormEntry("select", "hospital_year", "eh_hospital_year"),
        FormEntry("select", "medical_month", "eh_medical_month"),
        FormEntry("select", "medical_year", "eh_medical_year"),
        FormEntry("select", "plan_type", "eh_plan_type"),
        FormEntry("text", "ins_company", "eh_ins_company"),
        FormEntry("text", "policy_id", "eh_policy_id"),
        FormEntry("text", "ins_start_date", "eh_ins_start_date"),
        FormEntry("text", "ins_end_date", "eh_ins_end_date"),
        FormEntry("select", "pref_payment", "eh_pref_payment"),
        FormEntry("text", "bank_name", "eh_bank_name"),
        FormEntry("text", "account_number", "eh_account_number"),
        FormEntry("text", "routing_number", "eh_routing_number")
    ]


    minimum_buffer_min = 3
    # Check the access token
    if views.ds_token_ok(minimum_buffer_min):
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile("([^\w \-\@\.\,])+")

        envelope_args = {
            "signer_client_id": signer_client_id,
            "form_data": [],

            "ds_return_url": url_for("ds_return", _external=True)
        }

        # Populate envelope_args with the data from the form
        for v in form_variable_names:
            try:
                if "pdf_" in v.name:
                    v.value = request.form.get(v.name)
                else:
                    v.value = pattern.sub("", request.form.get(v.name))
            except:
                # If field is left blank, pass in empty string as value
                v.value = ""
            envelope_args["form_data"].append(v)

        # These args are used by Docusign for the electronic signature
        envelope_args["signer_email"] = request.form.get("email")
        envelope_args["signer_name"]  = request.form.get("first_name") + " " + request.form.get("last_name")

        # Pass args into worker
        args = {
            "account_id": session["ds_account_id"],
            "base_path": session["ds_base_path"],
            "ds_access_token": session["ds_access_token"],
            "envelope_args": envelope_args
        }

        try:
            results = worker(args)
        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"]


            print("ERROR FROM WORKER(): " + error_message)

            # views.ds_logout_internal();

            # session["eg"] = url_for("success")      # <-- problem: this works, except that our new request doesn't have the form data. Re-think architecture here.
            return views.ds_callback()#views.ds_login();

        if results:
            # Redirect the user to the Signing Ceremony
            # Don"t use an iFrame!
            # State can be stored/recovered using the framework's session or a
            # query parameter on the returnUrl (see the makeRecipientViewRequest method)


            session["envelope_id"] = results["envelope_id"]

            url = ("signing_ceremony/" +
                str(session["envelope_id"]) + "/" +
                str(args["account_id"]) )

            sign_later_url = request.base_url.replace("success", "") + url

            return render_template('form_submitted.html', sign_now_url=results["redirect_url"], sign_later_url=sign_later_url)

    else:
        print("must_authenticate")
        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_login"))
def create_controller():
    """
    1. Check the token
    2. Call the worker method
    3. Show results
    """
    minimum_buffer_min = 3
    token_ok = views.ds_token_ok(minimum_buffer_min)
    if token_ok:
        # 2. Call the worker method
        # More data validation would be a good idea here
        # Strip anything other than characters listed
        pattern = re.compile("([^\w \-\@\.\,])+")
        signer_email  = pattern.sub("", request.form.get("signer_email"))
        print("c")
        signer_name   = pattern.sub("", request.form.get("signer_name"))
        cc_email      = pattern.sub("", request.form.get("cc_email"))
        cc_name       = pattern.sub("", request.form.get("cc_name"))
        starting_view = pattern.sub("", request.form.get("starting_view"))

        envelope_args = {
            "signer_email": signer_email,
            "signer_name": signer_name,
            "cc_email": cc_email,
            "cc_name": cc_name,
            "status": "sent",
        }
        args = {
            "starting_view": starting_view,
            "account_id": session["ds_account_id"],
            "base_path": session["ds_base_path"],
            "ds_access_token": session["ds_access_token"],
            "envelope_args": envelope_args,
            "ds_return_url": url_for("ds_return", _external=True),
        }

        try:
            results = worker(args)
        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, 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
                                   )
        if results:
            # Redirect the user to the NDSE view
            # Don't use an iFrame!
            # State can be stored/recovered using the framework's session or a
            # query parameter on the returnUrl (see the makeRecipientViewRequest method)
            return redirect(results["redirect_url"])

    elif not token_ok:
        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"))
    elif not "envelope_id" in session:
        return render_template("eg011_embedded_sending.html",
                               title="Embedded Sending",
                               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"],
                               )