Cartde Technical Documentation

Complete internal documentation for the Cartde AI-powered e-commerce assistant platform. Built on Cloudflare Workers with D1 database.

Architecture
System design, service architecture, and infrastructure overview.
Database Schema
47 tables across 6 development phases with full schema documentation.
API Reference
17 route modules with 100+ endpoints for all platform features.
Infrastructure
Cloudflare Workers, D1, Pages, and AI integration setup.

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 Configuration
Database Name: cartde-db
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.

ColumnTypeDescription
idTEXT PKUnique user identifier
emailTEXT UNIQUEUser email address
password_hashTEXTBcrypt hashed password
nameTEXTDisplay name
avatar_urlTEXTProfile picture URL
email_verifiedTIMESTAMPEmail verification timestamp
created_atTIMESTAMPAccount creation time
updated_atTIMESTAMPLast update time

workspaces

Multi-tenant workspace containers for stores/businesses.

ColumnTypeDescription
idTEXT PKUnique workspace identifier
nameTEXTWorkspace display name
slugTEXT UNIQUEURL-friendly identifier
owner_idTEXT FKReferences users.id
settingsJSONWorkspace configuration
api_key_hashTEXTHashed API key for widget auth
api_key_prefixTEXTFirst 11 chars for lookup (ck_xxxxxxxx)
training_statusTEXTidle | training | completed | failed
products_countINTEGERCached product count
faqs_countINTEGERCached FAQ count
conversations_countINTEGERCached conversation count

products

Product catalog with full e-commerce attributes.

ColumnTypeDescription
idTEXT PKUnique product identifier
workspace_idTEXT FKReferences workspaces.id
external_idTEXTExternal system ID (WooCommerce, etc.)
nameTEXTProduct name
descriptionTEXTFull product description
short_descriptionTEXTBrief description for cards
priceINTEGERPrice in cents (9999 = $99.99)
compare_at_priceINTEGEROriginal price for sale display
currencyTEXTISO currency code (USD)
skuTEXTStock keeping unit
stock_statusTEXTin_stock | out_of_stock | backorder
stock_quantityINTEGERAvailable quantity
imagesJSONArray of image URLs
categoriesJSONArray of category names
tagsJSONArray of tags
is_activeBOOLEANProduct visibility
is_featuredBOOLEANFeatured product flag

conversations

Chat conversation sessions between customers and AI/agents.

ColumnTypeDescription
idTEXT PKUnique conversation identifier
workspace_idTEXT FKReferences workspaces.id
session_idTEXTBrowser session/visitor ID
customer_idTEXT FKReferences customers.id
statusTEXTactive | closed | archived
message_countINTEGERTotal messages in conversation
handled_byTEXTai | human | hybrid
assigned_agent_idTEXT FKHuman agent assignment
priorityTEXTlow | normal | high | urgent
flagged_for_reviewBOOLEANNeeds human review

messages

Individual messages within conversations.

ColumnTypeDescription
idTEXT PKUnique message identifier
conversation_idTEXT FKReferences conversations.id
roleTEXTuser | assistant | system
contentTEXTMessage text content
intentTEXTDetected intent (greeting, product_search, etc.)
structuredJSONProduct cards or other structured data
agent_idTEXT FKHuman agent who sent message
is_internalBOOLEANInternal note (not shown to customer)

Analytics & Metrics Tables

analytics_events

Real-time event tracking for user actions.

ColumnTypeDescription
idTEXT PKUnique event identifier
workspace_idTEXT FKReferences workspaces.id
event_typeTEXTchat_message | product_view | product_search | faq_answered | intent_detected
event_dataJSONEvent-specific payload
conversation_idTEXT FKRelated conversation
product_idTEXT FKRelated product
session_idTEXTVisitor session

analytics_daily

Pre-aggregated daily metrics for dashboards.

ColumnTypeDescription
idTEXT PKUnique record identifier
workspace_idTEXT FKReferences workspaces.id
dateTEXTDate in YYYY-MM-DD format
total_conversationsINTEGERConversations that day
total_messagesINTEGERMessages sent that day
unique_sessionsINTEGERUnique visitors
product_searchesINTEGERProduct search queries
intent_distributionJSONIntent counts {greeting: 5, ...}

Marketing & Automation Tables

carts

Shopping cart tracking for abandonment recovery.

ColumnTypeDescription
idTEXT PKUnique cart identifier
workspace_idTEXT FKReferences workspaces.id
customer_idTEXT FKReferences customers.id
statusTEXTactive | abandoned | recovered | converted
itemsJSONArray of cart items
subtotalINTEGERCart total in cents
abandoned_atTIMESTAMPWhen cart was marked abandoned
recovery_attemptsINTEGERNumber of recovery messages sent

leads

Lead capture from chat and forms.

ColumnTypeDescription
idTEXT PKUnique lead identifier
workspace_idTEXT FKReferences workspaces.id
emailTEXTLead email address
nameTEXTLead name
sourceTEXTchat | form | import
statusTEXTnew | contacted | qualified | converted | lost
scoreINTEGERLead score (0-100)
custom_fieldsJSONAdditional form data

webhooks

Outgoing webhook configurations.

