Based on the analysis of existing business simulation applications, the following key features have been identified as most valuable to incorporate into our web app:
- Cross-functional decision making - Allow users to make decisions across different business functions (marketing, finance, operations, HR)
- Integrated business ecosystem - Create a cohesive environment where decisions in one area affect others
- Comprehensive performance metrics - Track and visualize performance across all business functions
- Competitive market environment - Simulate realistic market responses to user decisions
- Industry-specific contexts - Provide tailored simulations for different industries
- Dynamic market conditions - Include changing market trends, economic factors, and unexpected events
- Resource allocation challenges - Force users to make trade-offs with limited resources
- Long-term vs. short-term decisions - Balance immediate needs with strategic goals
- Risk management scenarios - Include elements of uncertainty and risk assessment
- Budget allocation - Manage financial resources across different departments
- Investment decisions - Make R&D, marketing, and infrastructure investment choices
- Financial reporting - Generate detailed financial statements reflecting business performance
- ROI analysis - Calculate and display return on various investments
- Product development - Design and improve products based on market research
- Pricing strategy - Set and adjust pricing based on market conditions
- Promotion campaigns - Design and implement marketing campaigns with measurable results
- Distribution channels - Select and optimize sales and distribution channels
- Production management - Optimize production processes and capacity
- Inventory management - Balance inventory levels to meet demand while minimizing costs
- Supply chain optimization - Manage suppliers, logistics, and distribution networks
- Quality management - Make decisions affecting product quality and customer satisfaction
- Talent acquisition - Hire employees with different skills and attributes
- Team development - Train and develop employee skills
- Organizational structure - Design company structure and allocate human resources
- Employee satisfaction - Manage factors affecting employee morale and productivity
- Performance analytics - Detailed analysis of decision outcomes
- Benchmarking - Compare performance against competitors or best practices
- Guided learning - Progressive difficulty with instructional elements
- Scenario replays - Ability to review past decisions and their impacts
- Intuitive interface - Clean, modern UI that makes complex decisions accessible
- Data visualization - Clear charts and graphs to represent business performance
- Scenario customization - Ability to adjust simulation parameters and difficulty
- Mobile responsiveness - Access and play simulations on different devices
- Team collaboration - Allow multiple users to manage a business together
- Competitive rankings - Compare performance against other players
- Peer learning - Share strategies and learn from other players
- Discussion forums - Community space to discuss business strategies
—————
This document outlines the technical and functional requirements for developing a comprehensive business simulation web application based on the analysis of existing solutions.
-
Business Logic Processing
- Ability to process complex business rules and calculations
- Support for multiple simulation scenarios and industries
- Realistic cause-and-effect relationships between decisions and outcomes
-
Time Progression
- Simulated time periods (quarters, years) with decision cycles
- Historical data tracking across time periods
- Ability to save and resume simulations
-
Randomization and Variability
- Controlled randomness to create realistic market conditions
- Variable difficulty levels and challenge scenarios
- Unexpected events and market disruptions
-
Decision Interface
- Structured input forms for business decisions
- Decision validation and constraint enforcement
- Decision history and tracking
-
Decision Categories
- Strategic decisions (long-term impact)
- Tactical decisions (medium-term impact)
- Operational decisions (immediate impact)
-
Business Data Model
- Comprehensive data schema for business entities
- Relationships between business components
- Historical data storage and retrieval
-
Performance Metrics
- Financial metrics (profit, revenue, costs)
- Operational metrics (efficiency, quality, capacity)
- Market metrics (market share, customer satisfaction)
- HR metrics (employee satisfaction, productivity)
-
User Profiles
- User registration and authentication
- Progress tracking and achievements
- Personal performance history
-
Role-based Access
- Individual player mode
- Team collaboration mode
- Instructor/administrator mode (for educational context)
-
Tutorial System
- Interactive onboarding experience
- Contextual help and guidance
- Concept explanations and business theory
-
Feedback Mechanisms
- Performance analysis after each decision cycle
- Comparative benchmarking
- Improvement suggestions
-
Competitive Environment
- Leaderboards and rankings
- Performance comparisons
- Tournament capabilities
-
Collaborative Features
- Team-based decision making
- Role assignment within teams
- Communication tools for team members
-
Frontend
- Modern JavaScript framework (Next.js)
- Responsive design for desktop and mobile devices
- Interactive data visualizations
-
Backend
- RESTful API design
- Secure authentication and authorization
- Efficient data processing for simulation calculations
-
Database
- Structured data storage for simulation state
- Efficient querying for performance metrics
- Data integrity and transaction support
-
Responsiveness
- Fast loading times for simulation interface
- Real-time updates for collaborative features
- Efficient handling of complex calculations
-
Scalability
- Support for concurrent users and simulations
- Horizontal scaling capabilities
- Resource optimization for computation-heavy processes
-
Data Protection
- Secure user authentication
- Data encryption for sensitive information
- Protection against common web vulnerabilities
-
Access Control
- Role-based permissions
- Secure API endpoints
- Prevention of unauthorized simulation access
-
API Capabilities
- External data import/export
- Integration with learning management systems (for educational use)
- Extensibility for future features
-
Analytics Integration
- Performance tracking and analytics
- Learning progress measurement
- Usage statistics for platform improvement
-
Hosting Requirements
- Cloud-based deployment
- Automated scaling based on demand
- Regular backup and recovery procedures
-
Maintenance
- Monitoring and logging
- Update and patch management
- Performance optimization
- Intuitive user interface requiring minimal training
- Clear visualization of complex business data
- Consistent design language across all features
- Accessibility compliance for diverse users
- System availability of 99.9% during active hours
- Data persistence and recovery mechanisms
- Graceful handling of unexpected errors
- Modular design allowing for new simulation scenarios
- Ability to add new industries and business contexts
- Customizable metrics and performance indicators
- Comprehensive user documentation and help resources
- Technical documentation for maintenance and extensions
- API documentation for potential integrations
————-
This document provides a detailed analysis of various business simulation applications to identify their key features, strengths, and unique selling points.
Focus Areas: Strategy, Marketing, Entrepreneurship Target Audience: Education and Corporate Training
Key Features:
- Range of simulation games covering different business aspects
- Scenario-based learning environments
- Decision-making frameworks for strategic planning
- Performance analytics and feedback mechanisms
- Competitive team-based simulations
Strengths:
- Comprehensive coverage of business domains
- Educational focus with structured learning outcomes
- Adaptable for different skill levels and educational contexts
Focus Areas: Project Management Target Audience: Project Management Professionals, Students
Key Features:
- Realistic project management scenarios
- Time-constrained decision making
- Resource allocation challenges
- Risk management simulations
- Team collaboration tools
Strengths:
- Specialized focus on project management skills
- Practical application of PM methodologies
- Real-time decision consequences
- Emphasis on time management and prioritization
Focus Areas: Marketing, Finance, Entrepreneurship Target Audience: Academic and Corporate Training
Key Features:
- Industry-specific simulation environments
- Cross-functional business decision making
- Market analysis tools
- Competitive market dynamics
- Financial performance tracking
Strengths:
- Variety of industry contexts
- Integration of multiple business functions
- Realistic market response mechanisms
- Adaptable difficulty levels
Focus Areas: Business Strategy, Digital Camera Industry Target Audience: Business Students, Corporate Trainees
Key Features:
- Industry-specific simulation (digital cameras)
- Comprehensive business decision making
- R&D investment options
- Production and supply chain management
- Financial reporting and analysis
- Competitive ranking system
Strengths:
- Deep industry focus creates realistic context
- Integrated decision-making across business functions
- Competitive benchmarking against peers
- Detailed performance metrics
Focus Areas: Strategy, Finance, Operations Target Audience: Higher Education, Corporate Training
Key Features:
- Business assessment tools
- Strategic planning frameworks
- Financial decision making
- Operational efficiency simulations
- Performance analytics dashboard
Strengths:
- Strong assessment component for skills evaluation
- Balanced coverage of strategic and operational decisions
- Detailed feedback mechanisms
- Progressive difficulty levels
Focus Areas: Business Process Management (BPM) Target Audience: Process Managers, BPM Professionals
Key Features:
- Process optimization simulations
- Workflow management challenges
- Efficiency improvement scenarios
- System integration simulations
- Change management components
Strengths:
- Specialized focus on business processes
- Visual representation of process flows
- Immediate feedback on process changes
- Enterprise-level perspective
Focus Areas: General Business Management Target Audience: Entrepreneurs, Business Students
Key Features:
- Virtual company management
- Multiplayer competitive environment
- Cross-functional decision making
- Market dynamics simulation
- Long-term business development
Strengths:
- Open-ended gameplay with multiple success paths
- Social and competitive elements
- Comprehensive business ecosystem
- Ongoing development challenges
Focus Areas: Athletic Footwear Industry Target Audience: Business Students, Corporate Trainees
Key Features:
- Industry-specific context (athletic footwear)
- Global market considerations
- Production decisions
- Marketing strategy development
- Financial management tools
- Competitive performance rankings
Strengths:
- Realistic industry context
- Global business perspective
- Integrated decision-making across functions
- Competitive benchmarking
Focus Areas: Digital Marketing Target Audience: Marketing Students, Digital Marketers
Key Features:
- SEO strategy simulation
- SEM campaign management
- Social media marketing tactics
- Content marketing planning
- Digital marketing analytics
- Budget allocation challenges
Strengths:
- Specialized focus on digital marketing channels
- Practical application of modern marketing techniques
- Data-driven decision making
- Measurable campaign outcomes
Focus Areas: Entrepreneurship, Marketing, Supply Chain Target Audience: Business Students, Corporate Trainees
Key Features:
- Enterprise resource planning simulation
- Supply chain optimization
- Inventory management challenges
- Customer relationship management
- Financial decision making
Strengths:
- Integrated business functions
- Practical ERP concepts application
- Real-time decision consequences
- Team-based collaborative learning
Focus Areas: Accounting, Finance, Marketing Target Audience: Higher Education
Key Features:
- Specialized simulations for specific business functions
- Practical application of theoretical concepts
- Progressive learning modules
- Performance assessment tools
- Educational outcome tracking
Strengths:
- Strong academic alignment
- Function-specific skill development
- Structured learning progression
- Clear educational objectives
Focus Areas: General Business Management Target Audience: Business Students, Entrepreneurs
Key Features:
- Virtual business environment
- Market competition simulation
- Multi-functional business management
- Resource allocation challenges
- Business growth scenarios
Strengths:
- Comprehensive business ecosystem
- Competitive multiplayer elements
- Flexible learning pathways
- Practical application of business theory
Focus Areas: Corporate and Executive Training Target Audience: Business Executives, MBA Students
Key Features:
- High-quality simulations developed with top business schools
- Executive decision-making scenarios
- Strategic thinking challenges
- Leadership development components
- Complex business environment simulation
Strengths:
- Academic rigor from top business school partnerships
- Executive-level decision complexity
- Sophisticated modeling of business environments
- High-quality learning design ———
This document provides comprehensive guidelines for implementing the business simulation web application based on the prototype and design documents. These guidelines will help developers understand the architecture, components, and implementation steps required to build a fully functional business simulation application.
- Project Overview
- Technology Stack
- Project Structure
- Simulation Engine Implementation
- Frontend Implementation
- Database Schema
- API Endpoints
- Authentication and User Management
- Deployment Guidelines
- Testing Strategy
- Performance Considerations
- Future Enhancements
The Business Simulation Web App is designed to provide a comprehensive business simulation experience similar to industry-leading applications like Cesim, Capsim, and Marketplace Simulations. The application allows users to:
- Manage virtual companies in a competitive market environment
- Make strategic decisions across multiple business functions
- Analyze market conditions and competitor actions
- Track performance through detailed metrics and visualizations
- Learn business concepts through practical application
The application consists of two main components:
- A robust simulation engine that models business dynamics
- An intuitive user interface for decision-making and analysis
- Framework: Next.js with API routes
- Runtime: Node.js
- Database: Cloudflare D1 (SQLite-compatible)
- ORM: Prisma (optional)
- Authentication: NextAuth.js
- Framework: React with Next.js
- Styling: Tailwind CSS
- Component Library: shadcn/ui
- State Management: React Context API and/or Redux
- Data Visualization: Recharts
- Icons: Lucide icons
- Package Manager: pnpm
- Version Control: Git
- Linting: ESLint
- Formatting: Prettier
- Testing: Jest, React Testing Library
The project follows the Next.js application structure with additional organization for simulation engine components:
business_simulation_app/
├── migrations/ # Database migration files
├── public/ # Static assets
├── src/
│ ├── app/ # Next.js app router pages
│ │ ├── api/ # API routes
│ │ ├── auth/ # Authentication pages
│ │ ├── dashboard/ # Dashboard pages
│ │ ├── market/ # Market analysis pages
│ │ ├── products/ # Product management pages
│ │ └── ...
│ ├── components/ # Reusable UI components
│ │ ├── ui/ # Base UI components
│ │ ├── dashboard/ # Dashboard-specific components
│ │ ├── market/ # Market analysis components
│ │ ├── products/ # Product management components
│ │ └── ...
│ ├── hooks/ # Custom React hooks
│ ├── lib/ # Utility functions
│ │ ├── simulation/ # Simulation engine
│ │ │ ├── core.js # Core simulation logic
│ │ │ ├── market.js # Market dynamics
│ │ │ ├── decisions.js # Decision processing
│ │ │ └── ...
│ │ ├── db.js # Database client
│ │ └── ...
│ ├── styles/ # Global styles
│ └── types/ # TypeScript type definitions
├── .env # Environment variables
├── .gitignore # Git ignore file
├── package.json # Package configuration
├── wrangler.toml # Cloudflare configuration
└── README.md # Project documentation
The simulation engine is the core of the application, responsible for modeling business dynamics, processing decisions, and calculating outcomes. The engine is implemented as a set of JavaScript/TypeScript modules in the src/lib/simulation
directory.
- SimulationEngine: The main class that orchestrates the simulation process.
- Company: Represents a company in the simulation with properties and methods.
- Market: Models market dynamics, consumer behavior, and competitive forces.
- DecisionProcessor: Processes user decisions and applies them to the simulation.
- PerformanceCalculator: Calculates performance metrics based on decisions and market conditions.
- EventGenerator: Generates random events that affect the simulation.
- Convert Python Prototype to JavaScript/TypeScript:
- Start by converting the Python prototype files to JavaScript/TypeScript.
- Ensure type safety by adding TypeScript interfaces and types.
- Example conversion of the
SimulationEngine
class:
// src/lib/simulation/core.ts
import { Market } from './market';
import { DecisionProcessor } from './decisions';
import { PerformanceCalculator } from './performance';
import { EventGenerator } from './events';
import type { Company, Decision, SimulationConfig } from '../types';
export class SimulationEngine {
private companies: Company[];
private market: Market;
private decisionProcessor: DecisionProcessor;
private performanceCalculator: PerformanceCalculator;
private eventGenerator: EventGenerator;
private currentPeriod: number;
private config: SimulationConfig;
constructor(config: SimulationConfig) {
this.config = config;
this.companies = [];
this.market = new Market(config.marketConfig);
this.decisionProcessor = new DecisionProcessor();
this.performanceCalculator = new PerformanceCalculator();
this.eventGenerator = new EventGenerator(config.eventConfig);
this.currentPeriod = 0;
}
public initialize(): void {
// Initialize simulation state
this.currentPeriod = 0;
// Create initial market conditions
const initialMarketConditions = this.market.generateMarketConditions(0);
// Store initial state in database
// ...
}
public addCompany(company: Company): void {
this.companies.push(company);
}
public async processPeriod(decisions: Record<string, Decision[]>): Promise<void> {
// Process decisions for all companies
const processedDecisions = this.decisionProcessor.processDecisions(decisions, this.companies);
// Generate market conditions for the period
const marketConditions = this.market.generateMarketConditions(this.currentPeriod);
// Generate random events
const events = this.eventGenerator.generateEvents(this.currentPeriod, this.companies);
// Apply events to companies
this.applyEvents(events);
// Calculate performance metrics
const performanceResults = this.performanceCalculator.calculatePerformance(
this.companies,
processedDecisions,
marketConditions
);
// Update company states
this.updateCompanyStates(performanceResults);
// Increment period
this.currentPeriod++;
// Store results in database
// ...
}
private applyEvents(events: any[]): void {
// Apply events to companies
// ...
}
private updateCompanyStates(performanceResults: any): void {
// Update company states based on performance results
// ...
}
public getCurrentPeriod(): number {
return this.currentPeriod;
}
public getCompanies(): Company[] {
return [...this.companies];
}
public getMarketConditions(): any {
return this.market.getCurrentConditions();
}
}
-
Implement Market Dynamics:
- Convert the
MarketSimulator
,MarketTrends
,ConsumerBehavior
, andCompetitiveDynamics
classes. - Ensure proper integration with the core simulation engine.
- Convert the
-
Implement Decision Processing:
- Convert the decision types and schemas to TypeScript interfaces.
- Implement the decision processing logic to handle different types of decisions.
-
Implement Performance Calculation:
- Develop algorithms to calculate financial and operational performance metrics.
- Ensure proper integration with the market and company models.
-
Implement Event Generation:
- Create a system for generating random events that affect the simulation.
- Define event types, probabilities, and impact calculations.
-
Create Database Integration:
- Implement functions to store and retrieve simulation state from the database.
- Ensure proper transaction handling for consistency.
-
Develop API Layer:
- Create API endpoints to interact with the simulation engine.
- Implement proper error handling and validation.
The frontend provides the user interface for interacting with the simulation. It consists of multiple pages and components organized by functionality.
- Dashboard: Provides an overview of company performance and key metrics.
- Market Analysis: Displays market conditions, trends, and competitor analysis.
- Product Management: Allows users to manage products and view product performance.
- Decision Making: Interfaces for making various business decisions.
- Reports: Detailed reports and visualizations of performance data.
- Set Up Next.js Project:
- Create a new Next.js project using the provided command.
- Configure Tailwind CSS and other dependencies.
create_nextjs_app business_simulation_app
cd business_simulation_app
- Implement Base UI Components:
- Create reusable UI components based on the mockups.
- Use shadcn/ui for consistent styling and behavior.
Example of a reusable card component:
// src/components/ui/card.tsx
import React from 'react';
interface CardProps {
title?: string;
children: React.ReactNode;
actions?: React.ReactNode;
className?: string;
}
export function Card({ title, children, actions, className = '' }: CardProps) {
return (
<div className={`bg-white rounded-lg shadow-sm overflow-hidden ${className}`}>
{(title || actions) && (
<div className="flex items-center justify-between p-4 border-b border-gray-200">
{title && <h2 className="font-semibold text-gray-700">{title}</h2>}
{actions && <div className="flex items-center">{actions}</div>}
</div>
)}
<div className="p-4">{children}</div>
</div>
);
}
- Implement Dashboard Page:
- Create the dashboard layout based on the mockup.
- Implement charts and statistics components.
- Connect to the API to fetch real data.
// src/app/dashboard/page.tsx
import { Card } from '@/components/ui/card';
import { StatCard } from '@/components/dashboard/stat-card';
import { PerformanceChart } from '@/components/dashboard/performance-chart';
import { ProductTable } from '@/components/dashboard/product-table';
import { MarketShareChart } from '@/components/dashboard/market-share-chart';
import { TrendsList } from '@/components/dashboard/trends-list';
export default async function DashboardPage() {
// Fetch data from API
const dashboardData = await fetch('/api/dashboard').then(res => res.json());
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-6">Dashboard</h1>
<div className="grid grid-cols-3 gap-6 mb-6">
<StatCard
title="Cash Balance"
value={dashboardData.cashBalance}
change={dashboardData.cashBalanceChange}
/>
<StatCard
title="Revenue"
value={dashboardData.revenue}
change={dashboardData.revenueChange}
/>
<StatCard
title="Market Share"
value={dashboardData.marketShare}
change={dashboardData.marketShareChange}
format="percent"
/>
</div>
<div className="grid grid-cols-3 gap-6 mb-6">
<Card title="Financial Performance" className="col-span-2">
<PerformanceChart data={dashboardData.financialPerformance} />
</Card>
<Card title="Market Segments">
<MarketShareChart data={dashboardData.marketSegments} />
</Card>
</div>
<Card title="Product Performance" className="mb-6">
<ProductTable products={dashboardData.products} />
</Card>
<div className="grid grid-cols-3 gap-6">
<Card title="Competitor Analysis" className="col-span-2">
<MarketShareChart data={dashboardData.competitorAnalysis} />
</Card>
<Card title="Market Trends">
<TrendsList trends={dashboardData.marketTrends} />
</Card>
</div>
</div>
);
}
-
Implement Market Analysis Page:
- Create the market analysis layout based on the mockup.
- Implement market segment visualization components.
- Connect to the API to fetch market data.
-
Implement Product Management Page:
- Create the product management layout based on the mockup.
- Implement product listing and detail components.
- Connect to the API to fetch and update product data.
-
Implement Decision Making Interfaces:
- Create forms and interfaces for making different types of decisions.
- Implement validation and submission logic.
- Connect to the API to submit decisions.
-
Implement Authentication and User Management:
- Set up NextAuth.js for authentication.
- Create login, registration, and profile pages.
- Implement role-based access control if needed.
-
Implement Data Visualization:
- Use Recharts to create interactive charts and graphs.
- Ensure responsive design for different screen sizes.
Example of a performance chart component:
// src/components/dashboard/performance-chart.tsx
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
ResponsiveContainer
} from 'recharts';
interface PerformanceChartProps {
data: {
period: string;
revenue: number;
costs: number;
profit: number;
}[];
}
export function PerformanceChart({ data }: PerformanceChartProps) {
return (
<div className="h-80">
<ResponsiveContainer width="100%" height="100%">
<LineChart
data={data}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="period" />
<YAxis />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey="revenue"
stroke="#4f46e5"
activeDot={{ r: 8 }}
/>
<Line type="monotone" dataKey="costs" stroke="#ef4444" />
<Line type="monotone" dataKey="profit" stroke="#10b981" />
</LineChart>
</ResponsiveContainer>
</div>
);
}
The application uses Cloudflare D1 (SQLite-compatible) for data storage. The database schema is defined in migration files and includes the following tables:
CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE simulations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
config TEXT NOT NULL, -- JSON configuration
current_period INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIM<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>
————
# Database Schema Design for Business Simulation Web App
This document provides a detailed database schema design for the business simulation web application. The schema is designed to support all the functionality described in the implementation guide, with a focus on flexibility, performance, and data integrity.
## Database Technology
The application uses **Cloudflare D1**, which is SQLite-compatible, as the primary database. This provides:
- Seamless integration with Cloudflare Workers
- Global distribution for low-latency access
- SQL compatibility for familiar query patterns
- Automatic scaling and high availability
## Schema Overview
The database schema consists of the following main tables:
1. **Users** - Store user account information
2. **Simulations** - Store simulation configurations and state
3. **Companies** - Store company data for each user in a simulation
4. **Products** - Store product information for each company
5. **Decisions** - Store decisions made by users for their companies
6. **Market Conditions** - Store market conditions for each period
7. **Performance Results** - Store performance metrics for each company
8. **Events** - Store random events that occur during the simulation
9. **Transactions** - Store financial transactions for each company
10. **Research Projects** - Store R&D projects for each company
## Detailed Schema
### Users Table
Stores user account information and authentication details.
```sql
CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
Stores simulation configurations and state.
CREATE TABLE simulations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
config TEXT NOT NULL, -- JSON configuration
current_period INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active', -- active, paused, completed
created_by TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (created_by) REFERENCES users(id)
);
CREATE INDEX idx_simulations_status ON simulations(status);
CREATE INDEX idx_simulations_created_by ON simulations(created_by);
Stores the relationship between users and simulations (many-to-many).
CREATE TABLE simulation_users (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'participant', -- admin, participant, observer
joined_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id),
FOREIGN KEY (user_id) REFERENCES users(id),
UNIQUE(simulation_id, user_id)
);
CREATE INDEX idx_simulation_users_simulation_id ON simulation_users(simulation_id);
CREATE INDEX idx_simulation_users_user_id ON simulation_users(user_id);
Stores company data for each user in a simulation.
CREATE TABLE companies (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
user_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
logo_url TEXT,
cash_balance REAL NOT NULL DEFAULT 1000000,
total_assets REAL NOT NULL DEFAULT 1000000,
total_liabilities REAL NOT NULL DEFAULT 0,
credit_rating TEXT NOT NULL DEFAULT 'B',
brand_value REAL NOT NULL DEFAULT 50, -- 0-100 scale
data TEXT NOT NULL, -- JSON data for additional properties
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id),
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE INDEX idx_companies_simulation_id ON companies(simulation_id);
CREATE INDEX idx_companies_user_id ON companies(user_id);
Stores product information for each company.
CREATE TABLE products (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
category TEXT NOT NULL, -- budget, mid-range, premium
quality_rating REAL NOT NULL DEFAULT 5, -- 0-10 scale
innovation_rating REAL NOT NULL DEFAULT 5, -- 0-10 scale
sustainability_rating REAL NOT NULL DEFAULT 5, -- 0-10 scale
production_cost REAL NOT NULL,
selling_price REAL NOT NULL,
inventory_level INTEGER NOT NULL DEFAULT 0,
production_capacity INTEGER NOT NULL DEFAULT 1000,
development_cost REAL NOT NULL DEFAULT 0,
marketing_budget REAL NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'development', -- development, active, discontinued
launch_period INTEGER,
discontinue_period INTEGER,
data TEXT NOT NULL, -- JSON data for additional properties
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE INDEX idx_products_company_id ON products(company_id);
CREATE INDEX idx_products_category ON products(category);
CREATE INDEX idx_products_status ON products(status);
Stores decisions made by users for their companies.
CREATE TABLE decisions (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
period INTEGER NOT NULL,
type TEXT NOT NULL, -- product_development, pricing, marketing, production, hr, r&d, finance
data TEXT NOT NULL, -- JSON data for decision details
submitted_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
processed BOOLEAN NOT NULL DEFAULT FALSE,
processed_at TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE INDEX idx_decisions_company_id ON decisions(company_id);
CREATE INDEX idx_decisions_period ON decisions(period);
CREATE INDEX idx_decisions_type ON decisions(type);
CREATE INDEX idx_decisions_processed ON decisions(processed);
Stores market conditions for each period.
CREATE TABLE market_conditions (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
period INTEGER NOT NULL,
total_market_size REAL NOT NULL,
segment_distribution TEXT NOT NULL, -- JSON data for segment distribution
economic_indicators TEXT NOT NULL, -- JSON data for economic indicators
consumer_preferences TEXT NOT NULL, -- JSON data for consumer preferences
technology_trends TEXT NOT NULL, -- JSON data for technology trends
sustainability_importance REAL NOT NULL, -- 0-1 scale
data TEXT NOT NULL, -- JSON data for additional properties
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id),
UNIQUE(simulation_id, period)
);
CREATE INDEX idx_market_conditions_simulation_id ON market_conditions(simulation_id);
CREATE INDEX idx_market_conditions_period ON market_conditions(period);
Stores performance metrics for each company in each period.
CREATE TABLE performance_results (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
period INTEGER NOT NULL,
revenue REAL NOT NULL DEFAULT 0,
costs REAL NOT NULL DEFAULT 0,
profit REAL NOT NULL DEFAULT 0,
market_share REAL NOT NULL DEFAULT 0,
cash_flow REAL NOT NULL DEFAULT 0,
roi REAL NOT NULL DEFAULT 0,
customer_satisfaction REAL NOT NULL DEFAULT 0, -- 0-100 scale
employee_satisfaction REAL NOT NULL DEFAULT 0, -- 0-100 scale
sustainability_score REAL NOT NULL DEFAULT 0, -- 0-100 scale
innovation_score REAL NOT NULL DEFAULT 0, -- 0-100 scale
brand_value_change REAL NOT NULL DEFAULT 0,
data TEXT NOT NULL, -- JSON data for additional metrics
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id),
UNIQUE(company_id, period)
);
CREATE INDEX idx_performance_results_company_id ON performance_results(company_id);
CREATE INDEX idx_performance_results_period ON performance_results(period);
Stores performance metrics for each product in each period.
CREATE TABLE product_performance (
id TEXT PRIMARY KEY,
product_id TEXT NOT NULL,
period INTEGER NOT NULL,
sales_volume INTEGER NOT NULL DEFAULT 0,
revenue REAL NOT NULL DEFAULT 0,
costs REAL NOT NULL DEFAULT 0,
profit REAL NOT NULL DEFAULT 0,
market_share REAL NOT NULL DEFAULT 0,
customer_satisfaction REAL NOT NULL DEFAULT 0, -- 0-100 scale
data TEXT NOT NULL, -- JSON data for additional metrics
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (product_id) REFERENCES products(id),
UNIQUE(product_id, period)
);
CREATE INDEX idx_product_performance_product_id ON product_performance(product_id);
CREATE INDEX idx_product_performance_period ON product_performance(period);
Stores random events that occur during the simulation.
CREATE TABLE events (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
period INTEGER NOT NULL,
type TEXT NOT NULL, -- economic, industry, company, global
name TEXT NOT NULL,
description TEXT NOT NULL,
impact_area TEXT NOT NULL, -- market, production, finance, etc.
impact_strength REAL NOT NULL, -- -1 to 1 scale (negative to positive)
affected_companies TEXT, -- JSON array of company IDs, NULL for all
data TEXT NOT NULL, -- JSON data for additional properties
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id)
);
CREATE INDEX idx_events_simulation_id ON events(simulation_id);
CREATE INDEX idx_events_period ON events(period);
CREATE INDEX idx_events_type ON events(type);
Stores financial transactions for each company.
CREATE TABLE transactions (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
period INTEGER NOT NULL,
type TEXT NOT NULL, -- revenue, cost, investment, loan, etc.
amount REAL NOT NULL,
description TEXT NOT NULL,
category TEXT NOT NULL, -- operations, marketing, r&d, etc.
reference_id TEXT, -- ID of related entity (product, decision, etc.)
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE INDEX idx_transactions_company_id ON transactions(company_id);
CREATE INDEX idx_transactions_period ON transactions(period);
CREATE INDEX idx_transactions_type ON transactions(type);
CREATE INDEX idx_transactions_category ON transactions(category);
Stores R&D projects for each company.
CREATE TABLE research_projects (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
name TEXT NOT NULL,
description TEXT,
type TEXT NOT NULL, -- product, process, technology
budget REAL NOT NULL,
start_period INTEGER NOT NULL,
duration INTEGER NOT NULL, -- number of periods
progress REAL NOT NULL DEFAULT 0, -- 0-100 scale
status TEXT NOT NULL DEFAULT 'active', -- active, completed, cancelled
results TEXT, -- JSON data for project results
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id)
);
CREATE INDEX idx_research_projects_company_id ON research_projects(company_id);
CREATE INDEX idx_research_projects_status ON research_projects(status);
Stores human resources data for each company.
CREATE TABLE human_resources (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
period INTEGER NOT NULL,
total_employees INTEGER NOT NULL DEFAULT 100,
average_salary REAL NOT NULL DEFAULT 50000,
training_budget REAL NOT NULL DEFAULT 0,
employee_satisfaction REAL NOT NULL DEFAULT 50, -- 0-100 scale
productivity REAL NOT NULL DEFAULT 1, -- multiplier
turnover_rate REAL NOT NULL DEFAULT 0.15, -- 0-1 scale
data TEXT NOT NULL, -- JSON data for additional properties
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id),
UNIQUE(company_id, period)
);
CREATE INDEX idx_human_resources_company_id ON human_resources(company_id);
CREATE INDEX idx_human_resources_period ON human_resources(period);
Stores marketing campaigns for each company.
CREATE TABLE marketing_campaigns (
id TEXT PRIMARY KEY,
company_id TEXT NOT NULL,
product_id TEXT,
name TEXT NOT NULL,
description TEXT,
budget REAL NOT NULL,
start_period INTEGER NOT NULL,
duration INTEGER NOT NULL, -- number of periods
target_segment TEXT NOT NULL, -- budget, mid-range, premium, all
channel_allocation TEXT NOT NULL, -- JSON data for channel allocation
effectiveness REAL, -- 0-100 scale, NULL until evaluated
status TEXT NOT NULL DEFAULT 'active', -- planned, active, completed
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (company_id) REFERENCES companies(id),
FOREIGN KEY (product_id) REFERENCES products(id)
);
CREATE INDEX idx_marketing_campaigns_company_id ON marketing_campaigns(company_id);
CREATE INDEX idx_marketing_campaigns_product_id ON marketing_campaigns(product_id);
CREATE INDEX idx_marketing_campaigns_status ON marketing_campaigns(status);
Stores actions taken by simulated competitors.
CREATE TABLE competitor_actions (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
competitor_id TEXT NOT NULL, -- ID of the simulated competitor
period INTEGER NOT NULL,
type TEXT NOT NULL, -- product_launch, price_change, marketing, etc.
data TEXT NOT NULL, -- JSON data for action details
in_response_to TEXT, -- ID of the player action this responds to, if any
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id)
);
CREATE INDEX idx_competitor_actions_simulation_id ON competitor_actions(simulation_id);
CREATE INDEX idx_competitor_actions_competitor_id ON competitor_actions(competitor_id);
CREATE INDEX idx_competitor_actions_period ON competitor_actions(period);
CREATE INDEX idx_competitor_actions_type ON competitor_actions(type);
Database migrations are managed using Wrangler's D1 migration system. Migrations are stored in the migrations
directory and applied using the Wrangler CLI.
The initial migration creates all the tables defined above:
-- migrations/0001_initial.sql
-- Users table
CREATE TABLE users (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'user',
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_users_email ON users(email);
-- Simulations table
CREATE TABLE simulations (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT,
config TEXT NOT NULL,
current_period INTEGER NOT NULL DEFAULT 0,
status TEXT NOT NULL DEFAULT 'active',
created_by TEXT NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (created_by) REFERENCES users(id)
);
CREATE INDEX idx_simulations_status ON simulations(status);
CREATE INDEX idx_simulations_created_by ON simulations(created_by);
-- Simulation Users table
CREATE TABLE simulation_users (
id TEXT PRIMARY KEY,
simulation_id TEXT NOT NULL,
user_id TEXT NOT NULL,
role TEXT NOT NULL DEFAULT 'participant',
joined_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (simulation_id) REFERENCES simulations(id),
FOREIGN KEY (user_id) REFERENCES users(id),
UNIQUE(simulation_id, user_id)
);
CREATE INDEX idx_simulation_users_simulation_id ON simulation_users(simulation_id);
CREATE INDEX idx_simulatio<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>
———
# API Documentation for Business Simulation Web App
This document provides comprehensive documentation for the API endpoints in the Business Simulation Web App. These endpoints enable interaction with the simulation engine, user management, and all other aspects of the application.
## Base URL
All API endpoints are relative to the base URL of your deployed application:
https://your-app-domain.com/api
For local development:
## Authentication
Most API endpoints require authentication. The application uses JWT-based authentication through NextAuth.js.
### Authentication Headers
Include the authentication token in the `Authorization` header:
Authorization: Bearer
The token is automatically included in requests when using the application's frontend. For direct API access, you'll need to obtain a token by logging in through the `/api/auth/login` endpoint.
## Response Format
All API responses follow a consistent format:
### Success Response
```json
{
"success": true,
"data": {
// Response data specific to the endpoint
}
}
{
"success": false,
"error": {
"code": "ERROR_CODE",
"message": "Human-readable error message",
"details": {
// Optional additional error details
}
}
}
Code | Description |
---|---|
UNAUTHORIZED |
Authentication required or invalid credentials |
FORBIDDEN |
User doesn't have permission for the requested action |
NOT_FOUND |
Requested resource not found |
VALIDATION_ERROR |
Invalid input data |
INTERNAL_ERROR |
Server-side error |
SIMULATION_ERROR |
Error in simulation processing |
POST /auth/register
Request Body:
{
"name": "John Doe",
"email": "[email protected]",
"password": "securepassword123"
}
Response:
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
}
}
}
POST /auth/login
Request Body:
{
"email": "[email protected]",
"password": "securepassword123"
}
Response:
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
},
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}
GET /auth/session
Response:
{
"success": true,
"data": {
"user": {
"id": "user_123",
"name": "John Doe",
"email": "[email protected]",
"role": "user"
}
}
}
GET /auth/logout
Response:
{
"success": true,
"data": {
"message": "Logged out successfully"
}
}
GET /simulations
Query Parameters:
Parameter | Type | Description |
---|---|---|
status |
string | Filter by status (active, paused, completed) |
limit |
number | Maximum number of results to return |
offset |
number | Number of results to skip |
Response:
{
"success": true,
"data": {
"simulations": [
{
"id": "sim_123",
"name": "Business Strategy Simulation",
"description": "A simulation focused on strategic decision-making",
"current_period": 3,
"status": "active",
"created_by": "user_456",
"created_at": "2025-01-15T12:00:00Z",
"updated_at": "2025-03-10T15:30:00Z"
},
// More simulations...
],
"total": 10,
"limit": 20,
"offset": 0
}
}
POST /simulations
Request Body:
{
"name": "Manufacturing Simulation",
"description": "A simulation focused on manufacturing operations",
"config": {
"initial_cash": 1000000,
"periods": 12,
"market_segments": ["budget", "mid-range", "premium"],
"difficulty": "medium",
"events_frequency": 0.3
}
}
Response:
{
"success": true,
"data": {
"simulation": {
"id": "sim_789",
"name": "Manufacturing Simulation",
"description": "A simulation focused on manufacturing operations",
"current_period": 0,
"status": "active",
"created_by": "user_123",
"created_at": "2025-03-18T10:45:00Z",
"updated_at": "2025-03-18T10:45:00Z",
"config": {
"initial_cash": 1000000,
"periods": 12,
"market_segments": ["budget", "mid-range", "premium"],
"difficulty": "medium",
"events_frequency": 0.3
}
}
}
}
GET /simulations/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Simulation ID |
Response:
{
"success": true,
"data": {
"simulation": {
"id": "sim_123",
"name": "Business Strategy Simulation",
"description": "A simulation focused on strategic decision-making",
"current_period": 3,
"status": "active",
"created_by": "user_456",
"created_at": "2025-01-15T12:00:00Z",
"updated_at": "2025-03-10T15:30:00Z",
"config": {
"initial_cash": 1000000,
"periods": 12,
"market_segments": ["budget", "mid-range", "premium"],
"difficulty": "medium",
"events_frequency": 0.3
}
}
}
}
PUT /simulations/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Simulation ID |
Request Body:
{
"name": "Updated Simulation Name",
"description": "Updated description",
"status": "paused"
}
Response:
{
"success": true,
"data": {
"simulation": {
"id": "sim_123",
"name": "Updated Simulation Name",
"description": "Updated description",
"current_period": 3,
"status": "paused",
"created_by": "user_456",
"created_at": "2025-01-15T12:00:00Z",
"updated_at": "2025-03-18T10:50:00Z",
"config": {
"initial_cash": 1000000,
"periods": 12,
"market_segments": ["budget", "mid-range", "premium"],
"difficulty": "medium",
"events_frequency": 0.3
}
}
}
}
DELETE /simulations/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Simulation ID |
Response:
{
"success": true,
"data": {
"message": "Simulation deleted successfully"
}
}
POST /simulations/:id/join
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Simulation ID |
Request Body:
{
"role": "participant" // Optional, defaults to "participant"
}
Response:
{
"success": true,
"data": {
"message": "Joined simulation successfully",
"simulation_user": {
"id": "sim_user_123",
"simulation_id": "sim_123",
"user_id": "user_123",
"role": "participant",
"joined_at": "2025-03-18T10:55:00Z"
}
}
}
POST /simulations/:id/advance
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Simulation ID |
Response:
{
"success": true,
"data": {
"message": "Advanced to next period successfully",
"simulation": {
"id": "sim_123",
"name": "Business Strategy Simulation",
"current_period": 4,
"status": "active",
"updated_at": "2025-03-18T11:00:00Z"
},
"market_conditions": {
"id": "market_123",
"simulation_id": "sim_123",
"period": 4,
"total_market_size": 5200000,
// More market data...
}
}
}
GET /companies
Query Parameters:
Parameter | Type | Description |
---|---|---|
simulation_id |
string | Filter by simulation ID |
Response:
{
"success": true,
"data": {
"companies": [
{
"id": "company_123",
"simulation_id": "sim_123",
"user_id": "user_123",
"name": "TechInnovate Inc.",
"description": "A technology innovation company",
"logo_url": "https://example.com/logo.png",
"cash_balance": 1245000,
"total_assets": 2500000,
"total_liabilities": 800000,
"credit_rating": "A",
"brand_value": 75,
"created_at": "2025-01-15T12:30:00Z",
"updated_at": "2025-03-10T16:00:00Z",
"data": {
"mission_statement": "To innovate and transform technology",
"competitive_strategy": "differentiator"
}
},
// More companies...
]
}
}
POST /companies
Request Body:
{
"simulation_id": "sim_123",
"name": "Global Widgets Ltd.",
"description": "A widget manufacturing company",
"logo_url": "https://example.com/widgets-logo.png",
"data": {
"mission_statement": "To provide high-quality widgets worldwide",
"competitive_strategy": "cost_leader"
}
}
Response:
{
"success": true,
"data": {
"company": {
"id": "company_456",
"simulation_id": "sim_123",
"user_id": "user_123",
"name": "Global Widgets Ltd.",
"description": "A widget manufacturing company",
"logo_url": "https://example.com/widgets-logo.png",
"cash_balance": 1000000,
"total_assets": 1000000,
"total_liabilities": 0,
"credit_rating": "B",
"brand_value": 50,
"created_at": "2025-03-18T11:05:00Z",
"updated_at": "2025-03-18T11:05:00Z",
"data": {
"mission_statement": "To provide high-quality widgets worldwide",
"competitive_strategy": "cost_leader"
}
}
}
}
GET /companies/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Company ID |
Response:
{
"success": true,
"data": {
"company": {
"id": "company_123",
"simulation_id": "sim_123",
"user_id": "user_123",
"name": "TechInnovate Inc.",
"description": "A technology innovation company",
"logo_url": "https://example.com/logo.png",
"cash_balance": 1245000,
"total_assets": 2500000,
"total_liabilities": 800000,
"credit_rating": "A",
"brand_value": 75,
"created_at": "2025-01-15T12:30:00Z",
"updated_at": "2025-03-10T16:00:00Z",
"data": {
"mission_statement": "To innovate and transform technology",
"competitive_strategy": "differentiator"
}
}
}
}
PUT /companies/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Company ID |
Request Body:
{
"name": "TechInnovate Global",
"description": "A global technology innovation company",
"data": {
"mission_statement": "To innovate and transform technology globally",
"values": ["Innovation", "Integrity", "Excellence"]
}
}
Response:
{
"success": true,
"data": {
"company": {
"id": "company_123",
"simulation_id": "sim_123",
"user_id": "user_123",
"name": "TechInnovate Global",
"description": "A global technology innovation company",
"logo_url": "https://example.com/logo.png",
"cash_balance": 1245000,
"total_assets": 2500000,
"total_liabilities": 800000,
"credit_rating": "A",
"brand_value": 75,
"created_at": "2025-01-15T12:30:00Z",
"updated_at": "2025-03-18T11:10:00Z",
"data": {
"mission_statement": "To innovate and transform technology globally",
"competitive_strategy": "differentiator",
"values": ["Innovation", "Integrity", "Excellence"]
}
}
}
}
DELETE /companies/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Company ID |
Response:
{
"success": true,
"data": {
"message": "Company deleted successfully"
}
}
GET /products
Query Parameters:
Parameter | Type | Description |
---|---|---|
company_id |
string | Filter by company ID (required) |
status |
string | Filter by status (development, active, discontinued) |
category |
string | Filter by category (budget, mid-range, premium) |
Response:
{
"success": true,
"data": {
"products": [
{
"id": "product_123",
"company_id": "company_123",
"name": "Premium Widget",
"description": "Our flagship premium widget",
"category": "premium",
"quality_rating": 8.5,
"innovation_rating": 7.2,
"sustainability_rating": 6.8,
"production_cost": 150,
"selling_price": 300,
"inventory_level": 500,
"production_capacity": 1000,
"development_cost": 500000,
"marketing_budget": 100000,
"status": "active",
"launch_period": 2,
"discontinue_period": null,
"created_at": "2025-01-20T09:00:00Z",
"updated_at": "2025-03-10T16:30:00Z",
"data": {
"features": ["Advanced AI", "Premium Materials", "Extended Warranty"],
"target_audience": "High-income professionals"
}
},
// More products...
]
}
}
POST /products
Request Body:
{
"company_id": "company_123",
"name": "Standard Widget",
"description": "Our mid-range widget offering",
"category": "mid-range",
"quality_rating": 6.5,
"innovation_rating": 5.8,
"sustainability_rating": 6.0,
"production_cost": 75,
"selling_price": 150,
"development_cost": 300000,
"marketing_budget": 50000,
"data": {
"features": ["Reliable Performance", "Good Value"],
"target_audience": "Middle-income consumers"
}
}
Response:
{
"success": true,
"data": {
"product": {
"id": "product_456",
"company_id": "company_123",
"name": "Standard Widget",
"description": "Our mid-range widget offering",
"category": "mid-range",
"quality_rating": 6.5,
"innovation_rating": 5.8,
"sustainability_rating": 6.0,
"production_cost": 75,
"selling_price": 150,
"inventory_level": 0,
"production_capacity": 1000,
"development_cost": 300000,
"marketing_budget": 50000,
"status": "development",
"launch_period": null,
"discontinue_period": null,
"created_at": "2025-03-18T11:15:00Z",
"updated_at": "2025-03-18T11:15:00Z",
"data": {
"features": ["Reliable Performance", "Good Value"],
"target_audience": "Middle-income consumers"
}
}
}
}
GET /products/:id
Path Parameters:
Parameter | Type | Description |
---|---|---|
id |
string | Product ID |
Response:
{
"success": true,
"data": {
"product": {
"id": "product_123",
"company_id": "company_123",
"name": "Premium Widget",
"description": "Our flagship premium widget",
"category": "premium",
"quality_rating": 8.5,
"innovation_rating": 7.2,
"sustainability_rating": 6.8,
"production_cost": 150,
"selling_price": 300,
"inventory_level": 500,
"production_capacity": 1000,
<response clipped><NOTE>To save on context only part of this file has been shown to you. You should retry this tool after you have searched inside the file with `grep -n` in order to find the line numbers of what you are looking for.</NOTE>
———
# Business Simulation Web App - Project Overview
This document provides an overview of the Business Simulation Web App project, including the structure of the deliverables and instructions for implementation.
## Project Structure
The project deliverables are organized into the following directories:
1. **business_simulation_analysis/** - Analysis of existing business simulation applications
- analysis.md - Detailed analysis of the 13 business simulation applications
- features.md - Key features identified across the applications
- requirements.md - Requirements for our business simulation web app
2. **business_simulation_app_design/** - Architecture and design documents
- architecture.md - Overall architecture of the web application
- data_model.md - Data model design
- component_structure.md - UI component structure
3. **business_simulation_prototype/** - Prototype implementation
- **simulation_engine/** - Core simulation engine prototype
- simulation_core.py - Core simulation logic
- decision_types.py - Decision type definitions
- market_dynamics.py - Market simulation logic
- **ui_mockups/** - HTML mockups of key UI components
- dashboard.html - Dashboard UI mockup
- product_management.html - Product management UI mockup
- market_analysis.html - Market analysis UI mockup
- **implementation_guidelines/** - Implementation documentation
- implementation_guide.md - Comprehensive implementation guide
- database_schema.md - Database schema design
- api_documentation.md - API endpoint documentation
## Getting Started
To implement the Business Simulation Web App, follow these steps:
1. Review the analysis documents to understand the requirements and features
2. Study the architecture and design documents to understand the system structure
3. Examine the simulation engine prototype to understand the core business logic
4. Review the UI mockups to understand the user interface design
5. Follow the implementation guidelines to build the application
## Implementation Path
The recommended implementation path is:
1. Set up the development environment using Next.js
2. Implement the database schema
3. Convert the simulation engine from Python to TypeScript
4. Implement the API endpoints
5. Develop the UI components based on the mockups
6. Integrate all components
7. Test the application
8. Deploy to production
## Key Features
The Business Simulation Web App includes the following key features:
1. **Comprehensive Business Simulation Engine**
- Market dynamics modeling
- Competitor behavior simulation
- Financial performance calculation
- Multi-period simulation
2. **Strategic Decision Making**
- Product development decisions
- Pricing decisions
- Marketing decisions
- Production decisions
- HR decisions
- R&D decisions
- Financial decisions
3. **Interactive Dashboard**
- Financial performance metrics
- Market share analysis
- Product performance tracking
- Competitor analysis
4. **Market Analysis Tools**
- Market segment analysis
- Consumer preferences tracking
- Economic indicators
- Market trends
5. **Product Management**
- Product development
- Product lifecycle management
- Production planning
- Quality management
## Technology Stack
The application is designed to be built with:
- **Frontend**: React with Next.js, Tailwind CSS
- **Backend**: Next.js API routes
- **Database**: Cloudflare D1 (SQLite-compatible)
- **Deployment**: Cloudflare Pages