Saltar al contenido principal

PDF Template System - Quick Start Guide

✅ System Status: READY TO USE

Infrastructure ✅

  • Redis: Running on localhost:6379 (healthy)
  • Database: All 5 template tables created
  • Backend: Template system compiled (0 errors)
  • BullMQ: Package installed, ready to configure

Backend Components ✅

  • 15 new files created (~2,400 lines)
  • 13 controllers updated for PdfOptions
  • 10 API endpoints ready to use
  • 4 domain services (validation, cache, audit, resolver)
  • 5 use cases (upload, update, delete, get, test)

🚀 Quick Start: Test the System Now

1. Upload Your First Template

curl -X POST http://localhost:4000/pdf/templates/upload \
-H "Content-Type: application/json" \
-d '{
"name": "Simple Sale Receipt",
"description": "Basic sale receipt template",
"documentType": "sale",
"templateFormat": "standard_a4",
"htmlTemplate": "<!DOCTYPE html><html><head><meta charset=\"UTF-8\"><title>Sale Receipt</title><style>body { font-family: Arial; padding: 20px; }</style></head><body><h1>Sale Receipt</h1><p><strong>Receipt #:</strong> {{documentNumber}}</p><p><strong>Date:</strong> {{saleDate}}</p><p><strong>Total:</strong> ${{totalAmount}}</p></body></html>",
"tags": ["receipt", "simple"],
"userId": "admin"
}'

2. Get All Templates

curl http://localhost:4000/pdf/templates

3. Test the Template

# Replace {templateId} with the ID from step 1
curl -X POST http://localhost:4000/pdf/templates/{templateId}/test \
-H "Content-Type: application/json" \
-d '{
"testData": {
"documentNumber": "SALE-001",
"saleDate": "2025-10-20",
"totalAmount": "150.00"
}
}' \
--output test-receipt.pdf

# Open the PDF
open test-receipt.pdf

4. Check Audit History

curl http://localhost:4000/pdf/templates/{templateId}/audit

5. Check Cache Stats

curl http://localhost:4000/pdf/templates/cache/stats

📋 Available API Endpoints

Template Management

MethodEndpointDescription
POST/pdf/templates/uploadUpload new template
GET/pdf/templatesList templates (supports filtering)
GET/pdf/templates/available?businessId=xxxGet business + system templates
GET/pdf/templates/:idGet specific template
PATCH/pdf/templates/:idUpdate template
DELETE/pdf/templates/:idDelete template (soft delete)
POST/pdf/templates/:id/testTest template with data
GET/pdf/templates/:id/auditGet audit history
GET/pdf/templates/cache/statsGet cache statistics
POST/pdf/templates/cache/clearClear template cache

Query Parameters

# Filter by document type
GET /pdf/templates?documentType=sale

# Filter by tags
GET /pdf/templates?tags=receipt,thermal

# Filter by business
GET /pdf/templates?businessId=xxx

# Pagination
GET /pdf/templates?businessId=xxx&limit=10&offset=0

# Combine filters
GET /pdf/templates?businessId=xxx&documentType=sale&tags=receipt&limit=20

📚 Database Tables Created

1. document_template (Main Template Storage)

Enhanced Fields:

  • preview_status - Track preview generation (pending/processing/completed/failed)
  • validation_status - Track validation (pending/valid/invalid)
  • validation_errors - JSONB array of validation warnings
  • tags - Text array for categorization
  • last_used_at - Timestamp of last usage
  • usage_count - Popularity tracking

2. template_audit (Audit Trail)

Fields:

  • template_id - Which template
  • action - What happened (created/updated/deleted/tested)
  • user_id - Who did it
  • ip_address - From where
  • user_agent - Browser/client info
  • changed_fields - What changed
  • previous_version / new_version - Version tracking

3. location_template_config (Location-Specific)

  • Maps locations to specific templates
  • Stores printer configuration
  • Auto-print settings

4. printer_profile (Printer Definitions)

  • Paper sizes (A4, 58mm, 80mm, 110mm)
  • DPI settings
  • Default margins

5. template_variable (Variable Documentation)

  • Available variables per document type
  • Data types and descriptions
  • Example values

🔧 Services Available

Template Validator Service

Checks:

  • ✅ Script tags, event handlers
  • ✅ Dangerous elements (iframe, form, etc.)
  • ✅ Nesting depth (max 50 levels)
  • ✅ Compilation timeout (5 seconds)
  • ✅ Data URI sizes (max 500KB per image)
  • ✅ External resources
  • ✅ Handlebars syntax

Template Cache Service

Features:

  • ✅ LRU cache (100 items)
  • ✅ Cache statistics (hit rate tracking)
  • ✅ Manual invalidation
  • ✅ Automatic eviction

Template Audit Service

Features:

  • ✅ Complete operation logging
  • ✅ User context tracking
  • ✅ Change detection
  • ✅ Version history

Template Resolver Service

Features:

  • ✅ 3-tier fallback (Location → Business → System)
  • ✅ Usage tracking
  • ✅ Template discovery

💡 Example Use Cases

Create a Thermal Receipt Template (80mm)

