8.2 KiB
Custom Templates Feature
This document explains how the Custom Templates feature works in the Template Manager service, following the same pattern as Custom Features.
Overview
The Custom Templates feature allows users to submit custom templates that go through an admin approval workflow before becoming available in the system. This follows the exact same pattern as the existing Custom Features implementation.
Architecture
Database Tables
custom_templates- Stores custom template submissions with admin approval workflowtemplates- Mirrors approved custom templates (withtype = 'custom_<id>')
Models
CustomTemplate- Handles custom template CRUD operations and admin workflowTemplate- Standard template model (mirrors approved custom templates)
Routes
/api/custom-templates- Public endpoints for creating/managing custom templates/api/admin/templates/*- Admin endpoints for reviewing custom templates
How It Works
1. Template Submission
User submits custom template → CustomTemplate.create() → Admin notification → Mirror to templates table
2. Admin Review Process
Admin reviews → Updates status → If approved: activates mirrored template → If rejected: keeps inactive
3. Template Mirroring
- Custom templates are mirrored into the
templatestable withtype = 'custom_<id>' - This allows them to be used by existing template endpoints
- The mirrored template starts with
is_active = falseuntil approved
API Endpoints
Public Custom Template Endpoints
POST /api/custom-templates
Create a new custom template.
Required fields:
type- Template type identifiertitle- Template titlecategory- Template categorycomplexity- 'low', 'medium', or 'high'
Optional fields:
description- Template descriptionicon- Icon identifiergradient- CSS gradientborder- Border stylingtext- Primary textsubtext- Secondary textbusiness_rules- JSON business rulestechnical_requirements- JSON technical requirementscreated_by_user_session- User session identifier
Response:
{
"success": true,
"data": {
"id": "uuid",
"type": "custom_type",
"title": "Custom Template",
"status": "pending",
"approved": false
},
"message": "Custom template 'Custom Template' created successfully and submitted for admin review"
}
GET /api/custom-templates
Get all custom templates with pagination.
Query parameters:
limit- Number of templates to return (default: 100)offset- Number of templates to skip (default: 0)
GET /api/custom-templates/search
Search custom templates by title, description, or category.
Query parameters:
q- Search term (required)limit- Maximum results (default: 20)
GET /api/custom-templates/:id
Get a specific custom template by ID.
PUT /api/custom-templates/:id
Update a custom template.
DELETE /api/custom-templates/:id
Delete a custom template.
GET /api/custom-templates/status/:status
Get custom templates by status.
Valid statuses: pending, approved, rejected, duplicate
GET /api/custom-templates/stats
Get custom template statistics.
Admin Endpoints
GET /api/admin/templates/pending
Get pending templates for admin review.
GET /api/admin/templates/status/:status
Get templates by status (admin view).
POST /api/admin/templates/:id/review
Review a custom template.
Request body:
{
"status": "approved|rejected|duplicate",
"admin_notes": "Optional admin notes",
"canonical_template_id": "UUID of similar template (if duplicate)"
}
GET /api/admin/templates/stats
Get custom template statistics for admin dashboard.
Template Merging Endpoints
GET /api/templates/merged
Get all templates (default + approved custom) grouped by category.
This endpoint merges default templates with approved custom templates, providing a unified view.
Database Schema
custom_templates Table
CREATE TABLE custom_templates (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
type VARCHAR(100) NOT NULL,
title VARCHAR(200) NOT NULL,
description TEXT,
icon VARCHAR(50),
category VARCHAR(100) NOT NULL,
gradient VARCHAR(100),
border VARCHAR(100),
text VARCHAR(100),
subtext VARCHAR(100),
complexity VARCHAR(50) NOT NULL CHECK (complexity IN ('low', 'medium', 'high')),
business_rules JSONB,
technical_requirements JSONB,
approved BOOLEAN DEFAULT false,
usage_count INTEGER DEFAULT 1,
created_by_user_session VARCHAR(100),
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW(),
-- Admin approval workflow fields
status VARCHAR(50) DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected', 'duplicate')),
admin_notes TEXT,
admin_reviewed_at TIMESTAMP,
admin_reviewed_by VARCHAR(100),
canonical_template_id UUID REFERENCES templates(id) ON DELETE SET NULL,
similarity_score FLOAT CHECK (similarity_score >= 0 AND similarity_score <= 1)
);
Admin Workflow
1. Template Submission
- User creates custom template via
/api/custom-templates - Template is saved with
status = 'pending' - Admin notification is created
- Template is mirrored to
templatestable withis_active = false
2. Admin Review
- Admin views pending templates via
/api/admin/templates/pending - Admin reviews template and sets status:
- Approved: Template becomes active, mirrored template is activated
- Rejected: Template remains inactive
- Duplicate: Template marked as duplicate with reference to canonical template
3. Template Activation
- Approved templates have their mirrored version activated (
is_active = true) - Rejected/duplicate templates remain inactive
- All templates are accessible via the merged endpoints
Usage Examples
Creating a Custom Template
const response = await fetch('/api/custom-templates', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
type: 'ecommerce_custom',
title: 'Custom E-commerce Template',
description: 'A specialized e-commerce template for fashion retailers',
category: 'E-commerce',
complexity: 'medium',
business_rules: { payment_methods: ['stripe', 'paypal'] },
technical_requirements: { framework: 'react', backend: 'nodejs' }
})
});
Admin Review
const reviewResponse = await fetch('/api/admin/templates/uuid/review', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer admin-jwt-token'
},
body: JSON.stringify({
status: 'approved',
admin_notes: 'Great template design, approved for production use'
})
});
Getting Merged Templates
const mergedTemplates = await fetch('/api/templates/merged');
// Returns default + approved custom templates grouped by category
Migration
To add custom templates support to an existing database:
- Run the migration:
node src/migrations/migrate.js - The migration will create the
custom_templatestable - Existing templates and features remain unchanged
- New custom templates will be stored separately and mirrored
Benefits
- Non-disruptive: Existing templates and features remain unchanged
- Consistent Pattern: Follows the same workflow as custom features
- Admin Control: All custom templates go through approval process
- Unified Access: Approved custom templates are accessible via existing endpoints
- Audit Trail: Full tracking of submission, review, and approval process
Security Considerations
- Admin Authentication: All admin endpoints require JWT with admin role
- Input Validation: All user inputs are validated and sanitized
- Status Checks: Only approved templates become active
- Session Tracking: User sessions are tracked for audit purposes
Future Enhancements
- Template Similarity Detection: Automatic duplicate detection
- Bulk Operations: Approve/reject multiple templates at once
- Template Versioning: Track changes and versions
- Template Analytics: Usage statistics and performance metrics
- Template Categories: Dynamic category management