Cleveland Kitchen POC - WhereFour Integration Implementation
Date: March 6, 2026
Status: Backend Complete, UI/Routes Complete, Integration Pending
Feature Flag: wherefour-order-validation
Architecture Overview
Section titled “Architecture Overview”The CK POC uses Temporal-based durable transactions for order submission with feature flag controls.
┌─────────────────┐│ Webapp UI │ /orders/wherefour-submit.astro│ (Astro Page) │ ✓ Feature flag gated└────────┬────────┘ │ ▼┌─────────────────────────────────────────┐│ API Route: /api/integrations/wherefour ││ /validate-order (POST) ││ ││ - Auth check ││ - Feature flag: wherefour-order-... ││ - Call Temporal workflow ││ - Return discount chip │└────────┬────────────────────────────────┘ │ ▼┌──────────────────────────────────────┐│ Temporal Workflow ││ WhereFourOrderSubmissionWorkflow ││ ││ 1. fetch_order_from_api() [GET] ││ 2. get_pricing_tiers() [Cache] ││ 3. validate_order() [Python] ││ 4. calculate_discount() [Python] ││ 5. store_audit_log() [DB] ││ 6. (mock) submit [DISABLED] │└──────────────────────────────────────┘Files Created
Section titled “Files Created”Backend (Temporal Worker)
Section titled “Backend (Temporal Worker)”- ✅
apps/temporal-worker/workflows/wherefour_order_submission.py- Main workflow - ✅
apps/temporal-worker/activities/wherefour.py- GET activities - ✅
apps/temporal-worker/activities/wherefour_audit.py- Audit logging - ✅
apps/temporal-worker/activities/wherefour_mock.py- Mock submission
Database
Section titled “Database”- ✅
packages/db/src/schema/integration-audit-trail.ts- Audit schema - ⏳
packages/db/src/migrations/0001_integration_audit.sql- Generated by Drizzle
Webapp API
Section titled “Webapp API”- ✅
apps/webapp/src/pages/api/integrations/wherefour/validate-order.ts- Validation endpoint
Webapp UI
Section titled “Webapp UI”- ✅
apps/webapp/src/pages/orders/wherefour-submit.astro- Order submit page - ✅
apps/webapp/src/components/integrations/WhereFourDiscountChip.tsx- Discount component
Documentation
Section titled “Documentation”- ✅
docs/ck-poc-implementation.md- This file - ✅
docs/integration-architecture-pattern.md- Architecture pattern
Feature Flag Configuration
Section titled “Feature Flag Configuration”In Flagsmith Dashboard
Section titled “In Flagsmith Dashboard”Flag Name: wherefour-order-validation
Type: Boolean (Enable/Disable)
Targeting Rules:
Environment: development|staging → ENABLEDOrganization: CK Team → ENABLEDSubscription: professional+ → ENABLEDBeta Enabled: true → ENABLEDDefault → DISABLEDTraits Available (from @repo/feature-flags):
organizationId- Clerk org IDemail- User emailsubscriptionTier- free|starter|professional|enterprisebetaEnabled- Booleanenvironment- development|staging|production
Usage in Code
Section titled “Usage in Code”// Check if feature is enabled for userimport { isFeatureEnabled, type FlagsmithIdentity } from '@repo/feature-flags/server';
const identity: FlagsmithIdentity = { identifier: session.user.id, traits: { organizationId: session.orgId, email: session.user.email, environment: process.env.NODE_ENV, },};
const enabled = await isFeatureEnabled('wherefour-order-validation', identity);
if (!enabled) { return new Response('Feature not available', { status: 403 });}Data Flow
Section titled “Data Flow”1. User Navigates to Order Submission
Section titled “1. User Navigates to Order Submission”GET /orders/wherefour-submit ├─ Check auth (redirect if not logged in) ├─ Check feature flag: wherefour-order-validation └─ Return page (or redirect if disabled)2. User Enters Order ID & Clicks Validate
Section titled “2. User Enters Order ID & Clicks Validate”POST /api/integrations/wherefour/validate-order ├─ Body: { orderId: 123 } ├─ Auth check ├─ Feature flag check: wherefour-order-validation ├─ Call Temporal: │ └─ WhereFourOrderSubmissionWorkflow │ ├─ fetch_order_from_api(123) [GET /orders/123] │ ├─ get_pricing_tiers_from_cache() [Redis] │ ├─ get_customer_metadata() [Redis/API] │ ├─ validate_order() [Pure Python] │ ├─ calculate_discount() [Pure Python] │ └─ store_audit_log() [PostgreSQL] │ └─ Return DiscountChip: { original_total: 3275.16, new_total: 3208.32, discount_amount: 66.84, discount_percent: 2.04, pricing_tier_applied: "Sample Tier", notes: [...] }3. UI Displays Discount Chip
Section titled “3. UI Displays Discount Chip”Component: WhereFourDiscountChip
- Shows original → new total
- Shows discount amount & %
- Shows pricing tier
- Confirm/Cancel buttons
4. User Confirms (Mock)
Section titled “4. User Confirms (Mock)”(Button click) └─ Log to audit trail └─ Show mock PO ID └─ Workflow completeSafety Mechanisms
Section titled “Safety Mechanisms”1. Feature Flag Gating
Section titled “1. Feature Flag Gating”- Every endpoint checks
wherefour-order-validationflag - Disabled by default → opt-in per environment
- Can enable for specific users/orgs only
2. Mock Submission (Production Safety)
Section titled “2. Mock Submission (Production Safety)”submit_to_wherefour_mock()returns mock PO ID- Real submission blocked with error message
- Awaiting sandbox account credentials
3. Audit Trail Logging
Section titled “3. Audit Trail Logging”- Every operation logged to
integration_audit_trailtable - Includes workflow_id for tracing
- Tracks request/response payloads
- Required for compliance
4. Workflow Retry Logic
Section titled “4. Workflow Retry Logic”- Automatic retry with exponential backoff (3 attempts)
- Timeouts: 30s for API calls, 5s for cache reads
- Failures logged and returned to user
5. Error Handling
Section titled “5. Error Handling”- All errors returned as HTTP responses
- No details leaked (generic error message to client)
- Full error logged server-side for debugging
Testing Checklist
Section titled “Testing Checklist”Before enabling feature flag in production:
Local Development
Section titled “Local Development”- Start Temporal worker:
pnpm --filter temporal-worker dev - Start webapp:
pnpm --filter webapp dev - Enable flag in Flagsmith dashboard (development environment)
- Navigate to
/orders/wherefour-submit - Enter mock order ID (e.g., 4832453)
- Click “Validate Order”
- Verify discount chip displays
- Check audit trail:
SELECT * FROM integration_audit_trail WHERE integration_name='wherefour'
Staging Environment
Section titled “Staging Environment”- Deploy to staging
- Enable flag in Flagsmith (staging environment)
- Test full flow with real WhereFour sandbox account
- Verify pricing tier calculations
- Load test: 100+ concurrent validations
- Monitor: Check logs, metrics, error rates
Production Rollout
Section titled “Production Rollout”- Enable for 5% of users (beta testers)
- Monitor for 24 hours (errors, performance)
- Enable for 25% of users
- Monitor for 24 hours
- Enable for 100% if no issues
- Have rollback plan (disable flag instantly)
Database Setup
Section titled “Database Setup”Create Audit Trail Table
Section titled “Create Audit Trail Table”# Generate migration from Drizzle schemapnpm --filter @repo/db db:generate
# Apply migrationpnpm --filter @repo/db db:migrate
# Verify table createdpsql $DATABASE_URL -c "SELECT * FROM information_schema.tables WHERE table_name='integration_audit_trail';"Environment Variables (Required)
Section titled “Environment Variables (Required)”Already configured:
WHEREFOUR_SCRAPE_USER- Username for WhereFour APIWHEREFOUR_API_KEY- API key for WhereFour APIREDIS_URL- Redis connection for cachingDATABASE_URL- PostgreSQL for audit trailTEMPORAL_*- Temporal connection detailsFLAGSMITH_API_URL- Flagsmith API endpointFLAGSMITH_ENVIRONMENT_KEY- Flagsmith env key
Next Steps
Section titled “Next Steps”Immediate (This PR)
Section titled “Immediate (This PR)”- Review webapp routes + UI
- Generate database migration
- Commit all changes
- Create PR to staging
Next (After PR Merge)
Section titled “Next (After PR Merge)”- Deploy to staging
- Run database migration in staging
- Enable feature flag in Flagsmith (staging only)
- E2E testing in staging
- Get approval for production
Production (Week 2)
Section titled “Production (Week 2)”- Gradual rollout: 5% → 25% → 100%
- Monitor error rates + performance
- Collect user feedback
- Gather real discount data
Future (When Sandbox Available)
Section titled “Future (When Sandbox Available)”- Replace mock submission with real implementation
- Test full order submission to WhereFour
- Create rollback plan
- Production rollout for real submissions
Rollback Plan
Section titled “Rollback Plan”If issues detected:
Immediate
Section titled “Immediate”# Disable feature flag in Flagsmith# Reduces enabled% to 0 instantly# Users see "Feature not available" errorIf Needed
Section titled “If Needed”# Revert webapp commitgit revert <commit-hash>
# Clear audit trail cache (if needed)redis-cli DEL wherefour:*
# Check logskubectl logs -f deployment/webappMonitoring & Debugging
Section titled “Monitoring & Debugging”Audit Trail Query
Section titled “Audit Trail Query”-- See all WhereFour operationsSELECT workflow_id, operation, status, error_message, created_atFROM integration_audit_trailWHERE integration_name = 'wherefour'ORDER BY created_at DESCLIMIT 20;
-- See failures onlySELECT workflow_id, operation, error_message, created_atFROM integration_audit_trailWHERE integration_name = 'wherefour' AND status = 'FAILURE'ORDER BY created_at DESC;Temporal UI
Section titled “Temporal UI”http://localhost:8233 (dev)- Search workflows by ID- Replay failed workflows- View execution history# Webapptail -f logs/webapp.log | grep wherefour
# Temporal workertail -f logs/temporal-worker.log | grep wherefourSummary
Section titled “Summary”| Component | Status | Safety Level |
|---|---|---|
| Backend (Temporal) | ✅ Complete | ⛔ PRODUCTION READY |
| API Routes | ✅ Complete | ⛔ GATED BY FEATURE FLAG |
| UI Components | ✅ Complete | ⛔ GATED BY FEATURE FLAG |
| Database | ✅ Schema | ⏳ MIGRATION PENDING |
| Mock Submission | ✅ Complete | ⛔ NO WRITES TO ERP |
| Sandbox Testing | ⏳ BLOCKED | ⏳ AWAITING CREDENTIALS |
| Production Ready | ❌ NO | ⏳ AFTER SANDBOX TESTING |
Next: Database migration + test in staging