Skip to content

Latest commit

 

History

History
1076 lines (901 loc) · 46.4 KB

File metadata and controls

1076 lines (901 loc) · 46.4 KB

LearnBack Platform — Phase 1 Build Prompt

WHAT YOU'RE BUILDING

LearnBack is an AI-powered after-school learning platform for Indian students (ages 6-18). It replaces rote memorization with real-world problem solving, tracks learning across 5 intelligence dimensions, and pays students back for learning through a virtual currency called Vidya Coins (VC). Parents pay a monthly subscription; the child earns back up to 75% of fees through demonstrated learning.

Phase 1 Positioning: After-school learning companion, NOT a school replacement. The pitch to parents: "Your child goes to school for board exams. LearnBack teaches them everything school doesn't — and pays them back for learning it."

Phase 1 Scope — BUILD these:

  • AI learning engine (Claude API) generating unique real-world problems
  • Vidya Coins earn-back system with streak multipliers
  • Student Intelligence Profile (5-dimension radar tracking)
  • Board exam prep module (CBSE, Telangana State Board, AP State Board, ICSE/ISC)
  • Parent dashboard with child progress, earn-back tracking, AI insights
  • Admin panel for student management, AI quality review, VC economy, billing
  • Razorpay/UPI payment integration with subscription management
  • Responsive web app (phone + laptop), English only
  • Email/password + Google OAuth authentication
  • All age groups 6-18 (Class 1-12)

Phase 1 Scope — DO NOT build these yet:

  • Physical Learning Circle scheduling
  • Pathfinder (mentor) dashboard
  • Content contributor marketplace
  • Multi-language support
  • NIOS exam prep
  • Peer teaching/collaboration features
  • Mobile native apps

TECH STACK

Frontend:       Next.js 14 (App Router) + React 18 + Tailwind CSS
Backend:        Next.js API Routes (serverless)
Database:       Supabase (PostgreSQL + Auth + Storage + Row Level Security)
AI Engine:      Anthropic Claude API (claude-sonnet-4-20250514)
Payments:       Razorpay (Subscriptions API + Payment Links + Webhooks)
Charts:         Recharts (for radar charts, progress bars, earn-back charts)
Icons:          Lucide React
Hosting:        Vercel (free tier for Phase 1)
Domain:         app.learnback.in

Install command:

npx create-next-app@latest learnback --typescript --tailwind --app
cd learnback
npm install @supabase/supabase-js @supabase/ssr @anthropic-ai/sdk razorpay recharts lucide-react

Environment variables needed (.env.local):

NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE_KEY=
ANTHROPIC_API_KEY=
RAZORPAY_KEY_ID=
RAZORPAY_KEY_SECRET=
RAZORPAY_WEBHOOK_SECRET=
RAZORPAY_PLAN_ID=
NEXT_PUBLIC_APP_URL=

PROJECT STRUCTURE

learnback/
├── app/
│   ├── (auth)/
│   │   ├── login/page.tsx
│   │   └── signup/page.tsx
│   ├── (student)/
│   │   ├── dashboard/page.tsx
│   │   ├── learn/page.tsx              # Domain picker + problem view
│   │   ├── learn/results/page.tsx      # Results after submission
│   │   ├── profile/page.tsx            # SIP radar, badges, streaks
│   │   ├── exam-prep/page.tsx          # Board prep home
│   │   ├── exam-prep/practice/page.tsx # Individual exam questions
│   │   └── exam-prep/mock-test/page.tsx
│   ├── (parent)/
│   │   ├── dashboard/page.tsx
│   │   ├── child/[id]/page.tsx         # Child detail view
│   │   ├── earnback/page.tsx
│   │   ├── insights/page.tsx
│   │   ├── subscribe/page.tsx
│   │   └── billing/page.tsx
│   ├── (admin)/
│   │   ├── dashboard/page.tsx
│   │   ├── students/page.tsx
│   │   ├── review/page.tsx             # AI quality review
│   │   ├── vc-economy/page.tsx
│   │   ├── billing/page.tsx            # Revenue, payouts
│   │   └── exam-config/page.tsx        # Board syllabi management
│   ├── api/
│   │   ├── auth/
│   │   │   ├── signup/route.ts
│   │   │   ├── login/route.ts
│   │   │   └── google/route.ts
│   │   ├── learn/
│   │   │   ├── generate/route.ts       # AI problem generation
│   │   │   ├── submit/route.ts         # AI evaluation + VC award
│   │   │   └── history/route.ts
│   │   ├── exam/
│   │   │   ├── boards/route.ts
│   │   │   ├── syllabus/route.ts
│   │   │   ├── generate/route.ts       # Board exam question generation
│   │   │   ├── submit/route.ts         # Board exam answer evaluation
│   │   │   ├── mock-test/route.ts
│   │   │   └── progress/route.ts
│   │   ├── vc/
│   │   │   ├── balance/route.ts
│   │   │   ├── ledger/route.ts
│   │   │   └── earnback/route.ts
│   │   ├── sip/
│   │   │   ├── dimensions/route.ts
│   │   │   └── history/route.ts
│   │   ├── streak/
│   │   │   ├── status/route.ts
│   │   │   └── checkin/route.ts
│   │   ├── parent/
│   │   │   ├── children/route.ts
│   │   │   ├── child/[id]/route.ts
│   │   │   └── insights/[id]/route.ts
│   │   ├── pay/
│   │   │   ├── create-subscription/route.ts
│   │   │   ├── webhooks/razorpay/route.ts
│   │   │   ├── subscription/[id]/route.ts
│   │   │   ├── cancel/route.ts
│   │   │   └── history/route.ts
│   │   ├── earnback/
│   │   │   ├── summary/route.ts
│   │   │   └── calculate/route.ts      # Admin: trigger monthly calc
│   │   └── admin/
│   │       ├── student/route.ts
│   │       ├── link/route.ts
│   │       └── overview/route.ts
│   ├── layout.tsx
│   └── page.tsx                        # Landing page
├── components/
│   ├── ui/                             # Reusable: Button, Card, Modal, Input, etc.
│   ├── student/                        # ProblemCard, ResultsCard, DomainPicker, SIPRadar, StreakBadge, VCCounter
│   ├── parent/                         # ChildCard, EarnbackChart, InsightCard
│   └── admin/                          # StatsCard, StudentTable, AIReviewCard
├── lib/
│   ├── supabase/
│   │   ├── client.ts                   # Browser client
│   │   ├── server.ts                   # Server client
│   │   └── middleware.ts               # Auth middleware
│   ├── ai/
│   │   ├── generate-problem.ts         # LearnBack Way problem generation
│   │   ├── evaluate-answer.ts          # Answer evaluation + reasoning scoring
│   │   ├── generate-insight.ts         # Parent weekly insights
│   │   ├── generate-exam-question.ts   # Board exam question generation
│   │   └── evaluate-exam-answer.ts     # Board exam answer evaluation
│   ├── vc/
│   │   ├── calculate.ts               # VC calculation logic
│   │   └── ledger.ts                  # Ledger operations
│   ├── sip/
│   │   ├── update-scores.ts
│   │   └── calculate-dimensions.ts
│   ├── payments/
│   │   ├── razorpay.ts                # Razorpay client setup
│   │   ├── subscriptions.ts           # Subscription CRUD
│   │   ├── webhooks.ts                # Webhook handlers
│   │   └── earnback.ts                # Monthly earn-back calculation
│   └── exam/
│       ├── syllabus.ts                # Syllabus data helpers
│       └── mock-test.ts              # Mock test generation + scoring
├── supabase/
│   └── migrations/
│       └── 001_initial_schema.sql     # All tables, RLS policies, indexes
├── public/
│   └── (static assets)
├── .env.local
├── package.json
├── tailwind.config.ts
└── tsconfig.json

