12 KiB
Design — Composite Envelope Builder (Updated)
Project: Salesforce Composite Envelope Builder Version: 2.0 Date: 2026-03-25 Author: (auto-generated; update author/owner as needed)
1. Summary
This document describes the current implementation of the Composite Envelope Builder: how Screen Flows, Apex, and the dfsle toolkit collaborate to build and send a single DocuSign envelope composed from multiple DocuSign templates. It reflects the latest code and metadata in the repository (March 2026), including:
- Flow V3 (existing, email-only path) and Flow V4 (new, SMS collection path when recipient email is blank)
- Apex invocable:
DocusignCompositeEnvelopeBuilder.sendCompositeEnvelopeand supporting classes - SMS delivery support for recipients without an email (via
dfsle.Recipient.withSmsDelivery()) - Multi-copy support for the "Authorization to Release Information" template (up to 5 copies)
- Email subject & body composition rules: prefix
Docusign:, truncation, greeting/signoff handling and Spanish detection - Key constants:
SMS_PLACEHOLDER_EMAIL,MULTI_COPY_TEMPLATE_NAME
This is the canonical design doc for developers, release engineers, and reviewers.
2. Architecture Overview
High-level flow:
- User launches Screen Flow (Flow V3 or V4)
- User selects language (English/Spanish) and templates
- Flow optionally collects SMS phone when recipient email is blank (V4)
- Flow invokes Apex action
Send Composite Docusign Envelopewith inputs - Apex builds compound envelope JSON using selected templates (expands multi-copy templates as configured)
- Apex uses dfsle toolkit to send envelope; returns envelopeId and success/error
Components:
- Screen Flows:
Docusign_Envelope_Templates_V3(email path),Docusign_Envelope_Templates_V4(collect SMS phone when needed) - Apex:
DocusignCompositeEnvelopeBuilder.cls(invocable entrypoint + implementation)DocusignEnvelopeRequest.cls(invocable request contract)DocusignEnvelopeResult.cls(invocable result contract)DocusignAPIService.cls,DocusignCredentials.cls(service & credential management)
- DocuSign: Composite Templates API (via dfsle toolkit integration)
3. Flow Behavior (V3 and V4)
3.1 Shared behavior (V3 & V4)
- Language selection screen: user selects
EnglishorSpanish. - Template selection screen: multi-select list of templates filtered by selected language.
- After selection, a loop scans selected templates to detect the multi-copy template ("Authorization to Release Information").
- If detected, a copies screen appears (radio 1–5) that sets
authReleaseFormCopies. - Flow gathers
compositeTemplateIds(selected template IDs) and passes them to Apex action.
3.2 Flow V3
- Used when standard email delivery is expected.
- No SMS collection screen is present.
- Behavior is unchanged from previous releases except choices include 1–5 copies.
3.3 Flow V4 (SMS-aware)
- Added pre-send recipient lookup path:
Get_Records(Client_Case__c) →Get_Recipient_Contact(Contact lookup)Is_Recipient_Email_Blankdecision checks Contact.Email- If email is blank →
SMS_Phone_Screen(fieldsmsPhoneInputrequired, E.164 format recommended) →Store_SMS_Phoneassignment assigns torecipientSmsPhonevariable → continue - If email present → skip SMS_Phone_Screen and continue
- The
recipientSmsPhonevariable is passed into the Apex action; when non-blank the Apex sets up SMS delivery for Docusign Recipient #1. - Flow element names to reference in code and docs:
SMS_Phone_Screen,smsPhoneInput,Store_SMS_Phone,recipientSmsPhone.
Note: Flow metadata must keep element blocks contiguous (assignments, decisions, screens, etc.) to avoid deployment errors. The committed Docusign_Envelope_Templates_V4.flow-meta.xml already follows these rules.
4. Apex Implementation Details
4.1 Invocable contract (DocusignEnvelopeRequest)
Key input fields (invocable variables):
List<String> templateIds(required) — list of selected DocuSign template IDsString recordId(required) — Salesforce Client Case IdString language(optional) — e.g.,en,es,Spanish,Español(language detection is normalized in Apex)String emailSubject(optional) — optional override; Apex still prefixes withDocusign:and truncates to 100 charsInteger authReleaseFormCopies(optional) — 1–5; counts for Authorization templateString recipientSmsPhone(optional) — when provided, Apex will enable SMS delivery for Docusign Recipient #1
Outputs:
String envelopeIdBoolean successString errorMessage
4.2 Main behavior (DocusignCompositeEnvelopeBuilder.sendCompositeEnvelope)
- Validate inputs; throw friendly errors if invalid.
- Expand multi-copy templates:
- Find template IDs whose
Namecontains the constantMULTI_COPY_TEMPLATE_NAME. - If
authReleaseFormCopies> 1, append (copies - 1) additional entries for each matched template ID. - Cap copies to 5 (Math.min(..., 5)).
- Find template IDs whose
- Build document list (documents = fromTemplate(templateId, label)) and label duplicates as
(Copy N)to preserve uniqueness. - Build deduplicated display names for subject/body (merge repeated templates into count markers like
X (3)). - Compose envelope subject & body (see section 5 for rules).
- Resolve recipients via
resolveRecipients(recordId, recipientSmsPhone):- Query Client_Case__c for lookup fields
- For Docusign Recipient #1: if linked Contact has no Email and
recipientSmsPhoneis provided, set recipientEmail toSMS_PLACEHOLDER_EMAILand callrecipient.withSmsDelivery(smsPhone).
- Use dfsle toolkit to build envelope with documents and recipients and call send.
- Return
envelopeIdandsuccess.
4.3 Important constants
SMS_PLACEHOLDER_EMAIL(defined inDocusignCompositeEnvelopeBuilder.cls): placeholder email used when recipient has no email; required by DocuSign API even for SMS deliveries.MULTI_COPY_TEMPLATE_NAME(defined in same class): base name used to identify the Authorization to Release Information template (covers English + Spanish variations via LIKE).
4.4 i18n detection
- The code normalizes
req.languageto lowercase and treats as Spanish if any of the following are true:lang.startsWith('es')(e.g.es,es-CO)lang.contains('spanish')lang.contains('espa')(to captureespañol/espanol)
- On Spanish detection, Apex uses Spanish greeting/signoff; otherwise English is used.
5. Email Subject & Body Composition Rules
-
Subject:
- Prefix:
Docusign:is prepended to the subject to make the source explicit. - Truncation: After prefixing, subject is truncated to a maximum of 100 characters (Docusign requirement). The code uses
left(97) + '...'if longer. - If user supplies
emailSubject, prefix and truncation still apply.
- Prefix:
-
Body:
- Built as: GREETING + (template bodies joined by DIVIDER) + SIGNOFF
- DIVIDER:
"\n\n" + '─'.repeat(40) + "\n\n"(visual separator) - Greeting/Sign-off: English default; Spanish strings used when language detection matches Spanish variants. Examples:
- English greeting:
Hello,\n\nPlease complete the DocuSign signature request from Early Intervention Colorado.\n\n - Spanish greeting:
Hola,\n\nPor favor, firme la solicitud de DocuSign de parte de Intervención Temprana Colorado.\n\n
- English greeting:
6. Multi-copy Behavior
- Single constant drives detection:
MULTI_COPY_TEMPLATE_NAME = 'Authorization to Release Information'. - Flow shows a copies screen when the template is present; operator selects 1–5 copies.
- Apex expands the templateId list before building documents to include multiple entries; duplicates are intentionally kept so each copy becomes a separate document in the envelope.
- Document labels: duplicates are labeled with
(Copy N)so they appear distinct in DocuSign Status.
7. SMS Delivery Details
- Trigger: Flow V4 routes to
SMS_Phone_Screenif the Contact linked byDocusign_Recipient_1__chas emptyEmail. - The screen collects
smsPhoneInputwhich is assigned torecipientSmsPhonevariable and passed to Apex. - In Apex, when
recipientSmsPhoneis non-blank for Docusign Recipient #1:- If recipient record has no email, set
recipientEmail = SMS_PLACEHOLDER_EMAIL. - Call
recipient = recipient.withSmsDelivery(smsPhone)to enable SMS delivery via dfsle toolkit.
- If recipient record has no email, set
- Service Coordinator recipient always uses email delivery (unchanged).
- Important setup requirement (documented):
Docusign_Recipient_1__con the Client Case must be populated with a Contact. The Contact must haveNameand (for SMS flow) may have blankEmail. If the Contact is null, the recipient will be omitted and envelope will be missing that signer.
8. Flows & Metadata Notes
- Flow element naming conventions are important (screen fields bind by their
name). For the SMS flow, the screen field issmsPhoneInputand the assignment must use<elementReference>smsPhoneInput</elementReference>(notScreenName.smsPhoneInput). - Flow metadata must keep element blocks contiguous (screens, assignments, recordLookups, decisions, loops, choices) to avoid Salesforce Flow XML validation failures. The repo's V4 flow file was normalized accordingly.
9. Tests, Validation & CI
- Unit tests: ensure
DocusignCompositeEnvelopeBuilderTestcovers:- English and Spanish subject/body composition
- Multi-copy expansion with 1–5 copies
- SMS flow path: when Contact.Email blank + recipientSmsPhone provided, mailbox placeholder used and
withSmsDeliveryapplied - Error branches and API failures
- CI: add a PR validation job that does:
- sfdx auth to a validation org
- For changed flow or Apex files, run
sfdx force:source:deploy --checkonlyfor those components - Fail PR if check-only returns errors
- Pre-deploy: run check-only deploy to target org before actual deploy. Example local command:
sfdx force:source:deploy -p force-app/main/default/flows/Docusign_Envelope_Templates_V4.flow-meta.xml,force-app/main/default/classes/DocusignCompositeEnvelopeBuilder.cls -u dev-org --checkonly --testlevel NoTestRun
10. Edge Cases and Known Gotchas
- If operator edits a flow in the org and does not retrieve+commit the changes, repo and org diverge. Use mdapi
retrieveorsf project retrieveto pull the authoritative version and commit immediately. - Flow Builder sometimes reorders or normalizes XML: prefer re-checking contiguity of element blocks after Flow Builder saves.
- Ensure the Flow variable
recipientSmsPhoneis passed to Apex action and that the assignment usessmsPhoneInputas elementReference. - The DocuSign API requires an email field on every recipient even when SMS is used;
SMS_PLACEHOLDER_EMAILis central and must be kept updated in Apex if changed.
11. Deployment Checklist
- Confirm
force-app/main/default/flows/Docusign_Envelope_Templates_V4.flow-meta.xmlmatches the active version in org (if you intend to deploy active draft) - Confirm
force-app/main/default/classes/DocusignCompositeEnvelopeBuilder.clsand related classes/tests are committed - Run
sfdx force:source:deploy --checkonlyfor affected components against a validation org - Run Apex tests (or allow CI to run tests during deploy)
- Deploy to sandbox, perform a manual Flow Builder inspection of V4
- Activate the desired Flow version if runtime activation is needed
12. Change Log (high level)
- 2.0 (2026-03-25): Updated design to reflect:
- Flow V4 (SMS path) retrieval & Active flow committed
- Spanish greeting/signoff and broadened language detection
- Envelope subject prefix
Docusign:and truncation to 100 chars - Increased Authorization multi-copy support to 5 copies
- Flow element and metadata normalization
13. Contact & Ownership
- Primary developer: Paul Huliganga (update as appropriate)
- Repo:
composite-envelope-builder - For deployment questions: refer to
docs/DEPLOYMENT_AND_TESTING.md
This document was generated to represent the repository state as of March 25, 2026. Update the change log and ownership fields when you make future changes.