Google Docs¶
Overview¶
The Google Docs task integrates BaseCloud CRM with Google Docs API v1, enabling automated document creation, content retrieval, and dynamic updates for proposal generation, contract management, and report automation.
Key Features:
- 3 Actions: Create documents, retrieve content, update documents
- OAuth 2.0 Authentication: Secure Google integration with automatic token refresh
- Folder Organization: Create documents in specific Google Drive folders
- Content Modes: Append, prepend, or replace document content
- Plain Text Extraction: Extract readable text from structured Docs format
- Template System: Dynamic document generation with variable replacement
Use Cases:
- Automated proposal generation from CRM data
- Contract creation with client information
- Daily/weekly report compilation
- Meeting notes automation
- Document template processing
- Content aggregation from multiple sources
Prerequisites¶
1. Google Cloud Project¶
Setup Google Cloud:
- Go to https://console.cloud.google.com
- Create new project or select existing
- Enable Google Docs API
- Enable Google Drive API (required for folder management)
- Create OAuth 2.0 credentials:
- Application type: Web application
- Authorized redirect URIs:
https://yourapp.basecloudglobal.com/oauth/callback - Note Client ID and Client Secret
2. OAuth Configuration in BaseCloud¶
Create App Connection:
- Navigate to BaseCloud CRM → Settings → Integrations → App Connections
- Click + New App Connection
- Select Google Docs from dropdown
- Enter credentials:
- Client ID: From Google Cloud Console
- Client Secret: From Google Cloud Console
- Click Authorize with Google
- Authorize scopes:
https://www.googleapis.com/auth/documents- Read/write documentshttps://www.googleapis.com/auth/drive.file- Manage created files- Grant access to Google account
- Save connection
OAuth Scopes Required:
Note: drive.file scope only accesses files created/opened by the app, not entire Drive.
3. Google Drive Folder IDs (Optional)¶
Get Folder ID:
- Open Google Drive: https://drive.google.com
- Navigate to folder
- Check URL:
https://drive.google.com/drive/folders/{FOLDER_ID} - Copy folder ID after
/folders/ - Or right-click folder → Share → Copy link → Extract ID
Example Folder ID:
Configuration¶
Action 1: create_document¶
Create new Google Document with optional initial content and folder placement.
| Field | Required | Description | Example |
|---|---|---|---|
| action | Yes | Must be "create_document" | create_document |
| app_connection_id | Yes | OAuth connection ID | Select from dropdown |
| document_title | Yes | Title for new document | Q1 Sales Proposal - {{client_name}} |
| document_content | No | Initial text content (default: empty) | Proposal for {{client_company}}... |
| folder_id | No | Google Drive folder ID (default: root) | 1a2b3c4d5e6f7g8h9i0j |
Output Variables:
task_45001_run // true/false
task_45001_run_text // "Document \"Q1 Sales Proposal\" created successfully."
task_45001_document_id // Google Docs document ID
task_45001_document_url // Direct edit URL
task_45001_title // Document title
task_45001_folder_id // Parent folder ID (if specified)
How It Works:
- Creates blank document via Docs API
- Sets title
- If
document_contentprovided: - Inserts text at beginning (index 1)
- If
folder_idprovided: - Moves document from root to specified folder via Drive API
- Returns document ID and edit URL
API Endpoints:
POST https://docs.googleapis.com/v1/documents
POST https://docs.googleapis.com/v1/documents/{documentId}:batchUpdate
PATCH https://www.googleapis.com/drive/v3/files/{documentId}
Document URL Format:
Use Cases:
- Create proposal from template text
- Generate contract with client details
- Initialize daily report document
- Create meeting notes with agenda
Action 2: get_document¶
Retrieve document content and metadata, with plain text extraction.
| Field | Required | Description | Example |
|---|---|---|---|
| action | Yes | Must be "get_document" | get_document |
| app_connection_id | Yes | OAuth connection ID | Select from dropdown |
| document_id | Yes | Google Docs document ID | 1a2b3c4d5e6f7g8h9i0j |
Output Variables:
task_45001_run // true/false
task_45001_run_text // "Document retrieved successfully."
task_45001_document_id // Document ID
task_45001_document_url // Edit URL
task_45001_title // Document title
task_45001_plain_text // Extracted plain text content
task_45001_content // Raw Google Docs structure array
Plain Text Extraction:
- Recursively extracts text from document structure
- Handles paragraphs, headings, lists
- Extracts text from tables (preserves table structure with newlines)
- Removes formatting (bold, italic, links)
- Preserves paragraph breaks
- Suitable for AI analysis or text processing
How It Works:
- Fetches complete document via Docs API
- Extracts title and document ID
- Recursively processes content structure:
- Paragraphs → Extract text from elements
- Tables → Extract from rows/cells
- Nested structures → Recursive extraction
- Returns both plain text and raw structure
API Endpoint:
Use Cases:
- Extract document for AI analysis
- Parse document for workflow decisions
- Copy content to other systems
- Archive document text
- Search document content
Action 3: update_document¶
Modify document content with three update modes: append, prepend, or replace.
| Field | Required | Description | Example |
|---|---|---|---|
| action | Yes | Must be "update_document" | update_document |
| app_connection_id | Yes | OAuth connection ID | Select from dropdown |
| document_id | Yes | Document to update | 1a2b3c4d5e6f7g8h9i0j |
| document_content | Yes | Text to add/insert | \n\nUpdate: {{new_info}} |
| update_mode | No | How to update (default: append) | append, prepend, replace |
Update Modes:
| Mode | Description | Use Case |
|---|---|---|
| append | Add content to end of document | Add daily log entry, append section |
| prepend | Add content to beginning | Add header, insert summary at top |
| replace | Delete all content and insert new | Template refresh, complete rewrite |
Output Variables:
task_45001_run // true/false
task_45001_run_text // "Document updated successfully (append)."
task_45001_document_id // Document ID
task_45001_document_url // Edit URL
How It Works:
Append Mode: 1. Fetches current document to get end index 2. Inserts text at end index 3. Prepends newline for separation
Prepend Mode: 1. Inserts text at index 1 (beginning) 2. Appends newline after inserted text
Replace Mode: 1. Fetches current document for indices 2. Deletes all content (index 1 to end-1) 3. Inserts new content at index 1 4. Completely overwrites document
API Endpoint:
Batch Update Request (Replace Example):
{
requests: [
{
deleteContentRange: {
range: {
startIndex: 1,
endIndex: 1249 // Current document end - 1
}
}
},
{
insertText: {
location: { index: 1 },
text: "Completely new content..."
}
}
]
}
Document Index Structure:
- Index 0: Reserved (document start)
- Index 1: First insertable position (mandatory newline)
- Index N-1: Last character
- Index N: End of document (mandatory trailing newline)
Use Cases:
- Append: Daily logs, incremental reports, adding sections
- Prepend: Executive summaries, document headers, priority updates
- Replace: Template processing, report regeneration, complete refresh
Real-World Examples¶
Example 1: Automated Proposal Generation¶
Scenario: When deal reaches proposal stage, generate customized proposal document from template.
Workflow:
-
Trigger: CRM Event - Deal Stage Changed
-
Task: Variable - Build Proposal Content
Variable: proposal_content Value: PROPOSAL FOR {{client_company_name}} Prepared for: {{client_contact_name}} Date: {{current_date}} Valid until: {{proposal_expiry_date}} EXECUTIVE SUMMARY {{deal_description}} SCOPE OF WORK {{deal_scope}} INVESTMENT Total: ${{deal_value}} Payment Terms: {{payment_terms}} NEXT STEPS 1. Review proposal 2. Schedule kickoff call 3. Sign agreement Thank you for considering {{company_name}}. {{sales_rep_name}} {{sales_rep_email}} {{sales_rep_phone}} -
Task: Google Docs - Create Document
-
Task: Edit Client - Add Custom Field
-
Task: Email - Send Proposal Link
To: {{client_contact_email}} CC: {{sales_rep_email}} Subject: Proposal for {{client_company_name}} Body: Hi {{client_contact_name}}, Thank you for the opportunity to work with {{client_company_name}}. I've prepared a customized proposal for your review: {{task_45001_document_url}} The proposal includes: - Executive summary - Detailed scope of work - Investment breakdown - Next steps Please review and let me know if you have any questions. Looking forward to working together! Best regards, {{sales_rep_name}} -
Task: Workflow Note
Result: Automated proposal generation reduces manual work from hours to seconds.
Example 2: Daily Report Compilation¶
Scenario: Compile daily activity summary from CRM into running document.
Workflow:
-
Trigger: Timer - Daily at 5:00 PM
-
Task: Variable - Document ID
-
Task: MySQL Query - Get Today's Activities
SELECT COUNT(DISTINCT client_id) as clients_contacted, COUNT(DISTINCT CASE WHEN type='Call' THEN wfn_id END) as calls_made, COUNT(DISTINCT CASE WHEN type='Email' THEN wfn_id END) as emails_sent, COUNT(DISTINCT CASE WHEN type='Meeting' THEN wfn_id END) as meetings_held FROM workflow_notes WHERE DATE(created_date) = CURDATE() AND owner_id = {{user_id}} -
Task: MySQL Query - Get Deals Won Today
-
Task: Variable - Build Daily Summary
-
Task: Google Docs - Update Document
-
Task: Workflow Note
Result: Automated daily activity log maintained in single living document.
Example 3: Contract Generation with Template¶
Scenario: Generate service contract when deal is won, using document template.
Workflow:
-
Trigger: CRM Event - Deal Won
-
Task: Variable - Template Document ID
-
Task: Google Docs - Get Template
-
Task: Variable - Process Template
Variable: contract_content Value: {{task_45001_plain_text}} Replace: {{CLIENT_NAME}} with {{client_company_name}} Replace: {{CLIENT_ADDRESS}} with {{client_address}} Replace: {{CONTRACT_VALUE}} with ${{deal_value}} Replace: {{START_DATE}} with {{project_start_date}} Replace: {{DURATION}} with {{project_duration}} Replace: {{PAYMENT_TERMS}} with {{payment_terms}} -
Task: Google Docs - Create Contract
-
Task: Edit Client - Store Contract URL
-
Task: Email - Send for Review
Result: Automated contract generation from template with dynamic data insertion.
Example 4: Meeting Notes Automation¶
Scenario: Pre-populate meeting notes document before scheduled meeting.
Workflow:
-
Trigger: Timer - 1 hour before meeting
-
Task: Variable - Build Meeting Agenda
Variable: meeting_notes Value: MEETING: {{meeting_subject}} Date: {{meeting_date}} Time: {{meeting_time}} ATTENDEES: - {{attendee_list}} AGENDA: 1. Welcome and introductions 2. Review previous action items 3. {{meeting_agenda_item_1}} 4. {{meeting_agenda_item_2}} 5. {{meeting_agenda_item_3}} 6. Next steps and action items NOTES: [To be filled during meeting] ACTION ITEMS: [ ] [ ] [ ] NEXT MEETING: Date: Time: -
Task: Google Docs - Create Meeting Notes
-
Task: Edit Client - Store Notes URL
-
Task: Email - Send to Attendees
To: {{attendee_emails}} Subject: Meeting Prep - {{meeting_subject}} Body: Hi team, Our meeting is scheduled for {{meeting_date}} at {{meeting_time}}. I've prepared the meeting notes document: {{task_45001_document_url}} Please review the agenda and add any topics you'd like to discuss. See you there! -
Task: Workflow Note
Result: Pre-populated meeting notes ready before meeting starts.
Example 5: Weekly Report Aggregation¶
Scenario: Compile weekly sales metrics into executive summary document.
Workflow:
-
Trigger: Timer - Monday 8:00 AM
-
Task: MySQL Query - Last Week's Metrics
SELECT COUNT(DISTINCT CASE WHEN status='Won' THEN deal_id END) as deals_won, COUNT(DISTINCT CASE WHEN status='Lost' THEN deal_id END) as deals_lost, SUM(CASE WHEN status='Won' THEN deal_value ELSE 0 END) as revenue, COUNT(DISTINCT client_id) as new_clients, COUNT(DISTINCT wfn_id) as activities FROM ( SELECT * FROM deals WHERE WEEK(close_date) = WEEK(CURDATE()) - 1 UNION ALL SELECT * FROM clients WHERE WEEK(created_date) = WEEK(CURDATE()) - 1 UNION ALL SELECT * FROM workflow_notes WHERE WEEK(created_date) = WEEK(CURDATE()) - 1 ) AS weekly_data -
Task: Variable - Calculate Win Rate
-
Task: Variable - Build Report Content
Variable: weekly_report Value: === WEEKLY REPORT: {{last_week_start}} - {{last_week_end}} === 📊 SALES PERFORMANCE Deals Won: {{deals_won}} Deals Lost: {{deals_lost}} Win Rate: {{win_rate}}% Revenue: ${{revenue}} Average Deal Size: ${{revenue / deals_won}} 📈 GROWTH New Clients: {{new_clients}} Total Activities: {{activities}} 🎯 KEY WINS {{top_deals_summary}} 🔍 INSIGHTS {{analysis_notes}} 📅 NEXT WEEK FOCUS {{next_week_priorities}} --- -
Task: Variable - Year Report Doc ID
-
Task: Google Docs - Append to Year Report
-
Task: Google Docs - Create Individual Report
-
Task: Email - Send to Executives
Result: Automated weekly reporting with both individual and aggregate documents.
Troubleshooting¶
Error: "No app connection selected"¶
Cause: OAuth connection not configured
Solutions:
- Go to Settings → Integrations → App Connections
- Create Google Docs connection
- Enter Client ID and Client Secret
- Complete OAuth authorization
- Grant both Docs and Drive scopes
Error: "Invalid OAuth 2.0 Access Token"¶
Cause: Access token expired (refresh failed)
Solutions:
- BaseCloud automatically refreshes tokens
- If error persists, re-authorize connection:
- Settings → App Connections → Edit
- Click Re-authorize with Google
- Verify OAuth scopes are correct:
https://www.googleapis.com/auth/documentshttps://www.googleapis.com/auth/drive.file
Error: "Document not found" (404)¶
Cause: Invalid document ID or no access
Solutions:
- Verify document ID format (no spaces, special chars)
- Check document hasn't been deleted
- Ensure OAuth account has access to document
- Only works with documents created by app or explicitly shared
- Test with known working document ID
Error: "Insufficient permissions"¶
Cause: Missing OAuth scopes or Drive permissions
Solutions:
- Verify OAuth scopes granted:
- Documents scope for read/write
- Drive scope for folder management
- Re-authorize with all scopes
- Check document sharing settings
- Ensure account has edit access to document
Folder Move Failed¶
Cause: Invalid folder ID or permission issue
Solutions:
- Verify folder ID format (long alphanumeric string)
- Check folder exists in Google Drive
- Ensure OAuth account has access to folder
- Test folder ID in Drive URL:
drive.google.com/drive/folders/{ID} - Omit folder_id to keep in root Drive
Document Content Empty or Malformed¶
Cause: Content formatting or structure issue
Solutions:
- Content must be plain text (no HTML)
- Use
\nfor line breaks (double backslash in JSON) - Escape special characters in variables
- Check variable substitution completed
- Test with simple static text first
Update Mode Not Working as Expected¶
Cause: Misunderstanding mode behavior
Solutions:
- Append: Adds to end (doesn't create new paragraph automatically - add
\n\n) - Prepend: Adds to beginning (add
\n\nafter for spacing) - Replace: Deletes everything and inserts new content
- Document always has mandatory newlines at start/end
- Test with simple document first
Rate Limiting / Quota Exceeded¶
Cause: Exceeded Google API quotas
Solutions:
- Default Quotas:
- 300 requests per minute per user
-
60 requests per minute per project
-
Immediate Actions:
- Add delays in document creation loops (1-2 seconds)
- Reduce frequency of updates
-
Batch content updates instead of multiple small updates
-
Long-term:
- Request quota increase in Google Cloud Console
- Implement exponential backoff
- Cache document content locally
- Use batch update requests
Plain Text Extraction Incomplete¶
Cause: Complex document structure
Solutions:
- Extraction handles paragraphs and tables
- Some elements may not extract (images, drawings)
- Tables preserve basic structure with newlines
- Formatting removed (bold, italic, colors)
- For rich content, use raw
contentstructure instead
Best Practices¶
Document Organization¶
- Folder Structure:
- Create dedicated folders per document type
- Store folder IDs in variables for reuse
- Use client-specific folders:
/Clients/{{client_name}}/ -
Maintain folder ID mapping in database
-
Naming Conventions:
- Include date:
Report - 2024-02-08 - Include client:
Proposal - ABC Corp - Be descriptive:
Q1 Sales Report - EMEA Region -
Use consistent formatting across documents
-
Access Management:
- Documents created by app connection
- Share documents via Drive API or manually
- Store document URLs in CRM for easy access
- Use service account for organization-wide access
Content Strategy¶
- Template Design:
- Create master templates in Drive
- Use clear placeholder names:
{{CLIENT_NAME}} - Test templates with sample data
-
Store template IDs in configuration
-
Variable Replacement:
- Validate variables exist before using
- Provide default values for optional fields
- Format dates/currency consistently
-
Escape special characters if needed
-
Content Updates:
- Use append for logs and incremental content
- Use prepend for summaries and headers
- Use replace for complete refreshes
- Include separators (newlines) for readability
Automation Patterns¶
- Document Generation:
- Build content in Variable task first
- Test content formatting before creation
- Store document URL in CRM record
-
Send notification with document link
-
Scheduled Reports:
- Use Timer triggers for regular reports
- Compile data from multiple sources
- Append to running document or create new
-
Email stakeholders with document link
-
Template Processing:
- Get template content
- Replace placeholders with CRM data
- Create new document with processed content
- Original template remains unchanged
Performance Optimization¶
- API Calls:
- Minimize get_document calls (cache if possible)
- Batch content updates (don't update line by line)
- Use variables to build complete content before inserting
-
Avoid unnecessary document fetches
-
Content Size:
- Keep individual updates reasonable (<10KB)
- For large content, split into logical sections
- Consider using multiple documents for very long reports
-
Monitor document file sizes
-
Error Handling:
- Wrap document operations in If Conditions
- Log document IDs for troubleshooting
- Provide fallback workflows for failures
- Store backup content in MySQL if critical
Compliance and Security¶
- Data Protection:
- Be aware of data sensitivity in documents
- Use appropriate Drive sharing settings
- Consider encryption for highly sensitive data
-
Follow data retention policies
-
Access Control:
- Limit OAuth connection to specific accounts
- Use service accounts for organization documents
- Regular audit of created documents
-
Remove access when no longer needed
-
Audit Trail:
- Log all document operations in workflow notes
- Store document IDs in database
- Track document creation dates
- Maintain history of content updates
FAQ¶
Q: Can I format text (bold, italic, colors)?
A: Not with current actions. API supports formatting via insertText requests with textStyle, but requires additional implementation. Use Google Docs UI for formatting after creation.
Q: How do I add images to documents?
A: Images require additional API calls not currently implemented. Create document, then manually add images, or implement custom insertInlineImage request.
Q: Can I create documents from existing templates?
A: Yes, use Example 3 pattern: Get template content, replace placeholders, create new document. Original template remains unchanged.
Q: What's the maximum document size?
A: Google Docs supports up to 1.02 million characters. For larger content, split into multiple documents.
Q: Can I collaborate with others on created documents?
A: Yes, share documents via Google Drive. Documents created by app can be shared normally through Drive sharing settings.
Q: How do I handle tables in content?
A: Plain text extraction preserves table content with newlines. For complex tables, work with raw content structure or create tables via API (requires additional implementation).
Q: Can I export documents to PDF?
A: Use Google Drive export API (separate implementation) or use Drive export URL: https://docs.google.com/document/d/{docId}/export?format=pdf
Q: How often can I update a document?
A: Respect API quotas (300 requests/min). For frequent updates (e.g., every minute), consider batching updates or increasing interval.
Q: Can I search document content?
A: Use get_document to retrieve plain text, then search with If Condition or Code task. Drive API also supports content search.
Q: What happens if two automations update same document simultaneously?
A: Google Docs handles concurrent edits. Last write wins for conflicts. Use queue mechanisms for critical documents.
Q: Can I restore deleted documents?
A: Documents moved to Drive trash can be restored via Drive UI. Permanently deleted documents cannot be recovered.
Q: How do I share documents with specific people?
A: Use Google Drive API permissions (separate implementation) or share manually via Drive UI after creation.
Related Tasks¶
- Variable - Build document content
- Google Sheets - Spreadsheet automation
- PDF - PDF generation
- Email - Send document links
- If Statement - Conditional document creation
- Loop - Batch document generation
- MySQL Query - Aggregate data for reports
Technical Details¶
- Type ID: 45
- Function:
taskGoogleDocs()in automationService.js (lines 9571-9670) - Service:
googleDocsService.js(384 lines) - API Version: Google Docs API v1, Google Drive API v3
- Authentication: OAuth 2.0 with automatic token refresh
- Scopes:
https://www.googleapis.com/auth/documents,https://www.googleapis.com/auth/drive.file - Output Prefix:
task_45001_* - Rate Limits: 300 requests/minute/user, 60 requests/minute/project
- Timeout: 30 seconds per request
- Docs API Documentation: https://developers.google.com/docs/api
- Drive API Documentation: https://developers.google.com/drive/api/v3