DATABASE SCHEMA (16 TABLES)

Create all of these in a single Supabase migration file. Use Row-Level Security (RLS) on every table.

Users & Relationships

-- Extends Supabase auth.users
CREATE TABLE profiles (
  id UUID PRIMARY KEY REFERENCES auth.users(id) ON DELETE CASCADE,
  role TEXT NOT NULL CHECK (role IN ('student', 'parent', 'admin')),
  full_name TEXT NOT NULL,
  email TEXT NOT NULL,
  phone TEXT,
  city TEXT,
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE students (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  profile_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  age INTEGER NOT NULL CHECK (age BETWEEN 3 AND 20),
  grade INTEGER NOT NULL CHECK (grade BETWEEN 1 AND 12),
  learning_phase TEXT NOT NULL CHECK (learning_phase IN ('explorer', 'builder', 'quest', 'mastery')),
  -- explorer = ages 6-10, builder = ages 10-13, quest = ages 13-16, mastery = ages 16-18
  exam_board TEXT CHECK (exam_board IN ('CBSE', 'TS_SSC', 'TS_INTER', 'AP_SSC', 'AP_INTER', 'ICSE', 'ISC')),
  interests TEXT[],             -- array of interest tags for AI personalization
  daily_problem_count INTEGER DEFAULT 0,
  total_vc_earned INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE parent_student_link (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  parent_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  relationship TEXT DEFAULT 'parent',
  created_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE(parent_id, student_id)
);

Learning Activity

CREATE TABLE learning_sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  session_type TEXT NOT NULL CHECK (session_type IN ('learnback_way', 'exam_prep', 'mock_test')),
  domain TEXT,                  -- for learnback_way: thinking_skills, money_sense, communication, science_everyday, builder_challenges, world_society
  started_at TIMESTAMPTZ DEFAULT now(),
  ended_at TIMESTAMPTZ,
  total_problems INTEGER DEFAULT 0,
  total_vc_earned INTEGER DEFAULT 0
);

CREATE TABLE problems (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_id UUID NOT NULL REFERENCES learning_sessions(id) ON DELETE CASCADE,
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  domain TEXT NOT NULL,
  difficulty INTEGER NOT NULL CHECK (difficulty BETWEEN 1 AND 10),
  problem_text TEXT NOT NULL,           -- AI-generated problem scenario
  problem_metadata JSONB,               -- AI generation context (interests, city, etc.)
  student_answer TEXT,
  student_reasoning TEXT,
  is_correct BOOLEAN,
  reasoning_score INTEGER CHECK (reasoning_score BETWEEN 1 AND 10),
  ai_feedback TEXT,                     -- AI evaluation feedback
  ai_evaluation JSONB,                  -- Full AI evaluation response
  vc_earned INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT now(),
  submitted_at TIMESTAMPTZ
);

Vidya Coins & Streaks

CREATE TABLE vidya_coins_ledger (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  amount INTEGER NOT NULL,              -- positive = earned, negative = spent/adjusted
  source TEXT NOT NULL CHECK (source IN ('problem', 'mastery_gate', 'streak_bonus', 'exam_prep', 'mock_test', 'admin_adjustment')),
  reference_id UUID,                    -- problem_id or session_id that generated this
  description TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE streaks (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  current_streak INTEGER DEFAULT 0,
  longest_streak INTEGER DEFAULT 0,
  last_activity_date DATE,
  streak_multiplier NUMERIC(3,2) DEFAULT 1.00,
  -- 1-6 days: 1.0x, 7-29 days: 1.5x, 30-89 days: 2.0x, 90+ days: 3.0x
  updated_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE(student_id)
);

Student Intelligence Profile (SIP) & Achievements

CREATE TABLE sip_scores (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  dimension TEXT NOT NULL CHECK (dimension IN (
    'reasoning_pattern',     -- top-down vs bottom-up, linear vs lateral, ambiguity tolerance
    'domain_affinity',       -- which domains they engage with most deeply
    'learning_velocity',     -- how quickly they grasp new concepts per domain
    'communication_style',   -- best expression mode: writing, speaking, building
    'resilience_growth'      -- response to failure, retry patterns, help-seeking
  )),
  score NUMERIC(5,2) NOT NULL CHECK (score BETWEEN 0 AND 100),
  sub_scores JSONB,          -- granular breakdown within each dimension
  calculated_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE skill_badges (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  badge_name TEXT NOT NULL,              -- e.g. "Financial Reasoning L3", "Builder: First Prototype"
  badge_category TEXT NOT NULL,          -- domain or skill area
  badge_level INTEGER DEFAULT 1,
  earned_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE mastery_gates (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  domain TEXT NOT NULL,
  concept TEXT NOT NULL,
  gate_level INTEGER NOT NULL,
  passed BOOLEAN DEFAULT false,
  attempt_count INTEGER DEFAULT 0,
  vc_bonus INTEGER DEFAULT 0,           -- big VC reward on pass
  last_attempt_at TIMESTAMPTZ,
  passed_at TIMESTAMPTZ
);

Board Exam Prep

CREATE TABLE exam_boards (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  board_code TEXT NOT NULL UNIQUE,       -- CBSE, TS_SSC, TS_INTER, AP_SSC, AP_INTER, ICSE, ISC
  board_name TEXT NOT NULL,
  grade_range INT4RANGE NOT NULL,        -- [6,12] for CBSE, [6,10] for SSC, [11,12] for Inter
  subjects JSONB NOT NULL,               -- per-grade subject list with chapter names
  -- Structure: { "6": { "Mathematics": ["Knowing Our Numbers", "Whole Numbers", ...], "Science": [...] }, "7": {...} }
  exam_pattern JSONB,                    -- question types, marks distribution, time limits per subject
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE exam_prep_sessions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  board_code TEXT NOT NULL,
  grade INTEGER NOT NULL,
  subject TEXT NOT NULL,
  chapter TEXT,                          -- NULL for mock tests (full syllabus)
  session_type TEXT NOT NULL CHECK (session_type IN ('practice', 'mock_test')),
  total_questions INTEGER DEFAULT 0,
  correct_answers INTEGER DEFAULT 0,
  score_percentage NUMERIC(5,2),
  time_taken_seconds INTEGER,
  started_at TIMESTAMPTZ DEFAULT now(),
  completed_at TIMESTAMPTZ
);

CREATE TABLE exam_prep_questions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  session_id UUID NOT NULL REFERENCES exam_prep_sessions(id) ON DELETE CASCADE,
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  question_type TEXT NOT NULL CHECK (question_type IN ('mcq', 'short_answer', 'long_answer', 'numerical')),
  question_text TEXT NOT NULL,
  options JSONB,                         -- for MCQs: ["option A", "option B", "option C", "option D"]
  correct_answer TEXT,
  student_answer TEXT,
  is_correct BOOLEAN,
  marks_possible INTEGER DEFAULT 1,
  marks_obtained NUMERIC(5,2) DEFAULT 0,
  ai_feedback TEXT,
  solution_steps TEXT,                   -- AI-generated step-by-step solution
  common_mistakes TEXT,                  -- AI-generated common mistakes for this question
  vc_earned INTEGER DEFAULT 0,
  created_at TIMESTAMPTZ DEFAULT now(),
  submitted_at TIMESTAMPTZ
);

Payments & Billing

CREATE TABLE subscriptions (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  parent_id UUID NOT NULL REFERENCES profiles(id) ON DELETE CASCADE,
  razorpay_subscription_id TEXT UNIQUE,
  razorpay_plan_id TEXT,
  status TEXT NOT NULL DEFAULT 'created' CHECK (status IN ('created', 'authenticated', 'active', 'paused', 'cancelled', 'expired', 'halted')),
  amount_inr INTEGER NOT NULL DEFAULT 400000,  -- in paise (₹4,000 = 400000 paise)
  billing_cycle TEXT DEFAULT 'monthly',
  current_period_start TIMESTAMPTZ,
  current_period_end TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT now(),
  updated_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE(student_id)
);

CREATE TABLE payments (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  subscription_id UUID NOT NULL REFERENCES subscriptions(id) ON DELETE CASCADE,
  razorpay_payment_id TEXT UNIQUE,
  amount_inr INTEGER NOT NULL,           -- in paise
  status TEXT NOT NULL CHECK (status IN ('created', 'captured', 'failed', 'refunded')),
  payment_method TEXT,                   -- upi, card, netbanking
  paid_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT now()
);

CREATE TABLE earnback_payouts (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  student_id UUID NOT NULL REFERENCES students(id) ON DELETE CASCADE,
  month DATE NOT NULL,                   -- first day of the month
  total_vc_earned INTEGER NOT NULL,
  vc_to_inr_rate NUMERIC(5,2) DEFAULT 0.10,  -- 1 VC = ₹0.10
  earnback_amount_inr NUMERIC(10,2) NOT NULL,
  fee_paid_inr NUMERIC(10,2) NOT NULL,
  earnback_pct NUMERIC(5,2) NOT NULL,
  max_earnback_pct NUMERIC(5,2) DEFAULT 75.00,
  status TEXT DEFAULT 'calculated' CHECK (status IN ('calculated', 'approved', 'applied', 'paid_out')),
  created_at TIMESTAMPTZ DEFAULT now(),
  UNIQUE(student_id, month)
);

RLS Policies (apply to ALL tables)

-- Students can only see/edit their own data
-- Parents can see data for their linked children
-- Admins can see everything
-- Use supabase auth.uid() for current user

-- Example pattern for each table:
ALTER TABLE profiles ENABLE ROW LEVEL SECURITY;

CREATE POLICY "Users can view own profile" ON profiles
  FOR SELECT USING (id = auth.uid());

CREATE POLICY "Users can update own profile" ON profiles
  FOR UPDATE USING (id = auth.uid());

-- For student data tables, parents need access via parent_student_link:
CREATE POLICY "Parents can view linked students" ON students
  FOR SELECT USING (
    profile_id = auth.uid()
    OR id IN (
      SELECT student_id FROM parent_student_link WHERE parent_id = auth.uid()
    )
  );

-- Admin override (check role in profiles):
CREATE POLICY "Admins can view all" ON students
  FOR ALL USING (
    EXISTS (SELECT 1 FROM profiles WHERE id = auth.uid() AND role = 'admin')
  );

-- Apply similar patterns to ALL tables.

Indexes

CREATE INDEX idx_problems_student_id ON problems(student_id);
CREATE INDEX idx_problems_session_id ON problems(session_id);
CREATE INDEX idx_vc_ledger_student_id ON vidya_coins_ledger(student_id);
CREATE INDEX idx_vc_ledger_created_at ON vidya_coins_ledger(created_at);
CREATE INDEX idx_sip_scores_student ON sip_scores(student_id, dimension);
CREATE INDEX idx_exam_prep_sessions_student ON exam_prep_sessions(student_id);
CREATE INDEX idx_exam_prep_questions_session ON exam_prep_questions(session_id);
CREATE INDEX idx_subscriptions_student ON subscriptions(student_id);
CREATE INDEX idx_payments_subscription ON payments(subscription_id);
CREATE INDEX idx_earnback_student_month ON earnback_payouts(student_id, month);
CREATE INDEX idx_streaks_student ON streaks(student_id);
CREATE INDEX idx_parent_student_link_parent ON parent_student_link(parent_id);
CREATE INDEX idx_parent_student_link_student ON parent_student_link(student_id);

AI ENGINE — PROBLEM GENERATION & EVALUATION

This is the core of the platform. Two modes: "LearnBack Way" (real-world problems) and "Board Prep" (exam-style questions).

LearnBack Way — Problem Generation Flow

8-step flow:

  1. Student taps "LearnBack Way" and picks a domain (or "Surprise Me")
  2. System builds context payload: age, grade, learning_phase, SIP scores, interests, city, recent problem history (last 10)
  3. API call to Claude to generate a unique real-world problem
  4. Problem displayed to student
  5. Student submits answer + reasoning (text input or future: audio)
  6. API call to Claude to evaluate: correctness, reasoning quality (1-10), effort, creativity
  7. Vidya Coins calculated: base_vc = difficulty × reasoning_score, then final_vc = base_vc × streak_multiplier
  8. SIP scores updated in background based on evaluation

System Prompt for LearnBack Way Problem Generation

// lib/ai/generate-problem.ts

const SYSTEM_PROMPT = `You are the LearnBack AI Learning Engine. You generate unique, real-world problems for Indian students that teach through scenarios they encounter in daily life.

RULES:
1. NEVER generate textbook-style questions. Every problem must be a real-world scenario.
2. The problem must be solvable by the student's age/grade level but require genuine thinking, not just formula application.
3. Use Indian context — rupees (₹), Indian cities, Indian food, cricket, festivals, local businesses, family scenarios.
4. Personalize using the student's interests and city when provided.
5. Each problem must test reasoning, not memorization.
6. Include enough context that the student can work through the problem without external resources.
7. NEVER repeat a problem pattern from the student's recent history.

OUTPUT FORMAT (respond in JSON only):
{
  "problem_text": "The full problem scenario (2-4 paragraphs, engaging, conversational)",
  "domain": "the learning domain",
  "concepts_tested": ["list", "of", "concepts"],
  "difficulty": 1-10,
  "expected_reasoning": "brief description of the ideal reasoning approach",
  "hints": ["hint 1 if stuck", "hint 2 if really stuck"],
  "real_world_connection": "why this matters in real life"
}`;

// Context payload sent with each generation request
interface ProblemContext {
  student: {
    age: number;
    grade: number;
    learning_phase: string;
    interests: string[];
    city: string;
  };
  sip: {
    reasoning_pattern: number;
    domain_affinity: number;
    learning_velocity: number;
    communication_style: number;
    resilience_growth: number;
  };
  domain: string;           // chosen domain or "surprise_me"
  recent_problems: string[]; // last 10 problem summaries to avoid repetition
  difficulty_target: number; // calibrated based on recent performance
}

System Prompt for Answer Evaluation

// lib/ai/evaluate-answer.ts

const EVALUATION_PROMPT = `You are evaluating a student's answer to a LearnBack problem. You care about HOW they think, not just whether they're right.

EVALUATE THESE DIMENSIONS:
1. correctness: Is the answer factually/mathematically correct? (boolean)
2. reasoning_score: Quality of reasoning shown (1-10)
   - 1-3: No reasoning, just a guess or formula dump
   - 4-5: Some reasoning but incomplete or flawed logic
   - 6-7: Solid reasoning, clear logical steps
   - 8-9: Excellent reasoning with creative connections
   - 10: Exceptional — novel approach, deep insight
3. effort: Did they genuinely try? (low/medium/high)
4. creativity: Did they approach it in an unexpected way? (boolean)
5. growth_signal: Compared to what's expected at their level, is this above/at/below?

OUTPUT FORMAT (respond in JSON only):
{
  "correctness": true/false,
  "reasoning_score": 1-10,
  "effort": "low" | "medium" | "high",
  "creativity": true/false,
  "growth_signal": "above" | "at" | "below",
  "feedback": "2-3 sentences of encouraging, specific feedback. Acknowledge what they did well. If wrong, guide them toward the right thinking without giving the answer. Be warm and motivating, like a great mentor.",
  "concepts_demonstrated": ["concepts the student showed understanding of"],
  "concepts_to_work_on": ["concepts that need more practice"],
  "sip_updates": {
    "reasoning_pattern": -2 to +2 adjustment,
    "domain_affinity": -2 to +2 adjustment,
    "learning_velocity": -2 to +2 adjustment,
    "communication_style": -2 to +2 adjustment,
    "resilience_growth": -2 to +2 adjustment
  }
}`;

Vidya Coins Calculation

// lib/vc/calculate.ts

function calculateVC(
  difficulty: number,       // 1-10
  reasoningScore: number,   // 1-10
  streakMultiplier: number, // 1.0, 1.5, 2.0, or 3.0
  isCreative: boolean,
  sessionType: 'learnback_way' | 'exam_prep'
): number {
  const baseVC = difficulty * reasoningScore;
  // LearnBack Way earns more than exam prep (incentivize real-world learning)
  const typeMultiplier = sessionType === 'learnback_way' ? 1.0 : 0.7;
  const creativityBonus = isCreative ? Math.floor(baseVC * 0.2) : 0;
  
  const totalVC = Math.floor((baseVC * typeMultiplier + creativityBonus) * streakMultiplier);
  return totalVC;
}

// Streak multiplier rules:
// 1-6 days streak: 1.0x
// 7-29 days streak: 1.5x
// 30-89 days streak: 2.0x
// 90+ days streak: 3.0x

Board Exam Question Generation

// lib/ai/generate-exam-question.ts

const EXAM_QUESTION_PROMPT = `You are generating board exam practice questions for Indian students.

BOARD: {board_code}
CLASS: {grade}
SUBJECT: {subject}
CHAPTER: {chapter}
QUESTION TYPE: {question_type} (mcq / short_answer / long_answer / numerical)

RULES:
1. Generate questions that match the EXACT pattern of this board's actual exam papers.
2. For MCQs: 4 options, exactly ONE correct. Distractors must be plausible (common mistakes).
3. For short answers: Specify expected word count and marks.
4. For long answers: Specify expected word count, marks, and sub-parts if applicable.
5. For numericals: Include all necessary data. Solution must show clear steps.
6. Match the difficulty level of actual board exams for this class.
7. Each question must come with a detailed solution and list of common mistakes students make.

OUTPUT FORMAT (respond in JSON only):
{
  "question_text": "The question",
  "question_type": "mcq | short_answer | long_answer | numerical",
  "options": ["A", "B", "C", "D"] or null,
  "correct_answer": "the correct answer",
  "marks": number,
  "expected_word_count": number or null,
  "solution_steps": "Step-by-step solution",
  "common_mistakes": ["mistake 1", "mistake 2"],
  "concepts_tested": ["concept 1", "concept 2"],
  "difficulty": 1-10
}`;

Board Exam Answer Evaluation

// lib/ai/evaluate-exam-answer.ts

const EXAM_EVALUATION_PROMPT = `You are evaluating a student's answer to a board exam practice question.

Evaluate based on:
1. Correctness and completeness
2. For MCQ: simply right or wrong
3. For short/long answers: partial marks based on key points covered
4. For numericals: marks for correct method even if final answer is wrong
5. Provide step-by-step correction showing where they went right/wrong

OUTPUT FORMAT (respond in JSON only):
{
  "is_correct": true/false,
  "marks_obtained": number (can be partial),
  "marks_possible": number,
  "feedback": "Specific feedback on their answer",
  "corrections": "Where they went wrong and the correct approach",
  "concepts_strong": ["concepts they demonstrated well"],
  "concepts_weak": ["concepts they need to review"]
}`;

Monthly Earn-Back Calculation

// lib/payments/earnback.ts

async function calculateMonthlyEarnback(studentId: string, month: Date) {
  const monthStart = startOfMonth(month);
  const monthEnd = endOfMonth(month);
  
  // 1. Sum all VC earned this month
  const { data: vcData } = await supabase
    .from('vidya_coins_ledger')
    .select('amount')
    .eq('student_id', studentId)
    .gte('created_at', monthStart.toISOString())
    .lt('created_at', monthEnd.toISOString())
    .gt('amount', 0);
  
  const totalVC = vcData?.reduce((sum, row) => sum + row.amount, 0) ?? 0;
  
  // 2. Convert to INR
  const VC_TO_INR_RATE = 0.10; // 1 VC = ₹0.10
  const earnbackINR = totalVC * VC_TO_INR_RATE;
  
  // 3. Get subscription amount and cap at max earn-back %
  const { data: sub } = await supabase
    .from('subscriptions')
    .select('amount_inr')
    .eq('student_id', studentId)
    .eq('status', 'active')
    .single();
  
  const feeINR = (sub?.amount_inr ?? 400000) / 100; // paise to rupees
  const maxEarnbackPct = 75;
  const maxEarnback = feeINR * (maxEarnbackPct / 100);
  const finalEarnback = Math.min(earnbackINR, maxEarnback);
  
  // 4. Record payout
  await supabase.from('earnback_payouts').upsert({
    student_id: studentId,
    month: monthStart.toISOString().slice(0, 10),
    total_vc_earned: totalVC,
    vc_to_inr_rate: VC_TO_INR_RATE,
    earnback_amount_inr: finalEarnback,
    fee_paid_inr: feeINR,
    earnback_pct: (finalEarnback / feeINR) * 100,
    max_earnback_pct: maxEarnbackPct,
    status: 'calculated'
  }, { onConflict: 'student_id,month' });
  
  return { totalVC, earnbackINR: finalEarnback, earnbackPct: (finalEarnback / feeINR) * 100 };
}

Parent Weekly Insight Generation

// lib/ai/generate-insight.ts

const INSIGHT_PROMPT = `You are generating a weekly progress insight for a parent about their child's learning on LearnBack.

Write in a warm, encouraging, natural tone — like a caring mentor updating a parent over chai. Use the child's name. Be specific about what they did well and where they can improve. Never be harsh or discouraging.

DATA PROVIDED:
- Child's name, age, grade
- This week's problems attempted and scores
- Domains practiced
- Streak status
- SIP dimension scores and changes
- Board exam prep progress (chapters completed, scores)
- Vidya Coins earned this week vs last week

OUTPUT: 3-4 paragraphs of natural language insight. Include:
1. What the child did well this week (be specific)
2. An area they're growing in (positive framing)
3. A suggestion for the parent (something to encourage at home)
4. Board exam prep progress if applicable
5. Vidya Coins earned and what that means in ₹ terms

Example tone: "Riya had a fantastic week! She tackled 12 problems across Money Sense and Thinking Skills, and her reasoning scores have jumped — she scored 8/10 on a compound interest problem that most students her age find tricky..."`;

SIP (STUDENT INTELLIGENCE PROFILE) — 5 DIMENSIONS

The SIP is a radar chart showing 5 dimensions, each scored 0-100. Updated after every problem.

Dimension 1: Reasoning Pattern (0-100) Sub-scores: top_down_vs_bottom_up, linear_vs_lateral, ambiguity_tolerance Tracked by: How student approaches open-ended problems

Dimension 2: Domain Affinity (0-100) Sub-scores: per-domain engagement levels (thinking_skills, money_sense, communication, science_everyday, builder_challenges, world_society) Tracked by: Which domains they choose, time spent, quality of work

Dimension 3: Learning Velocity (0-100) Sub-scores: per-domain speed of concept grasp Tracked by: How quickly difficulty can increase without quality dropping

Dimension 4: Communication Style (0-100) Sub-scores: writing_clarity, reasoning_articulation, explanation_depth Tracked by: Quality of written reasoning in answers

Dimension 5: Resilience & Growth (0-100) Sub-scores: retry_after_failure, help_seeking, improvement_over_time Tracked by: Behavior after wrong answers — do they retry? Give up? Try differently?

Display as a Recharts RadarChart on the student profile and parent dashboard.


PAYMENT FLOW — RAZORPAY INTEGRATION

Step-by-step implementation:

1. Create subscription endpoint (POST /api/pay/create-subscription):

import Razorpay from 'razorpay';

const razorpay = new Razorpay({
  key_id: process.env.RAZORPAY_KEY_ID!,
  key_secret: process.env.RAZORPAY_KEY_SECRET!,
});

// Create a Razorpay subscription for the parent
const subscription = await razorpay.subscriptions.create({
  plan_id: process.env.RAZORPAY_PLAN_ID!,  // ₹4,000/month plan created in Razorpay dashboard
  total_count: 12,  // 12 months
  quantity: 1,
  customer_notify: 1,
  notes: {
    student_id: studentId,
    parent_id: parentId,
  }
});
// Return subscription.id and subscription.short_url to frontend
// Frontend opens Razorpay checkout modal with this subscription

2. Frontend checkout (subscribe page):

// Load Razorpay checkout script
// Open modal with subscription_id
// On success: redirect to billing page
// On failure: show error

3. Webhook handler (POST /api/pay/webhooks/razorpay):

// Verify webhook signature using RAZORPAY_WEBHOOK_SECRET
// Handle events:
// - subscription.authenticated → update subscription status
// - subscription.activated → mark subscription active, activate student account
// - subscription.charged → create payment record, update current_period dates
// - subscription.cancelled → mark subscription cancelled
// - payment.captured → record successful payment
// - payment.failed → record failed payment, notify parent

4. Phase 1 pricing: Flat ₹4,000/month for all students.

5. Earn-back display: Show on parent dashboard as credit. Applied as discount to next month (or accumulated for quarterly bank transfer in Phase 2).


USER FLOWS — DETAILED SCREEN SPECIFICATIONS

Student Dashboard

  • Top bar: Student name, streak fire icon + count, VC balance with coin animation
  • Two large CTA buttons: "LearnBack Way" (green, primary) and "Board Prep" (blue, secondary)
  • Recommended domains row (based on SIP — suggest weak areas wrapped in engaging framing)
  • Recent badges earned
  • Weekly activity heatmap (like GitHub contributions)
  • Quick stats: Problems solved today / this week, Current streak, VC earned today

Domain Picker (LearnBack Way)

  • 6 domain cards in a grid:
    • 🧠 Thinking Skills — Logic, reasoning, patterns, structured arguments
    • 💰 Money Sense — Savings, spending, investing, business basics
    • 💬 Communication — Writing, speaking, presenting, persuading
    • 🔬 Science of Everyday — Why things work, experiments, observations
    • 🔧 Builder Challenges — Design, build, create, ship
    • 🌍 World & Society — History, geography, civics through real dilemmas
  • Plus a "🎲 Surprise Me" button (AI picks based on SIP weak areas + interests)

Problem View

  • Scenario text (2-4 paragraphs, rendered nicely with good typography)
  • "Your Answer" text area (large, multiline)
  • "Explain Your Thinking" text area (required — this is what earns high VC)
  • Submit button (disabled until both fields have content)
  • "Need a Hint?" collapsible (shows progressive hints from AI)
  • Timer (optional, not penalized — just for self-awareness)

Results View

  • Large correct/incorrect indicator with animation
  • Reasoning score: star display (★★★★☆ = 8/10)
  • VC earned: animated counter with coin particles (+35 VC!)
  • AI feedback: 2-3 sentences in a chat-bubble style
  • If streak milestone hit: streak celebration animation
  • If badge earned: badge unlock animation
  • Two buttons: "Next Problem" and "Take a Break"

Board Prep Home

  • Board selector (auto-filled from student profile, changeable)
  • Class selector
  • Subject tabs (Math, Science, English, Social Science, etc.)
  • Chapter list for selected subject: each chapter shows name, progress bar (% complete), score
  • Two buttons per chapter: "Practice" and "Mock Test" (mock test for full subject only)

Exam Question View

  • Question text with proper formatting (equations, diagrams if needed)
  • For MCQ: 4 radio button options
  • For short/long answer: text area with word count indicator
  • For numerical: number input with "Show Work" text area
  • Timer (set to board's standard time allocation per question)
  • "Hint" button (costs 1 VC for exam prep hints)
  • Submit button

Mock Test View

  • Full simulated board paper
  • Question navigator sidebar (numbered buttons: green=answered, red=flagged, gray=unanswered)
  • Overall timer counting down
  • "Submit All" button with confirmation modal
  • After submission: detailed score breakdown by chapter and question type

Parent Dashboard

  • Child cards (one per linked child):
    • Name, age, grade
    • Streak fire + count
    • VC earned this month
    • Active learning time this week
    • SIP radar chart thumbnail
    • Click → Child Detail page

Child Detail (parent view)

  • Full SIP radar chart (interactive, hover for dimension details)
  • VC balance + ₹ earn-back value (prominently displayed)
  • Domain-wise progress bars
  • Board exam chapter progress (if enrolled)
  • Recent activity feed (last 20 problems with scores)
  • AI-generated weekly insight (see insight generation above)

Earn-Back Tab (parent view)

  • Hero number: "₹X,XXX earned back this month"
  • Total fees paid vs total earned back (pie or bar chart)
  • Month-by-month earn-back trend (Recharts line chart)
  • Earn-back percentage gauge
  • Explanation: "Your child earned X,XXX Vidya Coins this month. At ₹0.10 per coin, that's ₹X,XXX back — Y% of your monthly fee."

Subscribe Page

  • Plan card: ₹4,000/month with earn-back potential highlighted
  • "Your child can earn back up to ₹3,000/month through learning"
  • Razorpay checkout button → opens Razorpay modal (UPI, card, net banking)
  • After payment: success confirmation → redirect to parent dashboard

Admin Dashboard

  • Stat cards: Total students, Active today, Total VC issued, Monthly revenue, AI cost this month, Earn-back liability
  • Charts: Daily active users trend, VC economy health, Revenue vs earn-back
  • Flagged problems needing quality review
  • Recent signups

Admin: Student Management

  • Searchable, filterable table: Name, age, grade, board, streak, VC balance, subscription status, last active
  • Filters: age range, board, subscription status, activity level
  • Click → student detail
  • Bulk actions: export CSV

Admin: AI Quality Review

  • Random sample of recent AI-generated problems + evaluations
  • Each card shows: problem text, student answer, AI evaluation, VC awarded
  • Admin actions: Approve / Flag / Adjust VC

Admin: Billing & Revenue

  • Revenue summary: total active subscriptions, MRR, Razorpay settlement status
  • Overdue payments list
  • "Run Monthly Earn-Back Calculation" button (triggers for all students)
  • Earn-back payouts table: student, month, VC earned, ₹ value, status

6 LEARNING DOMAINS — EXAMPLES FOR AI CONTEXT

When the AI generates problems, it should understand what each domain means:

Thinking Skills: Logic puzzles, pattern recognition, structured arguments, identifying bias, cause-and-effect reasoning, probability thinking. Example for a 10-year-old: "Your neighborhood has 4 sweet shops. All of them close on Tuesdays. Today all 4 are open. What day is it definitely NOT? What days could it be? How do you know for sure?"

Money Sense: Savings, spending, budgeting, investing basics, how businesses work, value of money, compound interest, opportunity cost. Example for a 13-year-old: "Your family spends ₹1,200/month on milk. A neighbor offers to sell you a cow for ₹40,000. The cow gives 5 liters/day and costs ₹200/day to feed. Should your family buy the cow? Show your math for 1 year, 3 years, and 5 years."

Communication: Clear writing, persuasive arguments, explaining complex things simply, active listening, email/letter writing, presentation skills. Example for a 15-year-old: "Your school principal wants to ban mobile phones in school. Write a 200-word argument AGAINST the ban that would convince the principal. Then write a 200-word argument FOR the ban. Which argument is stronger and why?"

Science of Everyday: Physics of daily life, chemistry in cooking, biology of the body, weather, technology behind gadgets. Example for an 8-year-old: "Why does a steel spoon feel colder than a wooden spoon when both are on the same table? They should be the same temperature, right? What's happening?"

Builder Challenges: Design thinking, prototyping, fixing things, systems thinking, creating solutions. Example for a 12-year-old: "Design a system so your apartment building's watchman can track every delivery that arrives. He can't use a computer. Think about: what information needs to be recorded, what materials you'd need, and how the system works when 3 deliveries arrive at the same time."

World & Society: History through decisions, geography through real scenarios, civics through dilemmas, current events analysis. Example for a 16-year-old: "India's Parliament is debating a new law that would make coding a compulsory subject from Class 6. You're a member of the committee. Consider: What about schools without computers? What about students who struggle with languages, not logic? What would you recommend and why?"


DEPLOYMENT CHECKLIST

  1. Supabase: Create project (free tier) → copy URL + anon key + service role key → run migration SQL
  2. Anthropic: Create API key at console.anthropic.com → store in .env
  3. Razorpay: Create account → complete KYC (PAN + Aadhaar + bank, 2-3 days) → get API keys → create ₹4,000/month plan → set up webhook URL pointing to /api/pay/webhooks/razorpay
  4. Google OAuth: Configure in Supabase Auth settings → add redirect URLs
  5. Vercel: Connect GitHub repo → set all environment variables → deploy
  6. Domain: Buy learnback.in (~₹800/year) → point to Vercel
  7. Seed Data: Populate exam_boards table with chapter lists for CBSE (Class 6-12), TS SSC (6-10), TS Inter (11-12), AP SSC (6-10), AP Inter (11-12), ICSE (6-10), ISC (11-12) — approximately 140 chapter lists across ~5 subjects per grade

DESIGN GUIDELINES

  • Primary color: Emerald green (#10B981 / emerald-500) — growth, money, learning
  • Secondary color: Blue (#3B82F6 / blue-500) — for board prep sections
  • Accent: Amber (#F59E0B / amber-500) — for Vidya Coins, streaks, celebrations
  • Background: White and light gray (#F9FAFB)
  • Typography: Clean, readable. System fonts. Large text for problems (16-18px body).
  • Mobile-first: All screens must work on a 360px wide phone screen
  • Animations: Celebrate learning! VC counter should animate on earn. Streak milestones get fire animation. Badge unlocks get a satisfying reveal.
  • Indian context: Use ₹ symbol, Indian number formatting (1,00,000 not 100,000), IST timezone

BRAND ELEMENTS

  • Platform name: LearnBack
  • Logo concept: L-EARN-BACK (the word EARN is visually highlighted within LearnBack)
  • Tagline: "Education that pays you back"
  • Currency: Vidya Coins (VC) — symbol: V or ₹V
  • Learning modes: "LearnBack Way" (real-world problems) and "Board Prep" (exam practice)

COST PROJECTIONS (for validation)

At 30 students:

  • Supabase: ₹0 (free tier)
  • Vercel: ₹0 (free tier)
  • Claude API: ~₹6,750/month (30 students × 10 problems/day × ~₹0.75 per problem)
  • Razorpay: ~₹2,400/month (30 × ₹80 fee per transaction)
  • Domain: ₹67/month (~₹800/year)
  • Total: ~₹9,200/month
  • Revenue: ₹1,20,000/month (30 × ₹4,000)
  • Platform cost is ~8% of revenue — very healthy

KEY IMPLEMENTATION NOTES

  1. Authentication: Use Supabase Auth with email/password and Google OAuth. After signup, immediately create a profiles row. If student role, also create a students row and a streaks row.

  2. Route Protection: Use Next.js middleware to check auth. Redirect unauthenticated users to /login. Check role for route access: /student/* requires role=student, /parent/* requires role=parent, /admin/* requires role=admin.

  3. AI Cost Management: Cache problem generation context. Don't regenerate if student navigates away and comes back. Set a daily problem limit (configurable, start with 20/day). Track AI costs per student in real-time.

  4. Streak Logic: Check in the streaks table. If last_activity_date is yesterday, increment current_streak. If it's today, do nothing (already counted). If it's older than yesterday, reset to 1. Update streak_multiplier based on current_streak value.

  5. Real-time VC Updates: After each problem evaluation, insert into vidya_coins_ledger AND update students.total_vc_earned. Show the VC animation on the results page using the returned vc_earned value.

  6. SIP Updates: After each evaluation, update the relevant sip_scores rows using the AI's sip_updates response. If no row exists for a dimension, create one with a baseline of 50.

  7. Exam Board Seeding: The exam_boards table needs to be pre-populated with accurate chapter lists. For Phase 1, manually enter chapter names for each board × grade × subject combination. The AI doesn't need textbook content — just chapter names and key concepts. Claude's training data contains comprehensive knowledge of Indian board syllabi.

  8. Webhook Security: Always verify Razorpay webhook signatures before processing. Use the RAZORPAY_WEBHOOK_SECRET from your environment.

  9. Error Handling: All AI calls should have try/catch with graceful fallbacks. If Claude API fails, show a friendly "Our learning engine is taking a short break" message, not a crash.

  10. Mobile Responsiveness: Test every screen at 360px width. The problem view and exam question view are the most critical — students will use these on phones. Make text large and readable. Use sticky buttons at the bottom for submit actions.


BUILD ORDER (SUGGESTED)

Build in this order for fastest time to a working demo:

  1. Auth + Profiles — Signup, login, Google OAuth, profile creation, role-based routing
  2. Database Migration — All 16 tables, RLS policies, indexes
  3. Student Dashboard — Layout, navigation, placeholder data
  4. AI Problem Generation — The /api/learn/generate endpoint + problem display
  5. AI Evaluation — The /api/learn/submit endpoint + results display
  6. Vidya Coins — Ledger, balance display, earn animation
  7. Streaks — Daily check-in, multiplier calculation, streak display
  8. SIP — Dimension tracking, radar chart on profile
  9. Parent Dashboard — Child cards, child detail, SIP view, activity feed
  10. Board Exam Prep — Board/chapter selection, question generation, evaluation
  11. Payments — Razorpay integration, subscription creation, webhook handling
  12. Earn-Back — Monthly calculation, parent dashboard display, charts
  13. Admin Panel — Overview stats, student management, AI review, billing
  14. Polish — Animations, mobile testing, error states, loading states

REFERENCE ARCHITECTURE

I have a detailed interactive architecture document (React artifact) that covers all 11 sections visually — use it alongside this prompt for reference on database relationships, API structure, and user flows. The architecture artifact covers: Platform Overview, Tech Stack, Database Schema (with relationship diagrams), AI Engine flow, Board Exam Prep, Payments & Billing, User Flows, API Structure (all 36 endpoints), Screens & Components (all 25 screens), Deployment, and Running Costs.


This is LearnBack Phase 1. Build it solid, build it clean, build it for Indian students who deserve better than memorization. The AI is the engine. The earn-back is the hook. The real-world problems are the soul.