Skip to content

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) ​

typescript
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) ​

sql
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 IDFrontend NamePriceDepositBackend Status
market-essentialsMarket Essentials$1,495$299βœ… Synced
market-intelligenceMarket Intelligence Pro$2,995$599βœ… Synced
strategic-analysisStrategic Analysis & Advisory$4,995$999βœ… Synced
ongoing-retainerOngoing Intelligence Retainer$3,500/mo$3,500βœ… Synced
competitor-trackingReal-Time Competitor Intelligence$3,495/moComing Soon⏳ Inactive
market-pulse-executiveMarket Pulse - Executive ReportFree$0⏳ Inactive

πŸ”„ Synchronization Process ​

When Frontend Changes Occur: ​

  1. Service Configuration Update (services.config.ts)
  2. Run Sync Script (auto-generates SQL)
  3. Execute SQL (updates database)
  4. Clear Cache (forces API refresh)
  5. Deploy Frontend (if needed)
  6. Test Payment Flow

πŸ› οΈ Synchronization Scripts ​

Script 1: Generate Sync SQL from Frontend Config ​

Create: C:\workspace\scripts\generate-service-sync.js

javascript
/**
 * 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

bash
#!/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_FILE

Script 3: Service Configuration Validator ​

Create: C:\workspace\scripts\validate-service-sync.js

javascript
/**
 * 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: ​

  1. Update Frontend Config

    bash
    # Edit src/config/services.config.ts
    # Make your changes to pricing, features, etc.
  2. Generate Sync SQL

    bash
    cd C:\workspace\scripts
    node generate-service-sync.js
  3. Review Generated SQL

    bash
    # Check sync-services-from-frontend.sql
    # Verify the changes look correct
  4. Backup Database

    bash
    cd C:\workspace\stratiqx-payment
    wrangler d1 export stratiqx-main --output="backup-$(date +%Y%m%d_%H%M%S).sql" --env=production
  5. Execute Sync

    bash
    wrangler d1 execute stratiqx-main --file="../scripts/sync-services-from-frontend.sql" --env=production --remote
  6. Clear Cache

    bash
    wrangler deploy --env=production
  7. Deploy Frontend

    bash
    cd ../strategic-intelligence-onboarding
    npm run deploy
  8. Validate Sync

    bash
    cd ../scripts
    node validate-service-sync.js
  9. Test Payment Flow

⚠️ Common Sync Issues ​

1. Cache Not Clearing ​

Symptom: API returns old data after sync Solution:

bash
# Force clear cache with timestamp
curl "https://payments.stratiqx.ai/services?bust=$(date +%s)"
# Or wait 5 minutes for natural cache expiry

2. 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:

yaml
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 ​

bash
# 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 ​

  1. Always Backup before sync operations
  2. Validate Changes using the validation script
  3. Test Payment Flow after every sync
  4. Monitor Logs for sync failures
  5. Use Staging environment for testing major changes
  6. Document Changes in service audit log
  7. Version Control all sync scripts and configurations

πŸ“š Quick Reference ​

Key Files ​

  • Frontend Config: src/config/services.config.ts
  • Backend Schema: services table in D1 database
  • Sync Scripts: scripts/ directory
  • API Endpoint: https://payments.stratiqx.ai/services

Key Commands ​

bash
# 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 --remote

This guide ensures your frontend and backend services stay perfectly synchronized! 🎯

Strategic Intelligence Hub Documentation