Frontend-Backend Service Synchronization Guide β
π Overview β
This guide documents how services are mapped between the frontend (strategic-intelligence-onboarding) and backend (stratiqx-payment), and provides automated scripts to keep them synchronized.
π Service Data Flow β
Frontend Config β PaymentService β API Request β Backend Validation β Database
β β β β β
services.config.ts payment-v2.ts /create-payment payment.js services tableπ Service Mapping Structure β
Frontend Configuration (src/config/services.config.ts) β
interface ServiceConfig {
id: string // β services.id
name: string // β services.name
description: string // β services.description
price: {
value: number // β services.min_price, services.max_price
display: string // Display only (not stored in DB)
}
deposit: {
type: string // Not stored directly
value: number // Calculation reference
amount: number // β services.deposit_amount
display: string // Display only
}
billingType: string // β services.billing_type
features: string[] // β services.metadata.features
metadata: object // β services.metadata (merged)
active: boolean // β services.active
}Backend Database Schema (services table) β
CREATE TABLE services (
id TEXT PRIMARY KEY, -- From frontend: config.id
name TEXT NOT NULL, -- From frontend: config.name
description TEXT, -- From frontend: config.description
min_price INTEGER, -- From frontend: config.price.value
max_price INTEGER, -- From frontend: config.price.value (same for fixed pricing)
deposit_amount INTEGER, -- From frontend: config.deposit.amount
billing_type TEXT, -- From frontend: config.billingType
metadata TEXT, -- JSON: combines config.features + config.metadata
active INTEGER DEFAULT 1, -- From frontend: config.active (1=true, 0=false)
created_at TEXT DEFAULT CURRENT_TIMESTAMP
);πΊοΈ Current Service Mapping β
| Frontend ID | Frontend Name | Price | Deposit | Backend Status |
|---|---|---|---|---|
market-essentials | Market Essentials | $1,495 | $299 | β Synced |
market-intelligence | Market Intelligence Pro | $2,995 | $599 | β Synced |
strategic-analysis | Strategic Analysis & Advisory | $4,995 | $999 | β Synced |
ongoing-retainer | Ongoing Intelligence Retainer | $3,500/mo | $3,500 | β Synced |
competitor-tracking | Real-Time Competitor Intelligence | $3,495/mo | Coming Soon | β³ Inactive |
market-pulse-executive | Market Pulse - Executive Report | Free | $0 | β³ Inactive |
π Synchronization Process β
When Frontend Changes Occur: β
- Service Configuration Update (
services.config.ts) - Run Sync Script (auto-generates SQL)
- Execute SQL (updates database)
- Clear Cache (forces API refresh)
- Deploy Frontend (if needed)
- Test Payment Flow
π οΈ Synchronization Scripts β
Script 1: Generate Sync SQL from Frontend Config β
Create: C:\workspace\scripts\generate-service-sync.js
/**
* Generate SQL sync script from frontend service configuration
* Usage: node scripts/generate-service-sync.js
*/
import fs from 'fs';
import path from 'path';
// Import the service configuration (adjust path as needed)
const SERVICES_CONFIG_PATH = '../strategic-intelligence-onboarding/src/config/services.config.ts';
function generateSyncSQL() {
console.log('π Generating Service Synchronization SQL...\n');
// In a real implementation, you would parse the TypeScript file
// For now, let's define the current config structure
const frontendServices = {
'market-essentials': {
id: 'market-essentials',
name: 'Market Essentials',
description: 'Executive-grade market intelligence leveraging proprietary AI research methodology. Comprehensive strategic analysis typically valued at $25,000+, delivered through our next-generation technology platform.',
price: { value: 1495, display: '$1,495' },
deposit: { type: 'percentage', value: 20, amount: 299, display: '20% deposit required' },
billingType: 'one-time',
features: [
'Executive-grade market analysis (15-20 pages)',
'Proprietary AI-powered competitive intelligence',
'Strategic opportunity assessment & validation',
'C-suite ready executive presentation',
'Strategic consultation call included',
'Next day white-glove delivery'
],
metadata: {
deliveryTime: 'Next day',
reportPages: '15-20',
targetRevenue: '$1M-$5M'
},
active: true
}
// ... other services
};
let sql = `-- ============================================
-- Service Synchronization SQL
-- Generated: ${new Date().toISOString()}
-- Source: Frontend services.config.ts
-- ============================================
-- Clear existing active services (optional - comment out if preserving other data)
-- UPDATE services SET active = 0 WHERE active = 1;
-- Sync services from frontend configuration
`;
Object.values(frontendServices).forEach(service => {
const metadata = JSON.stringify({
features: service.features,
...service.metadata
});
sql += `
-- ${service.name}
INSERT OR REPLACE INTO services (
id, name, description, min_price, max_price, deposit_amount,
billing_type, metadata, active, created_at
) VALUES (
'${service.id}',
'${service.name}',
'${service.description.replace(/'/g, "''")}',
${service.price.value},
${service.price.value},
${service.deposit.amount},
'${service.billingType}',
'${metadata.replace(/'/g, "''")}',
${service.active ? 1 : 0},
datetime('now')
);
`;
});
return sql;
}
// Generate and save the SQL
const sql = generateSyncSQL();
const outputPath = path.join(process.cwd(), 'sync-services-from-frontend.sql');
fs.writeFileSync(outputPath, sql);
console.log(`β
SQL sync script generated: ${outputPath}`);Script 2: Automated Sync Command β
Create: C:\workspace\scripts\sync-services.sh
#!/bin/bash
# ============================================
# Automated Service Synchronization Script
# Usage: ./scripts/sync-services.sh [environment]
# ============================================
set -e
ENVIRONMENT=${1:-production}
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
LOG_FILE="sync-services-$TIMESTAMP.log"
echo "π StratIQX Service Synchronization" | tee $LOG_FILE
echo "Environment: $ENVIRONMENT" | tee -a $LOG_FILE
echo "Timestamp: $(date)" | tee -a $LOG_FILE
echo "============================================" | tee -a $LOG_FILE
# Step 1: Generate sync SQL from frontend config
echo "π Step 1: Generating sync SQL..." | tee -a $LOG_FILE
node scripts/generate-service-sync.js >> $LOG_FILE 2>&1
# Step 2: Backup database
echo "πΎ Step 2: Creating database backup..." | tee -a $LOG_FILE
wrangler d1 export stratiqx-main --output="backup-before-sync-$TIMESTAMP.sql" --env=$ENVIRONMENT >> $LOG_FILE 2>&1
# Step 3: Execute sync SQL
echo "π Step 3: Executing service sync..." | tee -a $LOG_FILE
wrangler d1 execute stratiqx-main --file="sync-services-from-frontend.sql" --env=$ENVIRONMENT --remote >> $LOG_FILE 2>&1
# Step 4: Deploy worker to clear cache
echo "π Step 4: Deploying worker to clear cache..." | tee -a $LOG_FILE
cd ../stratiqx-payment
wrangler deploy --env=$ENVIRONMENT >> ../$LOG_FILE 2>&1
cd ../scripts
echo "β
Synchronization Complete!" | tee -a $LOG_FILEScript 3: Service Configuration Validator β
Create: C:\workspace\scripts\validate-service-sync.js
/**
* Validate service synchronization between frontend and backend
* Usage: node scripts/validate-service-sync.js
*/
import fetch from 'node-fetch';
async function validateServiceSync() {
console.log('π Validating Service Synchronization...\n');
try {
// Fetch services from API
const response = await fetch('https://payments.stratiqx.ai/services');
const data = await response.json();
if (!data.success || !data.services) {
throw new Error('Invalid API response');
}
console.log(`β
API returned ${data.services.length} services\n`);
// Expected services from frontend config
const expectedServices = {
'market-essentials': { price: 1495, deposit: 299 },
'market-intelligence': { price: 2995, deposit: 599 },
'strategic-analysis': { price: 4995, deposit: 999 },
'ongoing-retainer': { price: 3500, deposit: 3500 }
};
// Validate each expected service
let syncErrors = [];
for (const [serviceId, expected] of Object.entries(expectedServices)) {
const apiService = data.services.find(s => s.id === serviceId);
if (!apiService) {
syncErrors.push(`β Service '${serviceId}' not found in API`);
continue;
}
// Check price and deposit
if (apiService.priceRange.min !== expected.price) {
syncErrors.push(`β ${serviceId}: Price mismatch. Expected: $${expected.price}, Got: $${apiService.priceRange.min}`);
}
if (apiService.depositAmount !== expected.deposit) {
syncErrors.push(`β ${serviceId}: Deposit mismatch. Expected: $${expected.deposit}, Got: $${apiService.depositAmount}`);
}
if (syncErrors.length === 0) {
console.log(`β
${serviceId}: Price $${apiService.priceRange.min}, Deposit $${apiService.depositAmount}`);
}
}
// Report results
if (syncErrors.length > 0) {
console.log('\nπ¨ Synchronization Issues Found:');
syncErrors.forEach(error => console.log(error));
console.log('\nπ§ Run sync script: ./scripts/sync-services.sh');
process.exit(1);
} else {
console.log('\nπ All services are properly synchronized!');
console.log('β
Frontend and backend are in perfect sync');
}
} catch (error) {
console.error('β Validation failed:', error.message);
process.exit(1);
}
}
validateServiceSync();π Manual Sync Procedure β
When Frontend Configuration Changes: β
Update Frontend Config
bash# Edit src/config/services.config.ts # Make your changes to pricing, features, etc.Generate Sync SQL
bashcd C:\workspace\scripts node generate-service-sync.jsReview Generated SQL
bash# Check sync-services-from-frontend.sql # Verify the changes look correctBackup Database
bashcd C:\workspace\stratiqx-payment wrangler d1 export stratiqx-main --output="backup-$(date +%Y%m%d_%H%M%S).sql" --env=productionExecute Sync
bashwrangler d1 execute stratiqx-main --file="../scripts/sync-services-from-frontend.sql" --env=production --remoteClear Cache
bashwrangler deploy --env=productionDeploy Frontend
bashcd ../strategic-intelligence-onboarding npm run deployValidate Sync
bashcd ../scripts node validate-service-sync.jsTest Payment Flow
- Go to https://preview.stratiqx.ai/payment
- Test each modified service
- Verify no validation errors
β οΈ Common Sync Issues β
1. Cache Not Clearing β
Symptom: API returns old data after sync Solution:
# Force clear cache with timestamp
curl "https://payments.stratiqx.ai/services?bust=$(date +%s)"
# Or wait 5 minutes for natural cache expiry2. Deposit Amount Mismatch β
Symptom: "Minimum deposit required" error Solution: Check frontend deposit.amount matches backend deposit_amount
3. Service Not Found β
Symptom: "Service 'xxx' not found or inactive" Solution: Verify service exists in database and active = 1
4. JSON Metadata Errors β
Symptom: Database insert fails with JSON error Solution: Escape quotes in metadata: metadata.replace(/'/g, "''")
π Automated Sync Workflow β
GitHub Action (Optional) β
Create .github/workflows/sync-services.yml:
name: Sync Services
on:
push:
paths: ['src/config/services.config.ts']
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
- name: Install wrangler
run: npm install -g wrangler
- name: Sync services
run: ./scripts/sync-services.sh production
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}π Monitoring and Alerting β
Service Sync Health Check β
# Add to cron or monitoring system
*/15 * * * * cd /path/to/scripts && node validate-service-sync.js || echo "Service sync check failed" | mail -s "StratIQX Sync Alert" admin@stratiqx.aiπ― Best Practices β
- Always Backup before sync operations
- Validate Changes using the validation script
- Test Payment Flow after every sync
- Monitor Logs for sync failures
- Use Staging environment for testing major changes
- Document Changes in service audit log
- Version Control all sync scripts and configurations
π Quick Reference β
Key Files β
- Frontend Config:
src/config/services.config.ts - Backend Schema:
servicestable in D1 database - Sync Scripts:
scripts/directory - API Endpoint:
https://payments.stratiqx.ai/services
Key Commands β
# Generate sync SQL
node scripts/generate-service-sync.js
# Full automated sync
./scripts/sync-services.sh production
# Validate sync
node scripts/validate-service-sync.js
# Manual database query
wrangler d1 execute stratiqx-main --command="SELECT * FROM services" --env=production --remoteThis guide ensures your frontend and backend services stay perfectly synchronized! π―