You are an expert full-stack SaaS engineering team tasked with building a complete, production-ready, multi-tenant AI Voice Assistant platform called Zyvra.

This system must be built as a web-based SaaS (not mobile) product, combining a secure backend, responsive frontend, AI voice simulation engine, and enterprise billing/analytics features.

Follow the full specification below exactly and deliver a working, well-documented project inside this Replit workspace.

🌍 Overview

Zyvra is an AI-powered voice assistant platform for enterprise clients (banks, call centers, fintech, healthcare, telecom, insurance).
It handles incoming calls, simulates AI responses, generates transcripts, analyzes sentiment, and automatically bills tenants per call.

🧩 Technology Stack (Replit AI decides best tools)

You may choose the stack, but prefer modern web technologies:

Frontend: React or Next.js, TailwindCSS, shadcn/ui

Backend: Node.js (NestJS or Express) or Python (FastAPI)

Database: PostgreSQL with row-level security (RLS)

Realtime: WebSockets or Server-Sent Events

Auth: JWT, OAuth, or SSO (SAML/OIDC optional)

Payments: Stripe (test mode ok)

Deployment: Docker Compose (local) or Kubernetes (Helm)

Justify core tech choices in a short README.md.

🧱 STEP 1 — Data Entities (with RLS)

Create the following database entities (JSON schema + SQL migrations):

Tenant

User

CallSession

KnowledgeBase

Invoice

BillingActivity

SystemLog

Each table must include:

Tenant scoping (via tenant_id)

Created/updated timestamps

Row-level security enabled

Example SQL:

ALTER TABLE call_sessions ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON call_sessions
  USING (tenant_id = current_setting('app.current_tenant')::uuid);


Include all migration files in /migrations.

🎨 STEP 2 — UI & LAYOUT

Create a dark-mode-first responsive layout:

Sidebar with Lucide icons (Shield, Phone, Users, Settings, BarChart3)

Role-based navigation (superadmin, tenant_admin, agent, billing_manager)

User avatar menu (Settings, Logout, Theme toggle)

Tenant info display (for non-superadmins)

Header with active page title

Design spec:

Background: bg-slate-950

Cards: bg-slate-900/50 border-slate-800

Accent gradient: from-indigo-600 to-cyan-600

Accessible + smooth animations

🌐 STEP 3 — Public Pages

Home: hero section, CTAs (“Start Free Trial”, “Schedule Demo”), 6 features, global stats.

Features: detailed breakdown of capabilities.

Pricing:

Plan	Price	Per Call	Limit
Starter	$49/mo	$0.08	500 calls
Professional	$199/mo	$0.06	5,000 calls
Enterprise	$499/mo	$0.04	Unlimited

Contact: name, email, company, message form (mock email sender).

Docs: API reference, Quick Start, Authentication, Calls API, Analytics, Webhooks, Testing Portal.

All pages must be fully responsive and in dark theme.

🔐 STEP 4 — Authentication & Onboarding

Pages:

Login: secure email/password form, logs attempts to SystemLog.

Register: 3-step wizard — Account → Company → Plan.

ForgotPassword / ResetPassword: secure token reset.

Rules:

Redirect after login:

Superadmin → /admin/dashboard

Others → /client/dashboard

Never redirect to Home after login.

JWT-based auth, CSRF protected, bcrypt/argon2 for passwords.

📊 STEP 5 — Dashboards
Admin Dashboard

KPIs: Tenants, Users, Total Calls, Monthly Revenue

Charts: Revenue trend, Plan distribution

Recent tenants table

Client Dashboard

KPIs: Total Calls, Avg Duration, Success Rate

Charts: Calls over time, Sentiment distribution

Recent call table

⚡ STEP 6 — Realtime & Simulation
Realtime Dashboard

Live metrics (calls today, active calls, avg sentiment, success rate)

Auto-refresh via React Query (refetchInterval: 3000)

Filters (Today, 7d, 30d, 90d)

Charts: line, bar, pie

Simulation Page

Choose scenario: Banking, Healthcare, Retail, Insurance, etc.

Each scenario has messages[] = {role, text, sentiment, confidence}

Messages appear with a 2.5s delay

Use this TTS:

const speakText = (text) => {
  const u = new SpeechSynthesisUtterance(text);
  u.rate = 0.85; u.pitch = 1.0; u.volume = 0.9;
  window.speechSynthesis.speak(u);
};


On simulation start:

Create CallSession

Call BillingService.trackCall()

Show results: sentiment, duration, confidence

📞 STEP 7 — Call Management

LiveCalls: auto-refresh list of active calls

CallHistory: searchable/filterable/exportable

CallRecordings: play/download/delete (log actions)

📈 STEP 8 — Analytics
ClientAnalytics

KPIs: Avg Duration, Success Rate, Escalation Rate, Satisfaction

Charts: 30-day trends, sentiment pie, hourly bar chart

AdminAnalytics

Platform metrics: calls by industry, revenue growth, plan distribution

Use Recharts or Chart.js, interactive and accessible.

🧑‍💼 STEP 9 — Organization Management

Team: invite members, assign roles, remove users

KnowledgeBase: CRUD + search

ClientSettings: tabs for General, AI Assistant (voice, tone), Security (2FA), Integrations (webhooks)

APIKeys: show/hide, regenerate, copy

ClientBilling: invoices, plan upgrades, usage stats

🧰 STEP 10 — Admin Pages

AdminTenants: list/filter tenants

AdminUsers: list/edit roles

AdminRoles: view/manage role permissions

AdminLogs: system logs with filters + export

💳 STEP 11 — Backend Services
BillingService.js
const BillingService = {
  trackCall: async (callSession) => {
    // Get tenant info
    // Compute cost = duration * tenant.per_call_rate
    // Create BillingActivity record
    // Update usage metrics
    // Emit webhook or event
  }
};
export default BillingService;

Others

CallProcessor: transcribe, sentiment analysis, store transcript, emit webhooks.

AuditService: system logs for all user actions.

⚙️ STEP 12 — Infrastructure

Security: CSRF, XSS, rate limiting, password hashing, JWT validation

Observability: structured logs, metrics, error reporting

Backups: DB dump + restore script

CI/CD: build → test → deploy pipeline

Scaling: WebSocket load handling and caching (Redis recommended)

💅 STEP 13 — Design & Accessibility

Default dark mode

Gradient accent (indigo → cyan)

Accessible (WCAG 2.1 AA)

Toasts for errors/success

Smooth transitions

🧪 STEP 14 — Testing

Unit tests for backend services

Integration tests for auth + billing

e2e tests for full tenant lifecycle

Include demo fixtures (sample tenant + calls)

📘 STEP 15 — Documentation

Provide:

README.md — setup, run, deploy

OPS.md — infra, scaling, backup, observability

API.md — endpoints (POST /calls, GET /calls, etc.)

Webhook events:

call.started

call.completed

call.escalated

transcript.updated

✅ ACCEPTANCE CHECKLIST

 Entities + migrations + RLS

 Layout + theme

 Public pages

 Auth + redirect rules

 Admin + Client dashboards

 Realtime dashboard + Simulation

 Analytics

 Team, KB, Billing, API Keys

 Admin pages

 BillingService + CallProcessor

 Tests + CI/CD

 Full documentation

🚀 Final Instructions for Replit AI

Implement the full project inside this Replit workspace.

Structure it as a runnable web app (frontend + backend + database).

Include working auth, dashboards, simulations, and mock AI logic.

Store secrets in .env.example.

Add demo script:

Register new tenant

Invite agent

Run voice simulation

View analytics + billing

Deliver complete code + docs.