From e32afc9bbc5c7c15cb3520412b8e2afe7ad33223 Mon Sep 17 00:00:00 2001 From: admin Date: Fri, 12 Jun 2026 16:00:04 +0000 Subject: [PATCH] Upload files to "specs" --- specs/01-product-spec.md | 357 +++++++++++++++++++ specs/02-system-architecture.md | 84 +++++ specs/05-classroom-and-institution-spec.md | 63 ++++ specs/06-gamification-and-simulation-spec.md | 50 +++ specs/07-data-and-analytics-spec.md | 64 ++++ 5 files changed, 618 insertions(+) create mode 100644 specs/01-product-spec.md create mode 100644 specs/02-system-architecture.md create mode 100644 specs/05-classroom-and-institution-spec.md create mode 100644 specs/06-gamification-and-simulation-spec.md create mode 100644 specs/07-data-and-analytics-spec.md diff --git a/specs/01-product-spec.md b/specs/01-product-spec.md new file mode 100644 index 0000000..2284358 --- /dev/null +++ b/specs/01-product-spec.md @@ -0,0 +1,357 @@ +# 01 Product Spec — InvestPlay + +## Overview + +InvestPlay is a cross-platform financial literacy and life-skills education product for ages 16–25, designed for individual learners, schools, universities, educational centers, and institutional partners. The platform uses gamification, simulation, guided lessons, challenges, and an educational AI coach to help users build practical money skills, starting from everyday budgeting and savings and progressing toward investing, risk, macroeconomics, and advanced financial decision-making.[file:1][file:2] + +The product is intentionally not a real trading app and not a robo-advisor. It uses only virtual money and simulated decision environments so users can learn safely, make mistakes without financial harm, and understand the consequences of choices before they face them in adult life.[file:2] + +## Product Vision + +The core mission of InvestPlay is to improve financial literacy for young people by turning financial education from passive theory into active experience. The product is built to counter misinformation, hype-driven decision-making, and shallow “easy money” narratives by teaching structured thinking, personal finance habits, and risk awareness through interactive systems.[file:2] + +InvestPlay should become a long-term financial learning platform rather than a single-use stock simulator. Its scope includes money habits, saving, budgeting, banking, rent and living costs, debt, inflation, investing, and more advanced economic concepts for older or more advanced users.[file:2] + +## Product Positioning + +InvestPlay is positioned as a financial life education platform with investing as one advanced pillar, not as the center of the product. The app combines elements already seen across financial literacy games, life simulations, and student finance platforms, where budgeting, money management, stock simulations, and classroom learning are bundled into one learning experience.[web:82][web:83][web:84][web:85][web:86] + +This positioning allows the product to serve both B2C learners and B2B educational buyers. For learners, the value is a safe and engaging way to prepare for adult financial life; for institutions, the value is curriculum delivery, classroom tools, measurable progress, and structured skill development.[file:2][web:83][web:84] + +## Target Users + +### Primary User Segments + +- Students aged 16–18 in high school who need foundational literacy in budgeting, banking, savings, and consumer decision-making.[file:2] +- Students aged 18–25 in universities, colleges, and early adult life who need more advanced content in investing, debt, financial planning, and economic decision-making.[file:2] +- Teachers, lecturers, and trainers who need structured lesson delivery, assignments, classroom analytics, and challenge-based activities.[file:2] +- Institutional buyers such as schools, universities, educational centers, banks, youth organizations, and financial literacy programs seeking a deployable education platform.[file:2] + +### Secondary User Segments + +- Individual self-directed learners using a freemium version.[file:2] +- Research and policy organizations interested in anonymized behavioral insights about youth financial literacy trends. +- Financial institutions that may later use the platform for partnerships, educational sponsorships, or post-graduation lead generation, subject to age, consent, and policy controls. + +## Platforms + +InvestPlay must be delivered as one product across multiple platforms so that it is accessible in schools, on personal devices, and on desktops and laptops used in classrooms. + +Required product channels: + +- Web application for Chrome, Safari, Firefox, and Edge on desktop and laptop. +- Mobile apps for iOS and Android. +- Desktop-distributed builds for Windows, macOS, and Linux for optional institutional deployment and offline-capable classroom use. + +The experience should be consistent across platforms, with responsive design and shared product logic. Platform-specific wrappers are acceptable, but the user should perceive one product ecosystem rather than different apps. + +## Core Product Principles + +### 1. Education first + +The product must always behave as an educational environment, not a recommendation engine. The AI coach, simulations, and all interactive mechanics should help users reason, compare, reflect, and understand trade-offs rather than pushing them toward specific actions or products.[file:2] + +### 2. Safe experimentation + +All user activity in the learning and investing layers is virtual. Simulations exist so users can fail safely, learn from mistakes, and build maturity before using real financial products.[file:2] + +### 3. Life-first, not trading-first + +InvestPlay should teach the full spectrum of financial adulthood: spending, rent, savings, emergency funds, subscriptions, debt, banking, taxes, inflation, and long-term planning before exposing users to advanced trading concepts. This principle is critical to avoid building “just another stock app.”[file:2][web:83][web:85][web:86] + +### 4. Modular and localizable + +The platform must support plug-and-play educational modules, lessons, mini-games, calculators, challenges, and simulations that can be turned on, off, reordered, replaced, or localized without changing application code. Dynamic block-based rendering through React and headless CMS patterns is well aligned with this requirement.[web:87][web:89][web:101] + +### 5. Institutional readiness + +The product must work for classroom and institutional use from the start, including roles, reporting, assignments, analytics, localization, branding controls, and cohort-based challenges.[file:2] + +## Product Scope + +InvestPlay includes four product pillars: + +### Learn + +Structured educational content including lessons, walkthroughs, tutorials, guided reading, concept explainers, glossaries, quizzes, and progression paths from beginner to advanced. + +### Play + +Mini-games, finance scenarios, challenges, blind simulations, timed exercises, score-based interactions, and gamified learning loops that teach through action rather than passive reading.[web:82][web:83][web:84][web:85] + +### Practice + +Virtual portfolios, calculators, budget planners, rent and cost-of-living tools, savings planners, interest comparison tools, risk exercises, and decision labs that help users apply knowledge. + +### Teach + +Teacher dashboards, assignments, classroom cohorts, reporting, progress analytics, leaderboards, curriculum packaging, and institution-specific deployment tools.[file:2][web:83][web:84] + +## Major Feature Domains + +### A. Financial literacy foundation + +This domain covers beginner and early-stage financial skills such as: + +- Needs vs wants. +- Budgeting. +- Cash flow. +- Saving habits. +- Emergency funds. +- Banking basics. +- Interest and APY. +- Subscriptions and recurring costs. +- Everyday spending choices. +- Digital payment awareness. + +### B. Adult life readiness + +This domain extends into practical adulthood topics such as: + +- Rent and housing trade-offs. +- Utilities and monthly bills. +- Debt and credit behavior. +- Salary, taxes, and net income. +- Inflation and purchasing power. +- Insurance basics. +- Cost of living. +- Long-term financial planning. + +### C. Investing and markets + +This domain introduces investment concepts progressively and only after core foundations: + +- Risk and return. +- Diversification. +- Stocks. +- ETFs. +- Bonds. +- ESG concepts. +- ROI basics. +- Time horizon and compounding. +- Portfolio building. +- Market behavior and volatility. +- Advanced exposure for universities: forex, rates, macro effects, additional instruments. + +### D. Decision-making and anti-hype education + +This domain teaches users how to think critically in high-noise environments: + +- Scam awareness. +- Social hype and finfluencer influence. +- FOMO and panic selling. +- Risk management. +- Reading incomplete information. +- Acting under uncertainty. +- Behavioral bias awareness. + +### E. Classroom and institutional education + +This domain supports academic deployment: + +- Classroom creation. +- Cohort enrollment. +- Assignments. +- Module activation by institution. +- Analytics and grading support. +- Classroom leaderboards. +- Session-based challenges. +- Institution-specific branding and localization. + +## Product Roles + +The platform should support the following user roles: + +- Student. +- Teacher / Instructor. +- Institution Admin. +- Platform Admin. +- Content Manager / Curriculum Editor. +- Research / Analytics role for approved aggregated reporting. + +Each role should have different permissions, content access, reporting access, and feature visibility. + +## AI Coach Product Definition + +The AI coach is an educational assistant, not a financial advisor. Its purpose is to explain concepts, ask reflective questions, clarify mistakes, provide contextual hints, summarize lessons, and support learning journeys without making decisions for the user.[file:2] + +The AI coach should: + +- Explain terms in simple or advanced language based on the learner stage. +- Review a user’s simulation or challenge outcome and explain what happened. +- Recommend which educational module to study next, not which asset to buy. +- Support multilingual conversation where possible. +- Be constrained by clear safety and usage policies. + +The AI coach should not: + +- Execute trades. +- Give real financial advice. +- Tell users what to buy or sell in real life. +- Behave like a brokerage assistant. +- Expose institutional buyers to uncontrolled AI costs. + +### AI Cost Policy + +AI is an optional service layer inside the platform and must be tenant-configurable. OpenAI project budgets can be configured and monitored, but reports indicate budget controls may act as alerts rather than absolute hard stops, so InvestPlay must enforce hard limits in its own backend.[web:92][web:93][web:94][web:95] + +Google has also added spend and quota controls for Gemini environments, which makes tenant-level provider selection possible, but backend-side caps are still required for predictable costs.[web:97][web:100] + +Supported AI operating modes: + +- Managed mode: InvestPlay provides AI under product-managed quotas. +- Institution mode: university or institution provides its own AI provider credentials and absorbs costs. +- Disabled mode: AI coach is turned off for that tenant. + +Minimum AI controls: + +- Per-user daily token limits. +- Per-tenant monthly token limits. +- Per-feature token budgets, for example chat vs lesson summary vs simulation review. +- Hard shutdown when quota is exhausted. +- Audit logs for prompt and token usage metadata. + +## Modular Content Strategy + +The educational system must be built as a modular content platform rather than fixed app screens. Lessons should be composed from reusable blocks rendered dynamically by the client, which matches established React + headless CMS block-rendering patterns.[web:87][web:89][web:101] + +A lesson can include reusable block types such as: + +- Intro text. +- Story scenario. +- Video or media. +- Quiz. +- Calculator. +- Reflection prompt. +- Chart analysis. +- Budget game. +- Blind simulation step. +- Teacher note. +- Assignment. +- Summary. + +This model must support: + +- Reordering blocks. +- Hiding or enabling blocks per tenant. +- Locale-specific content versions. +- Age-stage adaptation. +- Institution-specific curriculum packs. +- Reuse of the same block in multiple lessons or tracks. + +## Localization + +Localization is a core product requirement, not a later enhancement. The initial release must support at least English and Greek because that aligns with your current market entry goals.[file:2] + +Localization requirements: + +- All UI text stored as localization strings. +- Long-form educational content localized at CMS level. +- Support for locale-specific examples, currency, tax language, and educational references. +- Tenant default locale setting. +- User-level language preference override. +- Ability to add future EU locales without rewriting lesson logic. + +## Gamification Model + +Gamification is central to product engagement, but it must reinforce learning outcomes rather than addictive loops. The platform concept already includes challenges, achievements, leaderboards, and AI-guided feedback in a virtual-money environment.[file:2] + +Core gamification elements: + +- XP and level progression. +- Badges and achievements. +- Streaks. +- Lesson completion rewards. +- Challenge scoring. +- Classroom and event leaderboards. +- Time-based and scenario-based events. +- Unlockable advanced modules. + +Gamification should reward: + +- Good reasoning. +- Responsible risk management. +- Lesson completion. +- Reflection and learning consistency. +- Diversification and safe habits where applicable. + +Gamification should not reward only: + +- Maximum returns. +- Reckless risk. +- Short-term speculation. + +## Simulations and Challenges + +The product should support multiple challenge types, including blind historical simulations, budgeting games, trade-off scenarios, and life-finance decision labs. Life-simulation and finance game examples in the market show that budgeting and unexpected-life-event simulation formats are especially effective for teaching practical financial behavior.[web:82][web:83][web:85][web:86] + +Simulation types should include: + +- Budget challenge. +- Emergency fund scenario. +- Cost-of-living planner. +- Blind asset scenario. +- Market crash scenario. +- Rent vs transport trade-off. +- Savings habit challenge. +- ESG portfolio challenge. +- Interest and APY comparison game. +- Debt repayment strategy challenge. + +## Data and Analytics Product Requirements + +The platform should capture educational and behavioral data to improve teaching, personalization, and reporting. Data collection should serve product learning outcomes, institutional reporting, and anonymized aggregate research outputs where permitted. + +Data domains include: + +- Lesson completion. +- Quiz performance. +- Time spent. +- Challenge attempts. +- Challenge scores. +- Repeat mistakes. +- Risk warning interactions. +- Leaderboard performance. +- Session attendance. +- AI coach usage. +- Module progression. + +A core product rule is that analytics for external research or commercial insight must be anonymized and aggregated before being shared. + +## Business Model Support + +The product should be designed to support multiple business modes at once: + +- Freemium B2C learning tier for individuals.[file:2] +- B2B SaaS licensing for schools, universities, educational centers, and institutional programs.[file:2] +- White-label deployments for institutional buyers. +- Optional AI usage plans by tenant. +- Premium curriculum packs for advanced topics. +- Future partner pathways for post-18 users, subject to trust, compliance, and product boundaries. + +## Non-Goals + +The product is not intended to be: + +- A real broker. +- A trading signal provider. +- A copy-trading or social trading app. +- A fully autonomous financial assistant. +- A crypto speculation-first platform. +- A narrow portfolio game with no broader life-finance education. + +## Success Criteria + +The production product should be considered successful when it can: + +- Deliver financial education across web and mobile in a unified system. +- Support both self-learners and institutions in the same core platform. +- Localize curriculum and UI cleanly for multiple markets. +- Allow modular lessons and challenge systems to be added or removed without app rewrites. +- Provide measurable classroom and learner outcomes. +- Use AI safely and cost-effectively under configurable tenant controls. +- Position itself clearly as a financial adulthood education platform rather than another trading app. + +## Product Summary + +InvestPlay is a modular, cross-platform financial education ecosystem for young people that combines lessons, mini-games, simulations, classroom tools, and a constrained educational AI coach. It is designed to teach money habits, adult life decisions, and progressively advanced financial concepts through safe virtual practice, with strong support for institutions, localization, and long-term curriculum growth.[file:1][file:2][web:83][web:84] diff --git a/specs/02-system-architecture.md b/specs/02-system-architecture.md new file mode 100644 index 0000000..1221dd6 --- /dev/null +++ b/specs/02-system-architecture.md @@ -0,0 +1,84 @@ +# 02 System Architecture — InvestPlay + +## Overview + +InvestPlay follows a **Microservices-oriented Monorepo** architecture. It relies on a multi-tenant, role-based backend (Node.js/NestJS), an API-first headless CMS for dynamic educational content, and a unified React frontend that compiles to Web, Mobile (Capacitor), and Desktop (Tauri). + +The system is designed for high scalability, B2B white-labeling, strict data isolation between institutions, and robust controls over third-party API costs (like AI). + +## 1. Top-Level Architectural Pattern + +- **Monorepo Management:** Managed via `Turborepo` or `Nx` to share TypeScript interfaces, design tokens, UI components, and localization strings across all apps and services. +- **Infrastructure:** Containerized via **Docker**. Deployable to AWS, GCP, or a dedicated VPS environment (e.g., Contabo) via Docker Compose or Kubernetes. +- **Multi-Tenancy:** Schema-level or Row-Level Security (RLS) multi-tenancy. Every request is scoped to a `tenantId` to ensure institutional data isolation. + +## 2. Frontend Layer (Client Apps) + +The frontend uses a "Write Once, Run Everywhere" strategy to minimize maintenance overhead while maximizing device reach. + +- **Core UI Framework:** **React** (Vite or Next.js) + **TypeScript** + **TailwindCSS**. +- **Web App:** Standard SPA/SSR React application served via browser. +- **Mobile App (iOS/Android):** Wrapped using **Capacitor**. Provides native device capabilities (push notifications, haptics, biometrics) using the web codebase. +- **Desktop App (Windows/macOS/Linux):** Wrapped using **Tauri v2**. Rust-based, highly performant, and memory-efficient alternative to Electron. +- **State Management:** `Zustand` for global state (auth, active tenant) and `React Query` / `Apollo Client` for server state and caching. +- **UI Component Library:** Shared internal package built on `Radix UI` or `shadcn/ui` for accessible, headless components. + +## 3. Backend Layer (Core API) + +The backend handles business logic, real-time simulation streaming, gamification rules, and AI proxying. + +- **Core Framework:** **Node.js with NestJS**. Enforces a strict, modular architecture. +- **API Protocol:** **GraphQL** (Primary data fetching) and **REST** (Webhooks, third-party integrations). +- **Real-Time Protocol:** **WebSockets (Socket.io)** used exclusively for real-time multiplayer classroom simulations, live leaderboards, and AI chat streaming. +- **Background Workers:** **BullMQ** running on Redis for asynchronous tasks (e.g., end-of-day portfolio valuation, weekly email digests, analytics rollup, market tick generation). + +### Key NestJS Modules +- `AuthModule`: Handles JWT generation, SSO mapping, and role guards. +- `TenantModule`: Manages institutional settings, white-label UI configs, and feature flags. +- `CurriculumModule`: Interfaces with the Headless CMS to serve lessons and track student progress. +- `SimulationModule`: The "Time Machine" engine. Broadcasts historical market ticks via WebSockets. +- `PortfolioModule`: Executes virtual trades, calculates ROI, ESG scores, and risk metrics. +- `AICoachModule`: The secure proxy for LLM requests (enforces token limits, prompt injection). + +## 4. Data Layer + +- **Primary Database:** **PostgreSQL** accessed via **Prisma ORM**. Chosen for strict ACID compliance, relational integrity (essential for ledgers and transactions), and native JSON support (for flexible telemetry metadata). +- **In-Memory Store / Cache:** **Redis**. Handles WebSocket state, active user sessions, API rate-limiting token buckets, and fast-read leaderboards (Sorted Sets). +- **Blob Storage:** **S3-compatible storage** (AWS S3, Cloudflare R2, or MinIO). Stores user avatars, generated PDF reports, and downloaded CSV historical market data. + +## 5. Content Layer (Headless CMS) + +Educational content must be separated from application code to allow non-technical curriculum designers to update lessons. + +- **CMS Engine:** **Strapi** or **Payload CMS**. +- **Content Structure:** Lessons are built using a **Dynamic Block Model**. A lesson is a JSON array of components (e.g., `[ { type: 'Hero' }, { type: 'Text' }, { type: 'BudgetGame' }, { type: 'Quiz' } ]`). +- **Localization:** Native i18n support at the CMS level. The frontend requests content using the `Accept-Language` header. + +## 6. AI Integration & Cost Control Architecture + +The AI Coach is a metered, securely proxied service. **Client apps never communicate directly with OpenAI or Google Gemini.** + +- **Proxy Routing:** All chat requests hit the NestJS `AICoachModule`. +- **Context Injection:** The backend intercepts the request, appends the user's current virtual portfolio state, recent mistakes, and the specific lesson context into the hidden System Prompt. +- **Rate Limiting (Token Bucket algorithm via Redis):** + - *User limit:* Max N requests per day. + - *Tenant limit:* Max N tokens per month per school. +- **Billing Strategy:** If a university exceeds its monthly quota, the backend returns a `429 Too Many Requests` or gracefully falls back to static hint systems, unless the institution provides their own API key (Bring-Your-Own-Key mode). + +## 7. Third-Party Integrations + +- **Authentication & SSO:** **Clerk** or **Auth0**. Handles secure JWTs and provides out-of-the-box B2B SAML SSO (so universities can log in with their `.edu` Microsoft/Google accounts). +- **Transactional Emails:** **Resend** using `React Email` for templating (Welcome emails, teacher invites, weekly progress reports). +- **B2B Billing:** **Stripe Connect**. Manages institutional SaaS subscriptions (e.g., charging a school based on active student seats). +- **Push Notifications:** **Firebase Cloud Messaging (FCM)** for iOS/Android alerts. +- **Historical Market Data:** **Yahoo Finance (CSV exports)** or **Alpha Vantage (EOD APIs)** used asynchronously by background workers to seed "Blind Simulation" scenarios. + +## 8. Security & Compliance + +- **No Real Money Connectivity:** The system explicitly lacks Plaid, Stripe (for B2C), or real brokerage API integrations for students. `Decimal` types in PostgreSQL represent isolated virtual currency. +- **GDPR Compliance:** + - Soft-delete functionality for all user data. + - Telemetry and analytics data routed to institutional dashboards is aggregated. + - Anonymization pipelines strip PII (Personal Identifiable Information) before data is exported for research purposes. + - AI Prompt sanitization ensures no PII is sent to external LLM providers. +- **API Security:** CORS whitelisting, helmet (HTTP headers), JWT payload verification, and GraphQL query depth limiting to prevent Denial of Service (DoS) attacks. diff --git a/specs/05-classroom-and-institution-spec.md b/specs/05-classroom-and-institution-spec.md new file mode 100644 index 0000000..a64a17e --- /dev/null +++ b/specs/05-classroom-and-institution-spec.md @@ -0,0 +1,63 @@ +# 05 Classroom & Institution Spec — InvestPlay + +## Overview + +While individual users can use InvestPlay independently, the core B2B value proposition lies in the **Institution Layer**. This module transforms the app from a single-player game into a managed academic tool. It provides schools, universities, and banks with the tools to manage student cohorts, assign curriculum, run live simulations, and extract measurable learning outcomes. + +## 1. Institutional Hierarchy + +The system organizes users into a strict hierarchy to ensure data privacy and clear management structures. + +1. **Tenant (The Institution):** E.g., "University of Athens" or "National Bank of Greece". +2. **Tenant Admin:** An IT or department head who manages the subscription, white-label settings, AI billing mode, and invites Teachers. +3. **Teacher / Instructor:** An educator who creates Classrooms, invites Students, assigns lessons, and runs live simulations. +4. **Classroom (Cohort):** A specific group of students (e.g., "Macroeconomics 101 - Fall 2026"). +5. **Student:** The end-user completing modules and participating in simulations. + +## 2. The Teacher Dashboard + +The Teacher Dashboard is a dedicated web interface (not available on mobile) optimized for desktop and projector screens. + +### Core Capabilities +- **Classroom Management:** Create cohorts and generate unique, expiring Invite Codes or magic links for students to join. +- **Curriculum Assignment:** Browse the Headless CMS content library and assign specific Modules or Lessons to a Classroom with due dates. +- **Progress Tracking:** A visual heatmap showing which students have completed assignments, failed quizzes, or are falling behind. +- **Intervention Alerts:** Automated flags generated by the telemetry system (e.g., *"Warning: 40% of the class failed the Compound Interest quiz"* or *"Student A has ignored 3 consecutive risk warnings in the simulator"*). + +## 3. Live Classroom Simulations + +This is the flagship multiplayer feature of InvestPlay, designed to be played live during a class or lecture. + +### The "Time Machine" Event +Teachers can launch a synchronized historical simulation for the entire classroom. +1. **Selection:** The teacher selects a "Blind Scenario" (e.g., The 2008 Financial Crisis). +2. **Waiting Room:** Students join the "Lobby" via the mobile app. +3. **Execution:** The teacher clicks "Start". The NestJS backend begins streaming market ticks via WebSockets to all connected student apps simultaneously. +4. **Live Leaderboard:** The teacher's dashboard displays a real-time, anonymized leaderboard showing the cohort's aggregate performance and risk metrics as the simulation progresses. +5. **The Reveal:** At the end of the simulation, the teacher triggers the "Big Reveal," showing the real historical asset and facilitating a class discussion based on the data. + +## 4. Leaderboards & Gamification (B2B Context) + +Leaderboards in an educational setting must be handled carefully to avoid discouraging underperforming students or incentivizing reckless gambling. + +### Classroom Leaderboards +- **Opt-in / Anonymized:** Teachers can choose to show real names or anonymized avatars on the leaderboard. +- **Multi-Metric Ranking:** Students are ranked not just by "Highest ROI" (which encourages gambling), but by a **Composite Score** that factors in: + - Return on Investment (ROI). + - Risk Management (e.g., maintaining diversification). + - ESG Alignment (if applicable to the lesson). + - Quiz Scores and Lesson Completion. + +## 5. Institutional Reporting & Export + +Schools require proof of learning outcomes to justify software budgets. + +### Automated Reports +- **End-of-Session Reports:** After a live simulation, the system generates a PDF/CSV report detailing the cohort's average return, common mistakes made, and quiz pass rates. +- **Student Report Cards:** Individual, printable summaries of a student's progress through the curriculum, suitable for academic grading. +- **Tenant-Level Analytics (Admin):** Monthly summaries for the Tenant Admin showing total active users, AI token consumption, and aggregate platform engagement. + +### Data Privacy & Export (GDPR) +- Teachers only have access to data for students explicitly enrolled in their Classrooms. +- Students have the right to request a complete export of their data or request account deletion, compliant with EU regulations. +- Upon graduation or leaving the institution, a student can decouple their account from the Tenant, converting it into a standard B2C personal account while retaining their XP and Badges. diff --git a/specs/06-gamification-and-simulation-spec.md b/specs/06-gamification-and-simulation-spec.md new file mode 100644 index 0000000..1f0ad9f --- /dev/null +++ b/specs/06-gamification-and-simulation-spec.md @@ -0,0 +1,50 @@ +# 06 Gamification & Simulation Spec — InvestPlay + +## Overview + +Gamification in InvestPlay is designed to build healthy financial habits, not to simulate the dopamine loops of retail day-trading apps. The gamification mechanics and simulation engines reward consistency, risk management, critical thinking, and curriculum completion. + +This document details the core gamification loops, the types of interactive mini-games, and the mechanics of the "Blind Scenario" simulation engine designed to eliminate hindsight bias. + +## 1. Core Gamification Mechanics + +### XP and Leveling +- **Earning XP:** Students earn Experience Points (XP) for completing lessons, passing quizzes, maintaining daily login streaks, and completing interactive challenges. +- **Leveling Up:** Accumulating XP increases the user's overall Level. In B2C (self-guided) mode, reaching specific levels unlocks advanced modules (e.g., Level 10 unlocks "Macroeconomics"). +- **Consistency Over Spikes:** XP payouts heavily favor consistency. Logging in and completing one 5-minute lesson a day for 5 days yields more XP than completing five lessons in a single 25-minute binge. + +### Badges & Achievements +Badges are permanent profile unlocks that celebrate specific educational milestones or behavioral victories during simulations. +- *The Diversifier:* Maintained a portfolio with at least 3 different asset classes for a full simulation. +- *Crash Survivor:* Held through a 20% market drop without panic-selling in a blind scenario. +- *Debt Destroyer:* Successfully paid off the simulated credit card debt in the "Debt Snowball" mini-game. +- *The Skeptic:* Successfully identified and ignored a "Hype Trap" (scam event) during a simulation. + +## 2. Interactive Challenges & Mini-Games + +Instead of relying solely on standard quizzes, lessons incorporate interactive, React/Phaser.js-based mini-games. + +- **The 50/30/20 Salary Drop:** A drag-and-drop budgeting game where users must allocate a virtual €1,500 monthly paycheck into "Needs," "Wants," and "Savings" envelopes while unexpected life events (e.g., "Car breakdown: €200") disrupt their plans. +- **The Debt Snowball:** Users are given a simulated €5,000 credit card balance. They must allocate their monthly budget to pay it off, experiencing firsthand how minimum payments extend the debt lifespan vs. aggressive repayment. +- **The Hype Trap (Anti-Finfluencer):** A narrative-driven challenge where simulated "social media feeds" urge the user to buy a trending asset. The user must analyze the underlying metrics and choose whether to buy the hype or ignore it. + +## 3. The "Blind Scenario" Simulation Engine + +To solve the "Hindsight Bias" problem inherent in stock market games (where students know Apple will succeed and Enron will fail), InvestPlay uses **Blind Scenarios**. + +### The Mechanic +1. **The Context Drop:** The simulation starts by giving macroeconomic context without revealing the year or the asset. (e.g., *"A global supply chain crisis is occurring. Inflation is rising. You are analyzing a manufacturing company..."*) +2. **The Fast-Forward Play:** Using historical CSV data (e.g., Yahoo Finance OHLCV), the NestJS backend streams market ticks (1 tick = 1 week of real time). The frontend chart draws dynamically. The asset is labeled only as `COMPANY-X`. +3. **Injected News:** The backend injects anonymized news headlines at specific ticks to simulate the real-world information environment. +4. **The Reveal:** Once the simulation ends, the UI overlays the real-world dates, the actual company logo, and the true timeline. The AI Coach provides a summary of why the asset behaved the way it did. + +### Procedural / Synthetic Markets (Infinite Replayability) +In addition to historical data, the engine supports **Synthetic Data**. An algorithm generates fake OHLC chart data based on defined volatility and trend parameters. Because the asset never existed, it is mathematically impossible for students to cheat, making it perfect for high-stakes classroom assignments. + +## 4. Anti-Cheat Mechanisms + +For classroom environments, integrity is critical. + +- **Data Obfuscation:** During a Blind Scenario, the real ticker symbol and actual date timestamps are stripped from the WebSocket payload before being sent to the client. They are stored only in Redis on the backend until the session is explicitly marked as `ENDED`. +- **No API Peeking:** Because historical data is served from the InvestPlay backend (not fetched client-side from third-party APIs), tech-savvy students cannot inspect network requests to discover the asset. +- **Time-Bounded Actions:** During live classroom simulations, students have strict time windows (e.g., 30 seconds per tick) to execute trades. The backend rejects any orders stamped outside this window, preventing users from waiting to see what happens before acting. diff --git a/specs/07-data-and-analytics-spec.md b/specs/07-data-and-analytics-spec.md new file mode 100644 index 0000000..4375612 --- /dev/null +++ b/specs/07-data-and-analytics-spec.md @@ -0,0 +1,64 @@ +# 07 Data & Analytics Spec — InvestPlay + +## Overview + +InvestPlay is fundamentally a data-driven education platform. The analytics engine serves three distinct purposes: +1. **For the Student:** To provide personal insights and track progress. +2. **For the Teacher/Institution:** To prove learning outcomes and identify struggling students. +3. **For the Platform (B2B):** To aggregate anonymized behavioral data into macro-level insights (e.g., "The Gen Z Risk Tolerance Report") for research and institutional partners. + +This document defines the telemetry architecture, the reporting outputs, and the strict privacy boundaries required for EU/GDPR compliance. + +## 1. Behavioral Telemetry (Event Tracking) + +The system does not just track *if* a student completed a lesson; it tracks *how* they behave inside simulations. Every major interaction fires an event to the `AnalyticsModule` (stored in PostgreSQL as JSON metadata). + +### Key Tracked Events +- `LESSON_STARTED` / `LESSON_COMPLETED` +- `QUIZ_ATTEMPTED` (Includes score and specific answers chosen) +- `SIMULATION_JOINED` +- `TRADE_EXECUTED` (Includes asset, allocation %, and portfolio context at the time of trade) +- `RISK_WARNING_SHOWN` (e.g., UI warned student about lack of diversification) +- `RISK_WARNING_IGNORED` (Student proceeded with the trade anyway) +- `PANIC_SELL_DETECTED` (Student sold an asset immediately after a sharp drop in a blind scenario) +- `HYPE_TRAP_TRIGGERED` (Student bought an asset during a simulated finfluencer scam event) +- `AI_COACH_CONSULTED` (Counts when and why the student asked for help) + +## 2. Institutional Reporting (The B2B Value) + +Teachers and Tenant Admins require automated, readable proof of efficacy. + +### The Teacher Dashboard Analytics +- **The Cohort Heatmap:** A visual matrix showing the entire classroom. Green = passed module, Yellow = in progress, Red = failed quiz/struggling. +- **Intervention Feed:** An automated list of suggested actions for the teacher. (e.g., *"3 students failed the 'Compound Interest' quiz. Consider reviewing this topic next class."*) + +### Automated Report Generation (PDF/CSV) +The `AnalyticsModule` runs background jobs to compile session data into downloadable artifacts. +- **Post-Simulation Report:** After a live "Blind Scenario," the teacher can download a summary showing: + - Average class ROI. + - The most commonly held asset. + - The % of the class that diversified vs. went "all-in." + - The % of the class that panic-sold during the injected market crash. + +## 3. Macro Insights (The B2B Data Monetization Strategy) + +As the user base grows, the aggregated behavioral data of 16-25 year olds becomes highly valuable to universities, financial research centers, and policy makers. + +### The "Gen Z Financial Behavior Index" +InvestPlay can generate quarterly, macro-level reports answering questions like: +- *Do 18-year-olds prioritize ESG (Environmental, Social, Governance) metrics over pure ROI?* +- *How resilient is Gen Z to simulated market crashes compared to historical averages?* +- *What is the baseline budgeting knowledge of high school students before taking the curriculum?* + +### GDPR & Privacy Enforcement (Strict Rules) +To monetize insights legally and ethically in the EU, strict boundaries must exist. +1. **Total Anonymization:** Data exported for macro reports is stripped of all `userId`, `email`, `name`, and precise location data. +2. **Aggregation Only:** Reports only deal in cohorts of 50+ users. It must be impossible to trace a data point back to a single individual or a specific school. +3. **Opt-Out:** B2C users have a clear toggle to opt-out of research aggregation. +4. **B2B Tenant Controls:** Universities can explicitly stipulate in their SaaS contract that their students' data cannot be included in global aggregated research pools. The platform enforces this via the `Tenant.excludeFromResearch` flag. + +## 4. Technical Implementation + +- **Storage:** Telemetry events are stored in PostgreSQL using the `JSONB` column type for flexible querying. +- **Processing:** Raw events are processed nightly by a `BullMQ` worker that rolls them up into daily/weekly aggregated materialized views to ensure the dashboards load instantly. +- **Data Retention:** Raw user telemetry is soft-deleted or anonymized after 24 months, or immediately upon user account deletion, to comply with GDPR "Right to be Forgotten" mandates.