Cartde Technical Documentation
Complete internal documentation for the Cartde AI-powered e-commerce assistant platform. Built on Cloudflare Workers with D1 database.
System Architecture
Cartde is built as a serverless platform leveraging Cloudflare's edge infrastructure for global performance and scalability.
Tech Stack
| Component | Technology | Purpose |
|---|---|---|
| API Runtime | Cloudflare Workers | Serverless API execution at the edge |
| Database | Cloudflare D1 (SQLite) | Distributed SQLite database |
| AI/LLM | Cloudflare Workers AI | Llama 3.1 8B for chat responses |
| Web Framework | Hono | Fast, lightweight web framework |
| ORM | Drizzle ORM | Type-safe database operations |
| Frontend | Next.js 15 + React 18 | Dashboard application |
| Widget | Vanilla TypeScript | Embeddable chat widget SDK |
| Validation | Zod | Schema validation for API inputs |
| Auth | JWT (jose) | Stateless authentication tokens |
Deployment URLs
| Service | URL | Platform |
|---|---|---|
| API | https://cartde-api.cartde.workers.dev |
Cloudflare Workers |
| Dashboard | https://cartde-web.pages.dev |
Cloudflare Pages |
| Widget SDK | https://cartde-widget.pages.dev |
Cloudflare Pages |
Services Overview
The platform is organized into logical service modules, each handling specific functionality.
API Route Modules
| Module | Path | Description |
|---|---|---|
| auth | /v1/auth/* | User registration, login, profile management |
| workspaces | /v1/workspaces/* | Workspace CRUD, settings, API keys |
| products | /v1/workspaces/:wid/products/* | Product catalog management |
| faqs | /v1/workspaces/:wid/faqs/* | FAQ content management |
| chat | /v1/widget/chat/* | Widget chat endpoints |
| conversations | /v1/workspaces/:wid/conversations/* | Conversation history & management |
| teams | /v1/workspaces/:wid/team/* | Team members & invitations |
| analytics | /v1/workspaces/:wid/analytics/* | Basic analytics & metrics |
| advancedAnalytics | /v1/workspaces/:wid/analytics/advanced/* | Heatmaps, funnels, AI performance |
| voice | /v1/workspaces/:wid/voice/* | Voice chat settings |
| language | /v1/workspaces/:wid/language/* | Multi-language support |
| comparison | /v1/workspaces/:wid/comparison/* | Product comparison features |
| integrations | /v1/workspaces/:wid/integrations/* | WooCommerce, Shopify, CSV imports |
| support | /v1/workspaces/:wid/support/* | Tickets & canned responses |
| marketing | /v1/workspaces/:wid/marketing/* | Carts, leads, campaigns |
| ai | /v1/workspaces/:wid/ai/* | AI personalities & training |
| whitelabel | /v1/workspaces/:wid/whitelabel/* | Custom domains & branding |
Database Overview
Cartde uses Cloudflare D1, a distributed SQLite database. The schema is organized across 6 development phases with 47 tables total.
Database ID: 67fe7ff6-84c6-4d5f-89d9-5773e771f7e2
Account ID: 643cab4b2d055eed7c5e8c813ca4c6cd
Schema Phases
| Phase | Name | Tables | Description |
|---|---|---|---|
| 1-2 | Core Platform | 7 | Users, workspaces, products, FAQs, conversations, messages, training |
| 3 | Multi-tenancy & Analytics | 5 | Workspace members, invites, analytics events/daily |
| 4 | Support & Human Handoff | 3 | Tickets, canned responses, customers |
| 5 | Advanced AI & Personalization | 8 | Customer memories, segments, recommendations, AI personalities |
| 6 | Marketing & Automation | 14 | Carts, leads, webhooks, campaigns, integrations |
| 7-8 | Voice, Language, Comparison | 10 | Voice settings, translations, product comparisons, advanced analytics |
Core Database Tables
users
Stores user accounts and authentication data.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique user identifier |
| TEXT UNIQUE | User email address | |
| password_hash | TEXT | Bcrypt hashed password |
| name | TEXT | Display name |
| avatar_url | TEXT | Profile picture URL |
| email_verified | TIMESTAMP | Email verification timestamp |
| created_at | TIMESTAMP | Account creation time |
| updated_at | TIMESTAMP | Last update time |
workspaces
Multi-tenant workspace containers for stores/businesses.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique workspace identifier |
| name | TEXT | Workspace display name |
| slug | TEXT UNIQUE | URL-friendly identifier |
| owner_id | TEXT FK | References users.id |
| settings | JSON | Workspace configuration |
| api_key_hash | TEXT | Hashed API key for widget auth |
| api_key_prefix | TEXT | First 11 chars for lookup (ck_xxxxxxxx) |
| training_status | TEXT | idle | training | completed | failed |
| products_count | INTEGER | Cached product count |
| faqs_count | INTEGER | Cached FAQ count |
| conversations_count | INTEGER | Cached conversation count |
products
Product catalog with full e-commerce attributes.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique product identifier |
| workspace_id | TEXT FK | References workspaces.id |
| external_id | TEXT | External system ID (WooCommerce, etc.) |
| name | TEXT | Product name |
| description | TEXT | Full product description |
| short_description | TEXT | Brief description for cards |
| price | INTEGER | Price in cents (9999 = $99.99) |
| compare_at_price | INTEGER | Original price for sale display |
| currency | TEXT | ISO currency code (USD) |
| sku | TEXT | Stock keeping unit |
| stock_status | TEXT | in_stock | out_of_stock | backorder |
| stock_quantity | INTEGER | Available quantity |
| images | JSON | Array of image URLs |
| categories | JSON | Array of category names |
| tags | JSON | Array of tags |
| is_active | BOOLEAN | Product visibility |
| is_featured | BOOLEAN | Featured product flag |
conversations
Chat conversation sessions between customers and AI/agents.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique conversation identifier |
| workspace_id | TEXT FK | References workspaces.id |
| session_id | TEXT | Browser session/visitor ID |
| customer_id | TEXT FK | References customers.id |
| status | TEXT | active | closed | archived |
| message_count | INTEGER | Total messages in conversation |
| handled_by | TEXT | ai | human | hybrid |
| assigned_agent_id | TEXT FK | Human agent assignment |
| priority | TEXT | low | normal | high | urgent |
| flagged_for_review | BOOLEAN | Needs human review |
messages
Individual messages within conversations.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique message identifier |
| conversation_id | TEXT FK | References conversations.id |
| role | TEXT | user | assistant | system |
| content | TEXT | Message text content |
| intent | TEXT | Detected intent (greeting, product_search, etc.) |
| structured | JSON | Product cards or other structured data |
| agent_id | TEXT FK | Human agent who sent message |
| is_internal | BOOLEAN | Internal note (not shown to customer) |
Analytics & Metrics Tables
analytics_events
Real-time event tracking for user actions.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique event identifier |
| workspace_id | TEXT FK | References workspaces.id |
| event_type | TEXT | chat_message | product_view | product_search | faq_answered | intent_detected |
| event_data | JSON | Event-specific payload |
| conversation_id | TEXT FK | Related conversation |
| product_id | TEXT FK | Related product |
| session_id | TEXT | Visitor session |
analytics_daily
Pre-aggregated daily metrics for dashboards.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique record identifier |
| workspace_id | TEXT FK | References workspaces.id |
| date | TEXT | Date in YYYY-MM-DD format |
| total_conversations | INTEGER | Conversations that day |
| total_messages | INTEGER | Messages sent that day |
| unique_sessions | INTEGER | Unique visitors |
| product_searches | INTEGER | Product search queries |
| intent_distribution | JSON | Intent counts {greeting: 5, ...} |
Marketing & Automation Tables
carts
Shopping cart tracking for abandonment recovery.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique cart identifier |
| workspace_id | TEXT FK | References workspaces.id |
| customer_id | TEXT FK | References customers.id |
| status | TEXT | active | abandoned | recovered | converted |
| items | JSON | Array of cart items |
| subtotal | INTEGER | Cart total in cents |
| abandoned_at | TIMESTAMP | When cart was marked abandoned |
| recovery_attempts | INTEGER | Number of recovery messages sent |
leads
Lead capture from chat and forms.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique lead identifier |
| workspace_id | TEXT FK | References workspaces.id |
| TEXT | Lead email address | |
| name | TEXT | Lead name |
| source | TEXT | chat | form | import |
| status | TEXT | new | contacted | qualified | converted | lost |
| score | INTEGER | Lead score (0-100) |
| custom_fields | JSON | Additional form data |
webhooks
Outgoing webhook configurations.
| Column | Type | Description |
|---|---|---|
| id | TEXT PK | Unique webhook identifier |
| workspace_id | TEXT FK | References workspaces.id |
| name | TEXT | Webhook display name |
| url | TEXT | Webhook endpoint URL |
| secret | TEXT | HMAC signing secret |
| events | JSON | Array of event types to trigger |
| is_active | BOOLEAN | Webhook enabled status |
Authentication API
User authentication using JWT tokens. Tokens expire after 7 days by default.
Create a new user account.
Request Body
{
"email": "user@example.com",
"password": "min8chars",
"name": "John Doe"
}
Response
{
"success": true,
"data": {
"user": { "id": "abc123", "email": "user@example.com", "name": "John Doe" },
"token": "eyJhbGciOiJIUzI1NiJ9..."
}
}
Authenticate and receive a JWT token.
Request Body
{
"email": "user@example.com",
"password": "yourpassword"
}
Get current authenticated user profile.
Headers
Authorization: Bearer <jwt_token>
Workspaces API
Manage workspaces (stores/businesses). All workspace routes require authentication.
Create a new workspace. Returns the API key (only shown once).
Request Body
{
"name": "My Store",
"settings": {
"timezone": "UTC",
"currency": "USD",
"locale": "en-US"
}
}
Response
{
"success": true,
"data": {
"id": "wsp_abc123",
"name": "My Store",
"slug": "my-store",
"apiKey": "ck_xxxxxxxxxxxxxxxxxxxx", // Only shown once!
"settings": { ... }
}
}
List all workspaces the user has access to.
Get workspace details including settings and counts.
Products API
Manage product catalog for AI context.
List products with pagination and filtering.
Query Parameters
| Parameter | Type | Description |
|---|---|---|
| page | number | Page number (default: 1) |
| pageSize | number | Items per page (default: 20, max: 100) |
| search | string | Search in name/description |
| category | string | Filter by category |
| isActive | boolean | Filter by active status |
Create a new product.
Request Body
{
"name": "Product Name",
"description": "Full product description",
"shortDescription": "Brief description",
"price": 9999, // Price in cents ($99.99)
"sku": "SKU-001",
"stockStatus": "in_stock",
"categories": ["Electronics"],
"tags": ["sale", "featured"]
}
Chat & Widget API
Widget chat endpoints use API key authentication via the X-API-Key header.
X-API-Key header with a valid workspace API key (format: ck_xxxxxxxx or vk_xxxxxxxx).Send a message and receive an AI response.
Headers
X-API-Key: ck_your_api_key_here
Content-Type: application/json
Request Body
{
"sessionId": "visitor-uuid",
"message": "What products do you have?",
"conversationId": null, // null for new conversation
"metadata": {
"pageUrl": "https://example.com/shop",
"userAgent": "Mozilla/5.0..."
}
}
Response
{
"success": true,
"data": {
"conversationId": "conv_abc123",
"message": {
"id": "msg_xyz789",
"content": "We have several products available...",
"role": "assistant",
"products": [
{ "id": "prod_1", "name": "Widget", "price": 9999, "currency": "USD" }
]
},
"intent": "product_search"
}
}
Get widget configuration for the workspace.
Analytics API
Dashboard analytics and metrics.
Get dashboard overview metrics.
Response
{
"success": true,
"data": {
"totals": {
"conversations": 150,
"messages": 1200,
"products": 45,
"faqs": 20
},
"trends": {
"conversationsThisWeek": 25,
"conversationChange": 15.5
}
}
}
Get conversation activity heatmap (7x24 matrix).
Get AI response success rate and fallback metrics.
Integrations API
Connect external e-commerce platforms to sync products.
Sync products from WooCommerce.
Request Body
{
"storeUrl": "https://yourstore.com",
"consumerKey": "ck_woocommerce_key",
"consumerSecret": "cs_woocommerce_secret"
}
Sync products from Shopify.
Import products from JSON array.
Request Body
{
"products": [
{ "name": "Product 1", "description": "...", "price": 9999, "sku": "SKU-001" },
{ "name": "Product 2", "description": "...", "price": 14999, "sku": "SKU-002" }
]
}
Cloudflare Infrastructure
Account Details
| Resource | Value |
|---|---|
| Account ID | 643cab4b2d055eed7c5e8c813ca4c6cd |
| Worker Name | cartde-api |
| D1 Database | cartde-db |
| D1 Database ID | 67fe7ff6-84c6-4d5f-89d9-5773e771f7e2 |
Bindings
# wrangler.toml
name = "cartde-api"
main = "src/index.ts"
compatibility_date = "2024-11-01"
account_id = "643cab4b2d055eed7c5e8c813ca4c6cd"
[[d1_databases]]
binding = "DB"
database_name = "cartde-db"
database_id = "67fe7ff6-84c6-4d5f-89d9-5773e771f7e2"
[ai]
binding = "AI"
Environment Variables
| Variable | Description |
|---|---|
| JWT_SECRET | Secret key for signing JWT tokens (set via wrangler secret) |
| JWT_EXPIRES_IN | Token expiration (default: "7d") |
| APP_URL | Dashboard URL |
| WIDGET_URL | Widget SDK URL |
Deployment Commands
Deploy API
cd apps/api
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd npx wrangler deploy
Deploy Widget SDK
cd packages/widget-sdk
npm run build
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd npx wrangler pages deploy dist --project-name=cartde-widget
Deploy Dashboard
cd apps/web
NEXT_PUBLIC_API_URL=https://cartde-api.cartde.workers.dev npm run build
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd npx wrangler pages deploy out --project-name=cartde-web
Database Migrations
# Run a migration file
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd \
npx wrangler d1 execute cartde-db --remote --file=migrations/0001_initial.sql
# Execute SQL directly
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd \
npx wrangler d1 execute cartde-db --remote --command="SELECT * FROM users LIMIT 5"
Set Secrets
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd \
npx wrangler secret put JWT_SECRET