Overview
The Google Sheets integration provides a robust backend data store for Ai Studio, enabling real-time synchronization of customers, orders, reservations, products, and other business data. Using Google Apps Script, it exposes a RESTful API for CRUD operations without requiring a traditional database.Features
- Two-Way Sync: Bidirectional data synchronization between frontend and Google Sheets
- RESTful API: Web app endpoints for GET and POST operations
- CRUD Operations: Create, read, update, and delete data
- Authentication: Secret key-based security
- Automatic Type Conversion: JSON parsing and proper data typing
- Schedule Management: Special handling for business hours
- Multi-Sheet Support: Separate sheets for different data types
Sheet Structure
Your Google Sheet should contain these sheets:| Sheet Name | Purpose | Key Fields |
|---|---|---|
| Customers | Customer information | id, name, phone, email, address, categoryId |
| Orders | Order tracking | id, customer, items, total, status, type, createdAt |
| Reservations | Table reservations | id, customerName, customerPhone, guests, reservationTime, tableIds, status |
| Tables | Table configuration | id, name, capacity, allowsReservations |
| Schedule | Business hours | day, isOpen, slots |
| Products | Menu items | id, category, name, description, price, imageUrl |
| Promotions | Active promotions | id, name, items, price, isActive |
| Categories | Product categories | id, name, imageUrl, color |
| CustomerCategories | Customer segmentation | id, name, color |
| ReservationSettings | Reservation rules | duration, minBookingTime, slotInterval |
| SliceBotMetrics | AI bot metrics | distinctCustomers, totalMessages, ordersMade |
| ChatHistory | AI conversations | id, startTime, messages, outcome, tokensUsed |
| ScheduleExceptions | Holiday hours | id, name, startDate, endDate, type, slots |
| WhatsappsHistory | WhatsApp messages | timestamp, messageId, direction, from, to, body |
| WhastappAssistant_logs | WhatsApp events | timestamp, eventName, projectId, details |
Setup Instructions
Create Google Sheet
- Create a new Google Sheet
- Note the Sheet ID from the URL:
https://docs.google.com/spreadsheets/d/[SHEET_ID]/edit - The sheets will be auto-created when data is first synced
Deploy ScriptBD.js
This script handles main data CRUD operations:
- Open Google Apps Script editor from your sheet (Extensions > Apps Script)
- Create a new script file named
ScriptBD.gs - Copy contents from
AppsSript/ScriptBD.js - Update configuration:
- Deploy as Web App:
- Click Deploy > New Deployment
- Type: Web App
- Execute as: Me
- Who has access: Anyone
- Copy the web app URL
Deploy BotWhatsappCRUD.js
This script handles WhatsApp bot data operations:
- Create another script file named
BotWhatsappCRUD.gs - Copy contents from
AppsSript/BotWhatsappCRUD.js - Update the sheet ID:
- Deploy as a separate Web App following the same steps
- Copy this web app URL as well
ScriptBD API
The main data management script (ScriptBD.js) provides these operations:
GET Endpoints
POST Endpoints
Schedule Management
Schedule data requires special handling:AppsSript/ScriptBD.js:99
BotWhatsappCRUD API
The WhatsApp-specific script (BotWhatsappCRUD.js) handles bot-related operations:
Actions
Get Active Items
AppsSript/BotWhatsappCRUD.js:272
Data Type Conversion
The scripts automatically convert data types:AppsSript/ScriptBD.js:154
Complex objects (arrays, nested objects) are stored as JSON strings and automatically parsed when retrieved.
Generic Update Function
Both scripts use a generic update-by-ID function:AppsSript/BotWhatsappCRUD.js:390
Authentication
All requests require the secret key:AppsSript/ScriptBD.js:125
Error Handling
Both scripts use standardized error responses:AppsSript/ScriptBD.js:134
Auto-Creating Sheets
Sheets are automatically created with headers when first accessed:AppsSript/ScriptBD.js:143
Sync Efficiency
ThesyncSheet function efficiently updates entire sheets:
AppsSript/ScriptBD.js:318
Batch operations are much faster than row-by-row writes. Always use
setValues() with a 2D array instead of multiple appendRow() calls.Frontend Integration
Typical usage from the frontend:services/apiService.ts
Performance Considerations
- Batch Operations: Use
syncAllDatainstead of multiple individual updates - Caching: Cache sheet data in localStorage to reduce API calls
- Quotas: Apps Script has daily quotas; monitor usage in the Google Cloud Console
- Execution Time: Scripts timeout after 6 minutes; large syncs may need optimization
- Concurrent Access: Google Sheets handles concurrent writes, but race conditions can occur
Troubleshooting
”Permission Denied” Errors
- Ensure web app is deployed with “Execute as: Me”
- Set access to “Anyone” (web apps can’t use “Anyone with the link”)
- Re-authorize the script if permissions were recently changed
Data Not Updating
- Check that you’re using the latest deployment URL (not a previous version)
- Verify the
sheetIdmatches your Google Sheet - Check Apps Script logs for errors
- Ensure secret key matches in both script and frontend
Type Conversion Issues
- IDs and phone numbers may be converted to numbers; store them as strings
- Use consistent date formatting (ISO 8601 recommended)
- Large numbers may lose precision; store as strings if needed
”Script function not found” Error
- Ensure you saved the script after making changes
- Create a new deployment (don’t just redeploy existing one)
- Check function names match exactly (case-sensitive)
Best Practices
- Use Environment Variables: Store URLs and keys securely
- Handle Errors: Always check response status and handle failures
- Validate Data: Verify data structure before sending to sheets
- Version Control: Keep script versions in sync with frontend expectations
- Test Thoroughly: Test CRUD operations with Apps Script debugger
- Monitor Quotas: Track API usage to avoid hitting limits
- Backup Data: Regularly backup your Google Sheet
- Use IDs: Always include unique IDs for update/delete operations