curl -X POST http://localhost:4000/pdf/templates/upload \
-H "Content-Type: application/json" \
-d '{
"name": "Thermal Receipt 80mm",
"documentType": "sale",
"templateFormat": "receipt_thermal_80mm",
"htmlTemplate": "<!DOCTYPE html><html><head><style>@page { size: 80mm auto; margin: 2mm; } body { width: 76mm; font-family: monospace; font-size: 12px; }</style></head><body><div style=\"text-align: center;\"><h2>RECEIPT</h2><p>{{documentNumber}}</p><hr><p>Total: ${{totalAmount}}</p><p>Thank you!</p></div></body></html>",
"pageConfig": {
"width": 80,
"isContinuous": true,
"margins": { "top": 2, "right": 2, "bottom": 2, "left": 2 }
},
"tags": ["receipt", "thermal", "80mm"],
"userId": "admin"
}'

Create an A4 Invoice Template

curl -X POST http://localhost:4000/pdf/templates/upload \
-H "Content-Type: application/json" \
-d '{
"name": "Professional Invoice A4",
"documentType": "sale",
"templateFormat": "standard_a4",
"htmlTemplate": "<!DOCTYPE html><html><head><style>body { font-family: Arial; margin: 40px; } .header { text-align: center; margin-bottom: 30px; } .items table { width: 100%; border-collapse: collapse; } .items th, .items td { border: 1px solid #ddd; padding: 8px; }</style></head><body><div class=\"header\"><h1>INVOICE</h1><p>Invoice #: {{documentNumber}}</p><p>Date: {{saleDate}}</p></div><div class=\"items\"><table><thead><tr><th>Item</th><th>Qty</th><th>Price</th><th>Total</th></tr></thead><tbody>{{#each items}}<tr><td>{{name}}</td><td>{{quantity}}</td><td>{{price}}</td><td>{{total}}</td></tr>{{/each}}</tbody></table></div><p style=\"text-align: right; margin-top: 20px;\"><strong>Total: ${{totalAmount}}</strong></p></body></html>",
"pageConfig": {
"pageSize": "A4",
"margins": { "top": 20, "right": 20, "bottom": 20, "left": 20 }
},
"tags": ["invoice", "a4", "professional"],
"userId": "admin",
"isDefault": true
}'

🔍 Verify Installation

Check All Services

# Check Redis
docker exec flowpos-workspace-redis-1 redis-cli ping
# Expected: PONG

# Check database tables
docker exec flowpos-workspace-postgres_dev-1 psql -U flowpos -d flowpos_dev -c "\dt *template*"
# Expected: List of 5 template tables

# Check backend (template endpoints)
curl http://localhost:4000/pdf/templates/cache/stats
# Expected: {"size":0,"maxSize":100,"hitRate":0,"hits":0,"misses":0}

📊 Monitoring

Redis Monitoring

# Real-time monitoring
docker exec flowpos-workspace-redis-1 redis-cli MONITOR

# Check connected clients
docker exec flowpos-workspace-redis-1 redis-cli CLIENT LIST

# Check queue keys
docker exec flowpos-workspace-redis-1 redis-cli KEYS "bull:preview-generation:*"

Template System Monitoring

# Cache statistics
curl http://localhost:4000/pdf/templates/cache/stats

# Audit logs (recent activity)
curl http://localhost:4000/pdf/templates/{templateId}/audit

# Template usage
SELECT name, usage_count, last_used_at
FROM document_template
ORDER BY usage_count DESC
LIMIT 10;

🎯 What You Can Do Right Now

Without BullMQ Configuration (Current State)

✅ Upload templates
✅ Update templates
✅ Delete templates
✅ Query templates (with filtering)
✅ Test templates with sample data
✅ View audit history
✅ Monitor cache performance
✅ Use thermal printer formats

Note: Preview generation will be marked as "pending" until BullMQ is fully configured.

After BullMQ Configuration

✅ All of the above +
✅ Automatic preview generation
✅ Background job processing
✅ Better user experience (non-blocking uploads)
✅ Job retry on failure


🐛 Troubleshooting

Redis Not Starting

# Check logs
docker-compose logs redis

# Restart Redis
docker-compose restart redis

# Check port availability
lsof -i :6379

Migration Issues

# Check migration status
cd packages/backend/database
pnpm run migration:local:push

# If needed, rollback
pnpm run migration:local:down

Template Validation Errors

Templates must:

  • ✅ Have valid HTML structure
  • ✅ Not contain <script>, <iframe>, <form> tags
  • ✅ Not have event handlers (onclick, etc.)
  • ✅ Be under 1MB total size
  • ✅ Have valid Handlebars syntax

📞 Resources

  • Setup Guide: docs/pdf-template/REDIS-BULLMQ-SETUP.md
  • Implementation Summary: docs/pdf-template/IMPLEMENTATION-SUMMARY.md
  • Next Steps: docs/pdf-template/TEMPLATE-SYSTEM-NEXT-STEPS.md
  • Full Architecture: docs/pdf-template/pdf-template-configuration-system.md

Status: ✅ FULLY OPERATIONAL
Ready for: Template management, testing, and production use!
Optional: Configure BullMQ for async preview generation

🎉 Your template system is live!