ColumnTypeDescription
idTEXT PKUnique webhook identifier
workspace_idTEXT FKReferences workspaces.id
nameTEXTWebhook display name
urlTEXTWebhook endpoint URL
secretTEXTHMAC signing secret
eventsJSONArray of event types to trigger
is_activeBOOLEANWebhook enabled status

Authentication API

User authentication using JWT tokens. Tokens expire after 7 days by default.

POST /v1/auth/register

Create a new user account.

Request Body

JSON
{
  "email": "user@example.com",
  "password": "min8chars",
  "name": "John Doe"
}

Response

JSON
{
  "success": true,
  "data": {
    "user": { "id": "abc123", "email": "user@example.com", "name": "John Doe" },
    "token": "eyJhbGciOiJIUzI1NiJ9..."
  }
}
POST /v1/auth/login

Authenticate and receive a JWT token.

Request Body

JSON
{
  "email": "user@example.com",
  "password": "yourpassword"
}
GET /v1/auth/me

Get current authenticated user profile.

Headers

HTTP
Authorization: Bearer <jwt_token>

Workspaces API

Manage workspaces (stores/businesses). All workspace routes require authentication.

POST /v1/workspaces

Create a new workspace. Returns the API key (only shown once).

Request Body

JSON
{
  "name": "My Store",
  "settings": {
    "timezone": "UTC",
    "currency": "USD",
    "locale": "en-US"
  }
}

Response

JSON
{
  "success": true,
  "data": {
    "id": "wsp_abc123",
    "name": "My Store",
    "slug": "my-store",
    "apiKey": "ck_xxxxxxxxxxxxxxxxxxxx",  // Only shown once!
    "settings": { ... }
  }
}
GET /v1/workspaces

List all workspaces the user has access to.

GET /v1/workspaces/:workspaceId

Get workspace details including settings and counts.

Products API

Manage product catalog for AI context.

GET /v1/workspaces/:wid/products

List products with pagination and filtering.

Query Parameters

ParameterTypeDescription
pagenumberPage number (default: 1)
pageSizenumberItems per page (default: 20, max: 100)
searchstringSearch in name/description
categorystringFilter by category
isActivebooleanFilter by active status
POST /v1/workspaces/:wid/products

Create a new product.

Request Body

JSON
{
  "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.

API Key Authentication
Widget endpoints require the X-API-Key header with a valid workspace API key (format: ck_xxxxxxxx or vk_xxxxxxxx).
POST /v1/widget/chat

Send a message and receive an AI response.

Headers

HTTP
X-API-Key: ck_your_api_key_here
Content-Type: application/json

Request Body

JSON
{
  "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

JSON
{
  "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 /v1/widget/chat/config

Get widget configuration for the workspace.

Analytics API

Dashboard analytics and metrics.

GET /v1/workspaces/:wid/analytics/overview

Get dashboard overview metrics.

Response

JSON
{
  "success": true,
  "data": {
    "totals": {
      "conversations": 150,
      "messages": 1200,
      "products": 45,
      "faqs": 20
    },
    "trends": {
      "conversationsThisWeek": 25,
      "conversationChange": 15.5
    }
  }
}
GET /v1/workspaces/:wid/analytics/advanced/heatmap

Get conversation activity heatmap (7x24 matrix).

GET /v1/workspaces/:wid/analytics/advanced/ai-performance

Get AI response success rate and fallback metrics.

Integrations API

Connect external e-commerce platforms to sync products.

POST /v1/workspaces/:wid/integrations/woocommerce/sync

Sync products from WooCommerce.

Request Body

JSON
{
  "storeUrl": "https://yourstore.com",
  "consumerKey": "ck_woocommerce_key",
  "consumerSecret": "cs_woocommerce_secret"
}
POST /v1/workspaces/:wid/integrations/shopify/sync

Sync products from Shopify.

POST /v1/workspaces/:wid/integrations/csv/import

Import products from JSON array.

Request Body

JSON
{
  "products": [
    { "name": "Product 1", "description": "...", "price": 9999, "sku": "SKU-001" },
    { "name": "Product 2", "description": "...", "price": 14999, "sku": "SKU-002" }
  ]
}

Cloudflare Infrastructure

Account Details

ResourceValue
Account ID643cab4b2d055eed7c5e8c813ca4c6cd
Worker Namecartde-api
D1 Databasecartde-db
D1 Database ID67fe7ff6-84c6-4d5f-89d9-5773e771f7e2

Bindings

TOML
# 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

VariableDescription
JWT_SECRETSecret key for signing JWT tokens (set via wrangler secret)
JWT_EXPIRES_INToken expiration (default: "7d")
APP_URLDashboard URL
WIDGET_URLWidget SDK URL

Deployment Commands

Deploy API

Bash
cd apps/api
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd npx wrangler deploy

Deploy Widget SDK

Bash
cd packages/widget-sdk
npm run build
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd npx wrangler pages deploy dist --project-name=cartde-widget

Deploy Dashboard

Bash
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

Bash
# 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

Bash
CLOUDFLARE_ACCOUNT_ID=643cab4b2d055eed7c5e8c813ca4c6cd \
  npx wrangler secret put JWT_SECRET